Compare commits

..

1 Commits

Author SHA1 Message Date
Francisco Gaona
cddbd09f0f WIP - scaffold approvals 2026-01-16 23:27:09 +01:00
67 changed files with 2498 additions and 4932 deletions

View File

@@ -1,5 +1,5 @@
NUXT_PORT=3001
NUXT_HOST=0.0.0.0
# Nitro BFF backend URL (server-only, not exposed to client)
BACKEND_URL=https://backend.routebox.co
# Point Nuxt to the API container (not localhost)
NUXT_PUBLIC_API_BASE_URL=https://tenant1.routebox.co

View File

@@ -1,95 +0,0 @@
/**
* @param { import("knex").Knex } knex
* @returns { Promise<void> }
*/
exports.up = async function(knex) {
// Check if layout_type column already exists (in case of partial migration)
const hasLayoutType = await knex.schema.hasColumn('page_layouts', 'layout_type');
// Check if the old index exists
const [indexes] = await knex.raw(`SHOW INDEX FROM page_layouts WHERE Key_name = 'page_layouts_object_id_is_default_index'`);
const hasOldIndex = indexes.length > 0;
// Check if foreign key exists
const [fks] = await knex.raw(`
SELECT CONSTRAINT_NAME FROM information_schema.TABLE_CONSTRAINTS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'page_layouts'
AND CONSTRAINT_TYPE = 'FOREIGN KEY'
AND CONSTRAINT_NAME = 'page_layouts_object_id_foreign'
`);
const hasForeignKey = fks.length > 0;
if (hasOldIndex) {
// First, drop the foreign key constraint that depends on the index (if it exists)
if (hasForeignKey) {
await knex.schema.alterTable('page_layouts', (table) => {
table.dropForeign(['object_id']);
});
}
// Now we can safely drop the old index
await knex.schema.alterTable('page_layouts', (table) => {
table.dropIndex(['object_id', 'is_default']);
});
}
// Add layout_type column if it doesn't exist
if (!hasLayoutType) {
await knex.schema.alterTable('page_layouts', (table) => {
// Add layout_type column to distinguish between detail/edit layouts and list view layouts
// Default to 'detail' for existing layouts
table.enum('layout_type', ['detail', 'list']).notNullable().defaultTo('detail').after('name');
});
}
// Check if new index exists
const [newIndexes] = await knex.raw(`SHOW INDEX FROM page_layouts WHERE Key_name = 'page_layouts_object_id_layout_type_is_default_index'`);
const hasNewIndex = newIndexes.length > 0;
if (!hasNewIndex) {
// Create new index including layout_type
await knex.schema.alterTable('page_layouts', (table) => {
table.index(['object_id', 'layout_type', 'is_default']);
});
}
// Re-check if foreign key exists (may have been dropped above or in previous attempt)
const [fksAfter] = await knex.raw(`
SELECT CONSTRAINT_NAME FROM information_schema.TABLE_CONSTRAINTS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'page_layouts'
AND CONSTRAINT_TYPE = 'FOREIGN KEY'
AND CONSTRAINT_NAME = 'page_layouts_object_id_foreign'
`);
if (fksAfter.length === 0) {
// Re-add the foreign key constraint
await knex.schema.alterTable('page_layouts', (table) => {
table.foreign('object_id').references('id').inTable('object_definitions').onDelete('CASCADE');
});
}
};
/**
* @param { import("knex").Knex } knex
* @returns { Promise<void> }
*/
exports.down = async function(knex) {
// Drop the foreign key first
await knex.schema.alterTable('page_layouts', (table) => {
table.dropForeign(['object_id']);
});
// Drop the new index and column, restore old index
await knex.schema.alterTable('page_layouts', (table) => {
table.dropIndex(['object_id', 'layout_type', 'is_default']);
table.dropColumn('layout_type');
table.index(['object_id', 'is_default']);
});
// Re-add the foreign key constraint
await knex.schema.alterTable('page_layouts', (table) => {
table.foreign('object_id').references('id').inTable('object_definitions').onDelete('CASCADE');
});
};

View File

@@ -0,0 +1,190 @@
exports.up = async function (knex) {
await knex.schema.createTable('approval_definitions', (table) => {
table.string('id', 191).primary().defaultTo(knex.raw('(UUID())'));
table.string('name', 191).notNullable();
table.text('description');
table.string('triggerType', 191).notNullable();
table.string('targetObjectType', 191);
table.json('entryCriteria');
table.json('steps');
table.json('votingPolicy');
table.string('rejectionRule', 191);
table.string('materialChangePolicy', 191);
table.integer('version').notNullable().defaultTo(1);
table.boolean('isActive').notNullable().defaultTo(true);
table.timestamp('createdAt').notNullable().defaultTo(knex.fn.now());
table.timestamp('updatedAt').notNullable().defaultTo(knex.fn.now());
});
await knex.schema.createTable('approval_requests', (table) => {
table.string('id', 191).primary().defaultTo(knex.raw('(UUID())'));
table.string('definitionId', 191).notNullable();
table.string('status', 191).notNullable().defaultTo('pending');
table.string('targetObjectType', 191).notNullable();
table.string('targetObjectId', 191).notNullable();
table.string('action', 191);
table.string('stateFrom', 191);
table.string('stateTo', 191);
table.json('fieldChanges');
table.json('snapshot');
table.string('versionHash', 191);
table.string('submittedById', 191);
table.timestamp('submittedAt');
table.string('currentStepKey', 191);
table.timestamp('createdAt').notNullable().defaultTo(knex.fn.now());
table.timestamp('updatedAt').notNullable().defaultTo(knex.fn.now());
table.index(['definitionId']);
table.index(['targetObjectType', 'targetObjectId']);
table.index(['submittedById']);
table
.foreign('definitionId')
.references('id')
.inTable('approval_definitions')
.onDelete('CASCADE')
.onUpdate('CASCADE');
table
.foreign('submittedById')
.references('id')
.inTable('users')
.onDelete('SET NULL')
.onUpdate('CASCADE');
});
await knex.schema.createTable('approval_steps', (table) => {
table.string('id', 191).primary().defaultTo(knex.raw('(UUID())'));
table.string('requestId', 191).notNullable();
table.string('stepKey', 191).notNullable();
table.string('name', 191).notNullable();
table.integer('stepOrder').notNullable();
table.string('status', 191).notNullable().defaultTo('pending');
table.json('routing');
table.json('voting');
table.timestamp('dueAt');
table.timestamp('completedAt');
table.timestamp('createdAt').notNullable().defaultTo(knex.fn.now());
table.timestamp('updatedAt').notNullable().defaultTo(knex.fn.now());
table.index(['requestId']);
table.index(['status']);
table
.foreign('requestId')
.references('id')
.inTable('approval_requests')
.onDelete('CASCADE')
.onUpdate('CASCADE');
});
await knex.schema.createTable('approval_assignments', (table) => {
table.string('id', 191).primary().defaultTo(knex.raw('(UUID())'));
table.string('stepId', 191).notNullable();
table.string('assigneeId', 191).notNullable();
table.string('status', 191).notNullable().defaultTo('pending');
table.text('response');
table.timestamp('respondedAt');
table.timestamp('dueAt');
table.string('reassignedFromId', 191);
table.string('delegatedById', 191);
table.timestamp('createdAt').notNullable().defaultTo(knex.fn.now());
table.timestamp('updatedAt').notNullable().defaultTo(knex.fn.now());
table.index(['stepId']);
table.index(['assigneeId']);
table.index(['status']);
table
.foreign('stepId')
.references('id')
.inTable('approval_steps')
.onDelete('CASCADE')
.onUpdate('CASCADE');
table
.foreign('assigneeId')
.references('id')
.inTable('users')
.onDelete('RESTRICT')
.onUpdate('CASCADE');
table
.foreign('reassignedFromId')
.references('id')
.inTable('users')
.onDelete('SET NULL')
.onUpdate('CASCADE');
table
.foreign('delegatedById')
.references('id')
.inTable('users')
.onDelete('SET NULL')
.onUpdate('CASCADE');
});
await knex.schema.createTable('approval_effect_logs', (table) => {
table.string('id', 191).primary().defaultTo(knex.raw('(UUID())'));
table.string('requestId', 191).notNullable();
table.string('effectKey', 191).notNullable();
table.string('status', 191).notNullable().defaultTo('success');
table.json('response');
table.timestamp('executedAt').notNullable().defaultTo(knex.fn.now());
table.unique(['requestId', 'effectKey']);
table.index(['requestId']);
table
.foreign('requestId')
.references('id')
.inTable('approval_requests')
.onDelete('CASCADE')
.onUpdate('CASCADE');
});
await knex.schema.createTable('tasks', (table) => {
table.string('id', 191).primary().defaultTo(knex.raw('(UUID())'));
table.string('title', 191).notNullable();
table.text('description');
table.string('status', 191).notNullable().defaultTo('open');
table.string('priority', 191);
table.timestamp('dueAt');
table.string('assignedToId', 191);
table.string('relatedObjectType', 191);
table.string('relatedObjectId', 191);
table.timestamp('createdAt').notNullable().defaultTo(knex.fn.now());
table.timestamp('updatedAt').notNullable().defaultTo(knex.fn.now());
table.index(['assignedToId']);
table.index(['relatedObjectType', 'relatedObjectId']);
table
.foreign('assignedToId')
.references('id')
.inTable('users')
.onDelete('SET NULL')
.onUpdate('CASCADE');
});
await knex.schema.createTable('activity_logs', (table) => {
table.string('id', 191).primary().defaultTo(knex.raw('(UUID())'));
table.string('action', 191).notNullable();
table.string('subjectType', 191).notNullable();
table.string('subjectId', 191).notNullable();
table.text('description');
table.json('properties');
table.string('causerId', 191);
table.timestamp('createdAt').notNullable().defaultTo(knex.fn.now());
table.index(['subjectType', 'subjectId']);
table.index(['causerId']);
table
.foreign('causerId')
.references('id')
.inTable('users')
.onDelete('SET NULL')
.onUpdate('CASCADE');
});
};
exports.down = async function (knex) {
await knex.schema.dropTableIfExists('activity_logs');
await knex.schema.dropTableIfExists('tasks');
await knex.schema.dropTableIfExists('approval_effect_logs');
await knex.schema.dropTableIfExists('approval_assignments');
await knex.schema.dropTableIfExists('approval_steps');
await knex.schema.dropTableIfExists('approval_requests');
await knex.schema.dropTableIfExists('approval_definitions');
};

View File

@@ -11,7 +11,7 @@
"dependencies": {
"@casl/ability": "^6.7.5",
"@fastify/websocket": "^10.0.1",
"@langchain/core": "^1.1.15",
"@langchain/core": "^1.1.12",
"@langchain/langgraph": "^1.0.15",
"@langchain/openai": "^1.2.1",
"@nestjs/bullmq": "^10.1.0",
@@ -29,10 +29,9 @@
"bullmq": "^5.1.0",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.1",
"deepagents": "^1.5.0",
"ioredis": "^5.3.2",
"knex": "^3.1.0",
"langchain": "^1.2.10",
"langchain": "^1.2.7",
"mysql2": "^3.15.3",
"objection": "^3.1.5",
"openai": "^6.15.0",
@@ -229,26 +228,6 @@
"tslib": "^2.1.0"
}
},
"node_modules/@anthropic-ai/sdk": {
"version": "0.71.2",
"resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.71.2.tgz",
"integrity": "sha512-TGNDEUuEstk/DKu0/TflXAEt+p+p/WhTlFzEnoosvbaDU2LTjm42igSdlL0VijrKpWejtOKxX0b8A7uc+XiSAQ==",
"license": "MIT",
"dependencies": {
"json-schema-to-ts": "^3.1.1"
},
"bin": {
"anthropic-ai-sdk": "bin/cli"
},
"peerDependencies": {
"zod": "^3.25.0 || ^4.0.0"
},
"peerDependenciesMeta": {
"zod": {
"optional": true
}
}
},
"node_modules/@babel/code-frame": {
"version": "7.27.1",
"resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.27.1.tgz",
@@ -710,15 +689,6 @@
"@babel/core": "^7.0.0-0"
}
},
"node_modules/@babel/runtime": {
"version": "7.28.6",
"resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.28.6.tgz",
"integrity": "sha512-05WQkdpL9COIMz4LjTxGpPNCdlpyimKppYNoJ5Di5EUObifl8t4tuLuUBBZEpoLYOmfvIWrsp9fCl0HoPRVTdA==",
"license": "MIT",
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/template": {
"version": "7.27.2",
"resolved": "https://registry.npmjs.org/@babel/template/-/template-7.27.2.tgz",
@@ -1719,26 +1689,10 @@
"@jridgewell/sourcemap-codec": "^1.4.14"
}
},
"node_modules/@langchain/anthropic": {
"version": "1.3.10",
"resolved": "https://registry.npmjs.org/@langchain/anthropic/-/anthropic-1.3.10.tgz",
"integrity": "sha512-VXq5fsEJ4FB5XGrnoG+bfm0I7OlmYLI4jZ6cX9RasyqhGo9wcDyKw1+uEQ1H7Og7jWrTa1bfXCun76wttewJnw==",
"license": "MIT",
"dependencies": {
"@anthropic-ai/sdk": "^0.71.0",
"zod": "^3.25.76 || ^4"
},
"engines": {
"node": ">=20"
},
"peerDependencies": {
"@langchain/core": "1.1.15"
}
},
"node_modules/@langchain/core": {
"version": "1.1.15",
"resolved": "https://registry.npmjs.org/@langchain/core/-/core-1.1.15.tgz",
"integrity": "sha512-b8RN5DkWAmDAlMu/UpTZEluYwCLpm63PPWniRKlE8ie3KkkE7IuMQ38pf4kV1iaiI+d99BEQa2vafQHfCujsRA==",
"version": "1.1.12",
"resolved": "https://registry.npmjs.org/@langchain/core/-/core-1.1.12.tgz",
"integrity": "sha512-sHWLvhyLi3fntlg3MEPB89kCjxEX7/+imlIYJcp6uFGCAZfGxVWklqp22HwjT1szorUBYrkO8u0YA554ReKxGQ==",
"license": "MIT",
"dependencies": {
"@cfworker/json-schema": "^4.0.2",
@@ -2533,6 +2487,7 @@
"version": "2.1.5",
"resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz",
"integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==",
"dev": true,
"license": "MIT",
"dependencies": {
"@nodelib/fs.stat": "2.0.5",
@@ -2546,6 +2501,7 @@
"version": "2.0.5",
"resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz",
"integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 8"
@@ -2555,6 +2511,7 @@
"version": "1.2.8",
"resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz",
"integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@nodelib/fs.scandir": "2.1.5",
@@ -4072,6 +4029,7 @@
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz",
"integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==",
"dev": true,
"license": "MIT",
"dependencies": {
"fill-range": "^7.1.1"
@@ -4796,22 +4754,6 @@
"dev": true,
"license": "MIT"
},
"node_modules/deepagents": {
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/deepagents/-/deepagents-1.5.0.tgz",
"integrity": "sha512-tjZLOISPMpqfk+k/iE1uIZavXW9j4NrhopUmH5ARqzmk95EEtGDyN++tgnY+tdVOOZTjE2LHjOVV7or58dtx8A==",
"license": "MIT",
"dependencies": {
"@langchain/anthropic": "^1.3.7",
"@langchain/core": "^1.1.12",
"@langchain/langgraph": "^1.0.14",
"fast-glob": "^3.3.3",
"langchain": "^1.2.7",
"micromatch": "^4.0.8",
"yaml": "^2.8.2",
"zod": "^4.3.5"
}
},
"node_modules/deepmerge": {
"version": "4.3.1",
"resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.1.tgz",
@@ -5572,6 +5514,7 @@
"version": "3.3.3",
"resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz",
"integrity": "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@nodelib/fs.stat": "^2.0.2",
@@ -5797,6 +5740,7 @@
"version": "7.1.1",
"resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz",
"integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==",
"dev": true,
"license": "MIT",
"dependencies": {
"to-regex-range": "^5.0.1"
@@ -6201,6 +6145,7 @@
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz",
"integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==",
"dev": true,
"license": "ISC",
"dependencies": {
"is-glob": "^4.0.1"
@@ -6649,6 +6594,7 @@
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz",
"integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=0.10.0"
@@ -6677,6 +6623,7 @@
"version": "4.0.3",
"resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz",
"integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==",
"dev": true,
"license": "MIT",
"dependencies": {
"is-extglob": "^2.1.1"
@@ -6711,6 +6658,7 @@
"version": "7.0.0",
"resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz",
"integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=0.12.0"
@@ -7661,19 +7609,6 @@
"fast-deep-equal": "^3.1.3"
}
},
"node_modules/json-schema-to-ts": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/json-schema-to-ts/-/json-schema-to-ts-3.1.1.tgz",
"integrity": "sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g==",
"license": "MIT",
"dependencies": {
"@babel/runtime": "^7.18.3",
"ts-algebra": "^2.0.0"
},
"engines": {
"node": ">=16"
}
},
"node_modules/json-schema-traverse": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",
@@ -7876,9 +7811,9 @@
}
},
"node_modules/langchain": {
"version": "1.2.10",
"resolved": "https://registry.npmjs.org/langchain/-/langchain-1.2.10.tgz",
"integrity": "sha512-9uVxOJE/RTECvNutQfOLwH7f6R9mcq0G/IMHwA2eptDA86R/Yz2zWMz4vARVFPxPrdSJ9nJFDPAqRQlRFwdHBw==",
"version": "1.2.7",
"resolved": "https://registry.npmjs.org/langchain/-/langchain-1.2.7.tgz",
"integrity": "sha512-G+3Ftz/08CurJaE7LukQGBf3mCSz7XM8LZeAaFPg391Ru4lT8eLYfG6Fv4ZI0u6EBsPVcOQfaS9ig8nCRmJeqA==",
"license": "MIT",
"dependencies": {
"@langchain/langgraph": "^1.0.0",
@@ -7891,7 +7826,7 @@
"node": ">=20"
},
"peerDependencies": {
"@langchain/core": "1.1.15"
"@langchain/core": "1.1.12"
}
},
"node_modules/langchain/node_modules/uuid": {
@@ -8266,6 +8201,7 @@
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz",
"integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 8"
@@ -8275,6 +8211,7 @@
"version": "4.0.8",
"resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz",
"integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==",
"dev": true,
"license": "MIT",
"dependencies": {
"braces": "^3.0.3",
@@ -8288,6 +8225,7 @@
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz",
"integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8.6"
@@ -9450,6 +9388,7 @@
"version": "1.2.3",
"resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz",
"integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==",
"dev": true,
"funding": [
{
"type": "github",
@@ -9788,6 +9727,7 @@
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz",
"integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==",
"dev": true,
"funding": [
{
"type": "github",
@@ -10717,6 +10657,7 @@
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz",
"integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"is-number": "^7.0.0"
@@ -10768,12 +10709,6 @@
"tree-kill": "cli.js"
}
},
"node_modules/ts-algebra": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/ts-algebra/-/ts-algebra-2.0.0.tgz",
"integrity": "sha512-FPAhNPFMrkwz76P7cdjdmiShwMynZYN6SgOujD1urY4oNm80Ou9oMdmbR45LotcKOXoy7wSmHkRFE6Mxbrhefw==",
"license": "MIT"
},
"node_modules/ts-api-utils": {
"version": "1.4.3",
"resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-1.4.3.tgz",
@@ -11520,21 +11455,6 @@
"dev": true,
"license": "ISC"
},
"node_modules/yaml": {
"version": "2.8.2",
"resolved": "https://registry.npmjs.org/yaml/-/yaml-2.8.2.tgz",
"integrity": "sha512-mplynKqc1C2hTVYxd0PU2xQAc22TI1vShAYGksCCfxbn/dFwnHTNi1bvYsBTkhdUNtGIf5xNOg938rrSSYvS9A==",
"license": "ISC",
"bin": {
"yaml": "bin.mjs"
},
"engines": {
"node": ">= 14.6"
},
"funding": {
"url": "https://github.com/sponsors/eemeli"
}
},
"node_modules/yargs": {
"version": "17.7.2",
"resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz",
@@ -11588,9 +11508,9 @@
}
},
"node_modules/zod": {
"version": "4.3.5",
"resolved": "https://registry.npmjs.org/zod/-/zod-4.3.5.tgz",
"integrity": "sha512-k7Nwx6vuWx1IJ9Bjuf4Zt1PEllcwe7cls3VNzm4CQ1/hgtFUK2bRNG3rvnpPUhFjmqJKAKtjV576KnUkHocg/g==",
"version": "3.25.76",
"resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",
"integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/colinhacks"

View File

@@ -28,7 +28,7 @@
"dependencies": {
"@casl/ability": "^6.7.5",
"@fastify/websocket": "^10.0.1",
"@langchain/core": "^1.1.15",
"@langchain/core": "^1.1.12",
"@langchain/langgraph": "^1.0.15",
"@langchain/openai": "^1.2.1",
"@nestjs/bullmq": "^10.1.0",
@@ -46,10 +46,9 @@
"bullmq": "^5.1.0",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.1",
"deepagents": "^1.5.0",
"ioredis": "^5.3.2",
"knex": "^3.1.0",
"langchain": "^1.2.10",
"langchain": "^1.2.7",
"mysql2": "^3.15.3",
"objection": "^3.1.5",
"openai": "^6.15.0",

View File

@@ -0,0 +1,42 @@
import { Controller, Get, Post, Body, Query, UseGuards } from '@nestjs/common';
import { ActivityLogService } from './activity-log.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { TenantId } from '../tenant/tenant.decorator';
@Controller('activity-log')
@UseGuards(JwtAuthGuard)
export class ActivityLogController {
constructor(private activityLogService: ActivityLogService) {}
@Get()
async listActivities(
@TenantId() tenantId: string,
@Query('subjectType') subjectType?: string,
@Query('subjectId') subjectId?: string,
@Query('causerId') causerId?: string,
@Query('action') action?: string,
) {
return this.activityLogService.listActivities(tenantId, {
subjectType,
subjectId,
causerId,
action,
});
}
@Post()
async createActivity(
@TenantId() tenantId: string,
@Body()
body: {
action: string;
subjectType: string;
subjectId: string;
description?: string;
properties?: Record<string, any>;
causerId?: string;
},
) {
return this.activityLogService.logActivity(tenantId, body);
}
}

View File

@@ -0,0 +1,12 @@
import { Module } from '@nestjs/common';
import { ActivityLogController } from './activity-log.controller';
import { ActivityLogService } from './activity-log.service';
import { TenantModule } from '../tenant/tenant.module';
@Module({
imports: [TenantModule],
controllers: [ActivityLogController],
providers: [ActivityLogService],
exports: [ActivityLogService],
})
export class ActivityLogModule {}

View File

@@ -0,0 +1,54 @@
import { Injectable } from '@nestjs/common';
import { TenantDatabaseService } from '../tenant/tenant-database.service';
import { ActivityLog } from '../models/activity-log.model';
export interface ActivityLogInput {
action: string;
subjectType: string;
subjectId: string;
description?: string;
properties?: Record<string, any>;
causerId?: string | null;
}
@Injectable()
export class ActivityLogService {
constructor(private tenantDbService: TenantDatabaseService) {}
private async getKnex(tenantId: string) {
const resolved = await this.tenantDbService.resolveTenantId(tenantId);
return this.tenantDbService.getTenantKnexById(resolved);
}
async logActivity(tenantId: string, input: ActivityLogInput) {
const knex = await this.getKnex(tenantId);
return ActivityLog.query(knex).insert({
action: input.action,
subjectType: input.subjectType,
subjectId: input.subjectId,
description: input.description,
properties: input.properties ?? null,
causerId: input.causerId ?? null,
});
}
async listActivities(
tenantId: string,
filters: {
subjectType?: string;
subjectId?: string;
causerId?: string;
action?: string;
},
) {
const knex = await this.getKnex(tenantId);
return ActivityLog.query(knex)
.modify((qb) => {
if (filters.subjectType) qb.where('subjectType', filters.subjectType);
if (filters.subjectId) qb.where('subjectId', filters.subjectId);
if (filters.causerId) qb.where('causerId', filters.causerId);
if (filters.action) qb.where('action', filters.action);
})
.orderBy('createdAt', 'desc');
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -12,94 +12,15 @@ export interface AiChatContext {
export interface AiAssistantReply {
reply: string;
action?: 'create_record' | 'collect_fields' | 'clarify' | 'plan_complete' | 'plan_pending';
action?: 'create_record' | 'collect_fields' | 'clarify';
missingFields?: string[];
record?: any;
records?: any[]; // Multiple records when plan execution completes
plan?: RecordCreationPlan;
}
// ============================================
// Entity Discovery Types
// ============================================
export interface EntityFieldInfo {
apiName: string;
label: string;
type: string;
isRequired: boolean;
isSystem: boolean;
referenceObject?: string; // For LOOKUP fields, the target entity
description?: string;
}
export interface EntityRelationship {
fieldApiName: string;
fieldLabel: string;
targetEntity: string;
relationshipType: 'lookup' | 'master-detail' | 'polymorphic';
}
export interface EntityInfo {
apiName: string;
label: string;
pluralLabel?: string;
description?: string;
fields: EntityFieldInfo[];
requiredFields: string[]; // Field apiNames that are required
relationships: EntityRelationship[];
}
export interface SystemEntities {
entities: EntityInfo[];
entityByApiName: Record<string, EntityInfo>; // Changed from Map for state serialization
loadedAt: number;
}
// ============================================
// Planning Types
// ============================================
export interface PlannedRecord {
id: string; // Temporary ID for planning (e.g., "temp_account_1")
entityApiName: string;
entityLabel: string;
fields: Record<string, any>;
resolvedFields?: Record<string, any>; // Fields after dependency resolution
missingRequiredFields: string[];
dependsOn: string[]; // IDs of other planned records this depends on
status: 'pending' | 'ready' | 'created' | 'failed';
createdRecordId?: string; // Actual ID after creation
wasExisting?: boolean; // True if record already existed in database
error?: string;
}
export interface RecordCreationPlan {
id: string;
records: PlannedRecord[];
executionOrder: string[]; // Ordered list of planned record IDs
status: 'building' | 'incomplete' | 'ready' | 'executing' | 'completed' | 'failed';
createdRecords: any[];
errors: string[];
}
// ============================================
// State Types
// ============================================
export interface AiAssistantState {
message: string;
messages?: any[]; // BaseMessage[] from langchain - used when invoked by Deep Agent
history?: AiChatMessage[];
context: AiChatContext;
// Entity discovery
systemEntities?: SystemEntities;
// Planning
plan?: RecordCreationPlan;
// Legacy fields (kept for compatibility during transition)
objectDefinition?: any;
pageLayout?: any;
extractedFields?: Record<string, any>;

View File

@@ -10,14 +10,14 @@ export class AppBuilderService {
// Runtime endpoints
async getApps(tenantId: string, userId: string) {
const knex = await this.tenantDbService.getTenantKnexById(tenantId);
const knex = await this.tenantDbService.getTenantKnex(tenantId);
// For now, return all apps
// In production, you'd filter by user permissions
return App.query(knex).withGraphFetched('pages').orderBy('label', 'asc');
}
async getApp(tenantId: string, slug: string, userId: string) {
const knex = await this.tenantDbService.getTenantKnexById(tenantId);
const knex = await this.tenantDbService.getTenantKnex(tenantId);
const app = await App.query(knex)
.findOne({ slug })
.withGraphFetched('pages');
@@ -35,7 +35,7 @@ export class AppBuilderService {
pageSlug: string,
userId: string,
) {
const knex = await this.tenantDbService.getTenantKnexById(tenantId);
const knex = await this.tenantDbService.getTenantKnex(tenantId);
const app = await this.getApp(tenantId, appSlug, userId);
const page = await AppPage.query(knex).findOne({
@@ -52,12 +52,12 @@ export class AppBuilderService {
// Setup endpoints
async getAllApps(tenantId: string) {
const knex = await this.tenantDbService.getTenantKnexById(tenantId);
const knex = await this.tenantDbService.getTenantKnex(tenantId);
return App.query(knex).withGraphFetched('pages').orderBy('label', 'asc');
}
async getAppForSetup(tenantId: string, slug: string) {
const knex = await this.tenantDbService.getTenantKnexById(tenantId);
const knex = await this.tenantDbService.getTenantKnex(tenantId);
const app = await App.query(knex)
.findOne({ slug })
.withGraphFetched('pages');
@@ -77,7 +77,7 @@ export class AppBuilderService {
description?: string;
},
) {
const knex = await this.tenantDbService.getTenantKnexById(tenantId);
const knex = await this.tenantDbService.getTenantKnex(tenantId);
return App.query(knex).insert({
...data,
displayOrder: 0,
@@ -92,7 +92,7 @@ export class AppBuilderService {
description?: string;
},
) {
const knex = await this.tenantDbService.getTenantKnexById(tenantId);
const knex = await this.tenantDbService.getTenantKnex(tenantId);
const app = await this.getAppForSetup(tenantId, slug);
return App.query(knex).patchAndFetchById(app.id, data);
@@ -109,7 +109,7 @@ export class AppBuilderService {
sortOrder?: number;
},
) {
const knex = await this.tenantDbService.getTenantKnexById(tenantId);
const knex = await this.tenantDbService.getTenantKnex(tenantId);
const app = await this.getAppForSetup(tenantId, appSlug);
return AppPage.query(knex).insert({
@@ -133,7 +133,7 @@ export class AppBuilderService {
sortOrder?: number;
},
) {
const knex = await this.tenantDbService.getTenantKnexById(tenantId);
const knex = await this.tenantDbService.getTenantKnex(tenantId);
const app = await this.getAppForSetup(tenantId, appSlug);
const page = await AppPage.query(knex).findOne({

View File

@@ -9,6 +9,9 @@ import { AppBuilderModule } from './app-builder/app-builder.module';
import { PageLayoutModule } from './page-layout/page-layout.module';
import { VoiceModule } from './voice/voice.module';
import { AiAssistantModule } from './ai-assistant/ai-assistant.module';
import { ActivityLogModule } from './activity-log/activity-log.module';
import { TaskModule } from './task/task.module';
import { ApprovalModule } from './approval/approval.module';
@Module({
imports: [
@@ -24,6 +27,9 @@ import { AiAssistantModule } from './ai-assistant/ai-assistant.module';
PageLayoutModule,
VoiceModule,
AiAssistantModule,
ActivityLogModule,
TaskModule,
ApprovalModule,
],
})
export class AppModule {}

View File

@@ -0,0 +1,54 @@
import { Body, Controller, Get, Patch, Param, Post, UseGuards } from '@nestjs/common';
import { ApprovalService } from './approval.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { TenantId } from '../tenant/tenant.decorator';
@Controller('approvals')
@UseGuards(JwtAuthGuard)
export class ApprovalRequestController {
constructor(private approvalService: ApprovalService) {}
@Get()
async listRequests(@TenantId() tenantId: string) {
return this.approvalService.listRequests(tenantId);
}
@Post()
async createRequest(
@TenantId() tenantId: string,
@Body()
body: {
definitionId: string;
targetObjectType: string;
targetObjectId: string;
action?: string;
stateFrom?: string;
stateTo?: string;
fieldChanges?: Record<string, any>;
snapshot?: Record<string, any>;
submittedById?: string;
},
) {
return this.approvalService.createRequest(tenantId, body);
}
@Patch('assignments/:assignmentId')
async updateAssignmentStatus(
@TenantId() tenantId: string,
@Param('assignmentId') assignmentId: string,
@Body()
body: {
status: 'approved' | 'rejected';
response?: string;
actedById?: string;
},
) {
return this.approvalService.updateAssignmentStatus(
tenantId,
assignmentId,
body.status,
body.response,
body.actedById,
);
}
}

View File

@@ -0,0 +1,56 @@
import { Body, Controller, Get, Param, Patch, Post, UseGuards } from '@nestjs/common';
import { ApprovalService } from './approval.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { TenantId } from '../tenant/tenant.decorator';
@Controller('setup/approvals')
@UseGuards(JwtAuthGuard)
export class ApprovalSetupController {
constructor(private approvalService: ApprovalService) {}
@Get()
async listDefinitions(@TenantId() tenantId: string) {
return this.approvalService.listDefinitions(tenantId);
}
@Post()
async createDefinition(
@TenantId() tenantId: string,
@Body()
body: {
name: string;
description?: string;
triggerType: string;
targetObjectType?: string;
entryCriteria?: Record<string, any>;
steps?: Array<Record<string, any>>;
votingPolicy?: Record<string, any>;
rejectionRule?: string;
materialChangePolicy?: string;
isActive?: boolean;
},
) {
return this.approvalService.createDefinition(tenantId, body);
}
@Patch(':definitionId')
async updateDefinition(
@TenantId() tenantId: string,
@Param('definitionId') definitionId: string,
@Body()
body: {
name?: string;
description?: string;
triggerType?: string;
targetObjectType?: string;
entryCriteria?: Record<string, any>;
steps?: Array<Record<string, any>>;
votingPolicy?: Record<string, any>;
rejectionRule?: string;
materialChangePolicy?: string;
isActive?: boolean;
},
) {
return this.approvalService.updateDefinition(tenantId, definitionId, body);
}
}

View File

@@ -0,0 +1,14 @@
import { Module } from '@nestjs/common';
import { ApprovalService } from './approval.service';
import { ApprovalSetupController } from './approval-setup.controller';
import { ApprovalRequestController } from './approval-request.controller';
import { ActivityLogModule } from '../activity-log/activity-log.module';
import { TaskModule } from '../task/task.module';
import { TenantModule } from '../tenant/tenant.module';
@Module({
imports: [TenantModule, ActivityLogModule, TaskModule],
controllers: [ApprovalSetupController, ApprovalRequestController],
providers: [ApprovalService],
})
export class ApprovalModule {}

View File

@@ -0,0 +1,402 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { createHash } from 'crypto';
import { ActivityLogService } from '../activity-log/activity-log.service';
import { TaskService } from '../task/task.service';
import { TenantDatabaseService } from '../tenant/tenant-database.service';
import { ApprovalDefinition } from '../models/approval-definition.model';
import { ApprovalRequest } from '../models/approval-request.model';
import { ApprovalStep } from '../models/approval-step.model';
import { ApprovalAssignment } from '../models/approval-assignment.model';
import { ApprovalEffectLog } from '../models/approval-effect-log.model';
interface ApprovalDefinitionInput {
name: string;
description?: string;
triggerType: string;
targetObjectType?: string;
entryCriteria?: Record<string, any> | null;
steps?: Array<Record<string, any>> | null;
votingPolicy?: Record<string, any> | null;
rejectionRule?: string | null;
materialChangePolicy?: string | null;
isActive?: boolean;
}
interface ApprovalRequestInput {
definitionId: string;
targetObjectType: string;
targetObjectId: string;
action?: string;
stateFrom?: string;
stateTo?: string;
fieldChanges?: Record<string, any> | null;
snapshot?: Record<string, any> | null;
submittedById?: string | null;
}
@Injectable()
export class ApprovalService {
constructor(
private tenantDbService: TenantDatabaseService,
private activityLogService: ActivityLogService,
private taskService: TaskService,
) {}
private async getKnex(tenantId: string) {
const resolved = await this.tenantDbService.resolveTenantId(tenantId);
return this.tenantDbService.getTenantKnexById(resolved);
}
async listDefinitions(tenantId: string) {
const knex = await this.getKnex(tenantId);
return ApprovalDefinition.query(knex).orderBy('createdAt', 'desc');
}
async createDefinition(tenantId: string, input: ApprovalDefinitionInput) {
const knex = await this.getKnex(tenantId);
const definition = await ApprovalDefinition.query(knex).insert({
name: input.name,
description: input.description,
triggerType: input.triggerType,
targetObjectType: input.targetObjectType,
entryCriteria: input.entryCriteria ?? null,
steps: input.steps ?? null,
votingPolicy: input.votingPolicy ?? null,
rejectionRule: input.rejectionRule ?? null,
materialChangePolicy: input.materialChangePolicy ?? null,
isActive: input.isActive ?? true,
version: 1,
});
await this.activityLogService.logActivity(tenantId, {
action: 'approval_definition.created',
subjectType: 'ApprovalDefinition',
subjectId: definition.id,
description: `Created approval definition ${definition.name}`,
});
return definition;
}
async updateDefinition(
tenantId: string,
definitionId: string,
input: Partial<ApprovalDefinitionInput>,
) {
const knex = await this.getKnex(tenantId);
const existing = await ApprovalDefinition.query(knex).findById(definitionId);
if (!existing) {
throw new NotFoundException('Approval definition not found');
}
const needsVersionBump =
input.entryCriteria !== undefined ||
input.steps !== undefined ||
input.votingPolicy !== undefined ||
input.rejectionRule !== undefined ||
input.materialChangePolicy !== undefined;
const definition = await ApprovalDefinition.query(knex).patchAndFetchById(definitionId, {
name: input.name,
description: input.description,
triggerType: input.triggerType,
targetObjectType: input.targetObjectType,
entryCriteria: input.entryCriteria ?? undefined,
steps: input.steps ?? undefined,
votingPolicy: input.votingPolicy ?? undefined,
rejectionRule: input.rejectionRule ?? undefined,
materialChangePolicy: input.materialChangePolicy ?? undefined,
isActive: input.isActive,
version: needsVersionBump ? existing.version + 1 : existing.version,
});
await this.activityLogService.logActivity(tenantId, {
action: 'approval_definition.updated',
subjectType: 'ApprovalDefinition',
subjectId: definition.id,
description: `Updated approval definition ${definition.name}`,
});
return definition;
}
async listRequests(tenantId: string) {
const knex = await this.getKnex(tenantId);
return ApprovalRequest.query(knex)
.withGraphFetched('[steps.assignments,definition]')
.orderBy('createdAt', 'desc');
}
async createRequest(tenantId: string, input: ApprovalRequestInput) {
const knex = await this.getKnex(tenantId);
const definition = await ApprovalDefinition.query(knex).findById(input.definitionId);
if (!definition) {
throw new NotFoundException('Approval definition not found');
}
const versionHash = this.createVersionHash({
snapshot: input.snapshot ?? {},
fieldChanges: input.fieldChanges ?? {},
definitionVersion: definition.version,
});
const request = await ApprovalRequest.query(knex).insertAndFetch({
definitionId: definition.id,
status: 'pending',
targetObjectType: input.targetObjectType,
targetObjectId: input.targetObjectId,
action: input.action,
stateFrom: input.stateFrom,
stateTo: input.stateTo,
fieldChanges: input.fieldChanges ?? null,
snapshot: input.snapshot ?? null,
versionHash,
submittedById: input.submittedById ?? null,
submittedAt: new Date(),
});
const stepConfigs = Array.isArray(definition.steps) ? definition.steps : [];
for (const [index, stepConfig] of stepConfigs.entries()) {
const stepKey = stepConfig.key || `step-${index + 1}`;
const step = await ApprovalStep.query(knex).insertAndFetch({
requestId: request.id,
stepKey,
name: stepConfig.name || `Step ${index + 1}`,
stepOrder: stepConfig.order ?? index + 1,
status: 'pending',
routing: stepConfig.routing ?? null,
voting: stepConfig.voting ?? null,
dueAt: stepConfig.dueAt ? new Date(stepConfig.dueAt) : null,
});
const assignees: string[] = Array.isArray(stepConfig.assignees)
? stepConfig.assignees
: [];
for (const assigneeId of assignees) {
const assignment = await ApprovalAssignment.query(knex).insertAndFetch({
stepId: step.id,
assigneeId,
status: 'pending',
dueAt: stepConfig.dueAt ? new Date(stepConfig.dueAt) : null,
});
await this.taskService.createTask(tenantId, {
title: `Approval needed: ${definition.name}`,
description: `Approval step ${step.name} requires your review.`,
dueAt: stepConfig.dueAt ?? undefined,
assignedToId: assigneeId,
relatedObjectType: 'ApprovalAssignment',
relatedObjectId: assignment.id,
});
await this.activityLogService.logActivity(tenantId, {
action: 'approval_assignment.created',
subjectType: 'ApprovalAssignment',
subjectId: assignment.id,
description: `Assignment created for approval step ${step.name}`,
causerId: input.submittedById ?? undefined,
properties: {
requestId: request.id,
stepId: step.id,
},
});
}
}
await this.activityLogService.logActivity(tenantId, {
action: 'approval_request.created',
subjectType: 'ApprovalRequest',
subjectId: request.id,
description: `Created approval request for ${input.targetObjectType}`,
causerId: input.submittedById ?? undefined,
properties: {
definitionId: definition.id,
targetObjectId: input.targetObjectId,
},
});
return request;
}
async updateAssignmentStatus(
tenantId: string,
assignmentId: string,
status: 'approved' | 'rejected',
response?: string,
actedById?: string,
) {
const knex = await this.getKnex(tenantId);
const assignment = await ApprovalAssignment.query(knex)
.findById(assignmentId)
.withGraphFetched('step.request');
if (!assignment) {
throw new NotFoundException('Approval assignment not found');
}
const updatedAssignment = await ApprovalAssignment.query(knex).patchAndFetchById(
assignmentId,
{
status,
response,
respondedAt: new Date(),
},
);
await this.taskService.updateTaskByRelated(
tenantId,
'ApprovalAssignment',
assignmentId,
{
status: 'completed',
},
);
await this.activityLogService.logActivity(tenantId, {
action: `approval_assignment.${status}`,
subjectType: 'ApprovalAssignment',
subjectId: assignmentId,
description: `Assignment ${status}`,
causerId: actedById ?? assignment.assigneeId,
properties: {
stepId: assignment.stepId,
requestId: assignment.step?.requestId,
},
});
await this.evaluateStepCompletion(
tenantId,
assignment.stepId,
actedById ?? assignment.assigneeId,
);
return updatedAssignment;
}
private async evaluateStepCompletion(tenantId: string, stepId: string, actedById?: string) {
const knex = await this.getKnex(tenantId);
const step = await ApprovalStep.query(knex)
.findById(stepId)
.withGraphFetched('[assignments, request.[definition,steps]]');
if (!step) {
return;
}
const voting = (step.voting as Record<string, any>) || {};
const rule = voting.type || 'unanimous';
const rejectionRule = voting.rejectionRule || step.request?.definition?.rejectionRule || 'any';
const approvals = (step.assignments || []).filter((assignment) => assignment.status === 'approved');
const rejections = (step.assignments || []).filter((assignment) => assignment.status === 'rejected');
const totalAssignments = step.assignments?.length || 1;
if (rejections.length > 0 && rejectionRule === 'any') {
await this.completeStep(tenantId, step, 'rejected', actedById);
await this.completeRequestIfNeeded(tenantId, step.requestId, 'rejected', actedById);
return;
}
const approved = this.checkApprovalRule(rule, approvals.length, totalAssignments, voting.threshold);
if (approved) {
await this.completeStep(tenantId, step, 'approved', actedById);
await this.completeRequestIfNeeded(tenantId, step.requestId, 'approved', actedById);
}
}
private checkApprovalRule(rule: string, approvals: number, total: number, threshold?: number) {
if (rule === 'majority') {
return approvals > total / 2;
}
if (rule === 'k-of-n') {
const required = threshold ?? total;
return approvals >= required;
}
return approvals === total;
}
private async completeStep(
tenantId: string,
step: { id: string; status: string; requestId: string; name: string },
status: string,
actedById?: string,
) {
const knex = await this.getKnex(tenantId);
if (step.status === status) {
return;
}
await ApprovalStep.query(knex).patchAndFetchById(step.id, {
status,
completedAt: new Date(),
});
await this.activityLogService.logActivity(tenantId, {
action: `approval_step.${status}`,
subjectType: 'ApprovalStep',
subjectId: step.id,
description: `Step ${step.name} marked ${status}`,
causerId: actedById,
properties: { requestId: step.requestId },
});
}
private async completeRequestIfNeeded(
tenantId: string,
requestId: string,
status: 'approved' | 'rejected',
actedById?: string,
) {
const knex = await this.getKnex(tenantId);
const request = await ApprovalRequest.query(knex)
.findById(requestId)
.withGraphFetched('steps');
if (!request) {
return;
}
const allApproved = (request.steps || []).every((step) => step.status === 'approved');
if (status === 'rejected' || allApproved) {
const finalStatus = status === 'rejected' ? 'rejected' : 'approved';
await ApprovalRequest.query(knex).patchAndFetchById(requestId, {
status: finalStatus,
});
await this.activityLogService.logActivity(tenantId, {
action: `approval_request.${finalStatus}`,
subjectType: 'ApprovalRequest',
subjectId: requestId,
description: `Request ${finalStatus}`,
causerId: actedById,
});
await this.logEffectExecution(tenantId, requestId, `on_${finalStatus}`);
}
}
private async logEffectExecution(tenantId: string, requestId: string, effectKey: string) {
const knex = await this.getKnex(tenantId);
const existing = await ApprovalEffectLog.query(knex)
.where({ requestId, effectKey })
.first();
if (existing) {
return existing;
}
return ApprovalEffectLog.query(knex).insert({
requestId,
effectKey,
status: 'success',
});
}
private createVersionHash(payload: Record<string, any>) {
return createHash('sha256').update(JSON.stringify(payload)).digest('hex');
}
}

View File

@@ -1,19 +1,15 @@
import {
Controller,
Post,
Get,
Body,
UnauthorizedException,
HttpCode,
HttpStatus,
Req,
UseGuards,
} from '@nestjs/common';
import { IsEmail, IsString, MinLength, IsOptional } from 'class-validator';
import { AuthService } from './auth.service';
import { TenantId } from '../tenant/tenant.decorator';
import { JwtAuthGuard } from './jwt-auth.guard';
import { CurrentUser } from './current-user.decorator';
class LoginDto {
@IsEmail()
@@ -115,15 +111,4 @@ export class AuthController {
// This endpoint exists for consistency and potential future enhancements
return { message: 'Logged out successfully' };
}
@UseGuards(JwtAuthGuard)
@Get('me')
async me(@CurrentUser() user: any, @TenantId() tenantId: string) {
// Return the current authenticated user info
return {
id: user.userId,
email: user.email,
tenantId: tenantId || user.tenantId,
};
}
}

View File

@@ -29,8 +29,8 @@ export class AuthService {
}
// Otherwise, validate as tenant user
const tenantDb = await this.tenantDbService.getTenantKnexById(tenantId);
const tenantDb = await this.tenantDbService.getTenantKnex(tenantId);
const user = await tenantDb('users')
.where({ email })
.first();
@@ -113,7 +113,7 @@ export class AuthService {
}
// Otherwise, register as tenant user
const tenantDb = await this.tenantDbService.getTenantKnexById(tenantId);
const tenantDb = await this.tenantDbService.getTenantKnex(tenantId);
const hashedPassword = await bcrypt.hash(password, 10);

View File

@@ -0,0 +1,14 @@
import { BaseModel } from './base.model';
export class ActivityLog extends BaseModel {
static tableName = 'activity_logs';
id!: string;
action!: string;
subjectType!: string;
subjectId!: string;
description?: string;
properties?: Record<string, any>;
causerId?: string | null;
createdAt!: Date;
}

View File

@@ -0,0 +1,30 @@
import { BaseModel } from './base.model';
import { ApprovalStep } from './approval-step.model';
export class ApprovalAssignment extends BaseModel {
static tableName = 'approval_assignments';
id!: string;
stepId!: string;
assigneeId!: string;
status!: string;
response?: string | null;
respondedAt?: Date | null;
dueAt?: Date | null;
reassignedFromId?: string | null;
delegatedById?: string | null;
createdAt!: Date;
updatedAt!: Date;
step?: ApprovalStep;
static relationMappings = () => ({
step: {
relation: BaseModel.BelongsToOneRelation,
modelClass: 'approval-step.model',
join: {
from: 'approval_assignments.stepId',
to: 'approval_steps.id',
},
},
});
}

View File

@@ -0,0 +1,31 @@
import { BaseModel } from './base.model';
export class ApprovalDefinition extends BaseModel {
static tableName = 'approval_definitions';
id!: string;
name!: string;
description?: string;
triggerType!: string;
targetObjectType?: string;
entryCriteria?: Record<string, any> | null;
steps?: any[] | null;
votingPolicy?: Record<string, any> | null;
rejectionRule?: string | null;
materialChangePolicy?: string | null;
version!: number;
isActive!: boolean;
createdAt!: Date;
updatedAt!: Date;
static relationMappings = () => ({
requests: {
relation: BaseModel.HasManyRelation,
modelClass: 'approval-request.model',
join: {
from: 'approval_definitions.id',
to: 'approval_requests.definitionId',
},
},
});
}

View File

@@ -0,0 +1,23 @@
import { BaseModel } from './base.model';
export class ApprovalEffectLog extends BaseModel {
static tableName = 'approval_effect_logs';
id!: string;
requestId!: string;
effectKey!: string;
status!: string;
response?: Record<string, any> | null;
executedAt!: Date;
static relationMappings = () => ({
request: {
relation: BaseModel.BelongsToOneRelation,
modelClass: 'approval-request.model',
join: {
from: 'approval_effect_logs.requestId',
to: 'approval_requests.id',
},
},
});
}

View File

@@ -0,0 +1,55 @@
import { BaseModel } from './base.model';
import { ApprovalDefinition } from './approval-definition.model';
import { ApprovalStep } from './approval-step.model';
import { ApprovalEffectLog } from './approval-effect-log.model';
export class ApprovalRequest extends BaseModel {
static tableName = 'approval_requests';
id!: string;
definitionId!: string;
status!: string;
targetObjectType!: string;
targetObjectId!: string;
action?: string;
stateFrom?: string;
stateTo?: string;
fieldChanges?: Record<string, any> | null;
snapshot?: Record<string, any> | null;
versionHash?: string | null;
submittedById?: string | null;
submittedAt?: Date | null;
currentStepKey?: string | null;
createdAt!: Date;
updatedAt!: Date;
definition?: ApprovalDefinition;
steps?: ApprovalStep[];
effectLogs?: ApprovalEffectLog[];
static relationMappings = () => ({
definition: {
relation: BaseModel.BelongsToOneRelation,
modelClass: 'approval-definition.model',
join: {
from: 'approval_requests.definitionId',
to: 'approval_definitions.id',
},
},
steps: {
relation: BaseModel.HasManyRelation,
modelClass: 'approval-step.model',
join: {
from: 'approval_requests.id',
to: 'approval_steps.requestId',
},
},
effectLogs: {
relation: BaseModel.HasManyRelation,
modelClass: 'approval-effect-log.model',
join: {
from: 'approval_requests.id',
to: 'approval_effect_logs.requestId',
},
},
});
}

View File

@@ -0,0 +1,41 @@
import { BaseModel } from './base.model';
import { ApprovalRequest } from './approval-request.model';
import { ApprovalAssignment } from './approval-assignment.model';
export class ApprovalStep extends BaseModel {
static tableName = 'approval_steps';
id!: string;
requestId!: string;
stepKey!: string;
name!: string;
stepOrder!: number;
status!: string;
routing?: Record<string, any> | null;
voting?: Record<string, any> | null;
dueAt?: Date | null;
completedAt?: Date | null;
createdAt!: Date;
updatedAt!: Date;
request?: ApprovalRequest;
assignments?: ApprovalAssignment[];
static relationMappings = () => ({
request: {
relation: BaseModel.BelongsToOneRelation,
modelClass: 'approval-request.model',
join: {
from: 'approval_steps.requestId',
to: 'approval_requests.id',
},
},
assignments: {
relation: BaseModel.HasManyRelation,
modelClass: 'approval-assignment.model',
join: {
from: 'approval_steps.id',
to: 'approval_assignments.stepId',
},
},
});
}

View File

@@ -0,0 +1,15 @@
import { BaseModel } from './base.model';
export class Task extends BaseModel {
static tableName = 'tasks';
id!: string;
title!: string;
description?: string;
status!: string;
priority?: string;
dueAt?: Date;
assignedToId?: string | null;
relatedObjectType?: string | null;
relatedObjectId?: string | null;
}

View File

@@ -79,10 +79,6 @@ export class FieldMapperService {
const frontendType = this.mapFieldType(field.type);
const isLookupField = frontendType === 'belongsTo' || field.type.toLowerCase().includes('lookup');
// Hide 'id' field from list view by default
const isIdField = field.apiName === 'id';
const defaultShowOnList = isIdField ? false : true;
return {
id: field.id,
apiName: field.apiName,
@@ -99,7 +95,7 @@ export class FieldMapperService {
isReadOnly: field.isSystem || uiMetadata.isReadOnly || false,
// View visibility
showOnList: uiMetadata.showOnList !== undefined ? uiMetadata.showOnList : defaultShowOnList,
showOnList: uiMetadata.showOnList !== false,
showOnDetail: uiMetadata.showOnDetail !== false,
showOnEdit: uiMetadata.showOnEdit !== false && !field.isSystem,
sortable: uiMetadata.sortable !== false,
@@ -145,7 +141,6 @@ export class FieldMapperService {
'boolean': 'boolean',
'date': 'date',
'datetime': 'datetime',
'date_time': 'datetime',
'time': 'time',
'email': 'email',
'url': 'url',

View File

@@ -1,6 +1,4 @@
import { IsString, IsUUID, IsBoolean, IsOptional, IsObject, IsIn } from 'class-validator';
export type PageLayoutType = 'detail' | 'list';
import { IsString, IsUUID, IsBoolean, IsOptional, IsObject } from 'class-validator';
export class CreatePageLayoutDto {
@IsString()
@@ -9,25 +7,18 @@ export class CreatePageLayoutDto {
@IsUUID()
objectId: string;
@IsIn(['detail', 'list'])
@IsOptional()
layoutType?: PageLayoutType = 'detail';
@IsBoolean()
@IsOptional()
isDefault?: boolean;
@IsObject()
layoutConfig: {
// For detail layouts: grid-based field positions
fields: Array<{
fieldId: string;
x?: number;
y?: number;
w?: number;
h?: number;
// For list layouts: field order (optional, defaults to array index)
order?: number;
x: number;
y: number;
w: number;
h: number;
}>;
relatedLists?: string[];
};
@@ -51,11 +42,10 @@ export class UpdatePageLayoutDto {
layoutConfig?: {
fields: Array<{
fieldId: string;
x?: number;
y?: number;
w?: number;
h?: number;
order?: number;
x: number;
y: number;
w: number;
h: number;
}>;
relatedLists?: string[];
};

View File

@@ -10,7 +10,7 @@ import {
Query,
} from '@nestjs/common';
import { PageLayoutService } from './page-layout.service';
import { CreatePageLayoutDto, UpdatePageLayoutDto, PageLayoutType } from './dto/page-layout.dto';
import { CreatePageLayoutDto, UpdatePageLayoutDto } from './dto/page-layout.dto';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { TenantId } from '../tenant/tenant.decorator';
@@ -25,21 +25,13 @@ export class PageLayoutController {
}
@Get()
findAll(
@TenantId() tenantId: string,
@Query('objectId') objectId?: string,
@Query('layoutType') layoutType?: PageLayoutType,
) {
return this.pageLayoutService.findAll(tenantId, objectId, layoutType);
findAll(@TenantId() tenantId: string, @Query('objectId') objectId?: string) {
return this.pageLayoutService.findAll(tenantId, objectId);
}
@Get('default/:objectId')
findDefaultByObject(
@TenantId() tenantId: string,
@Param('objectId') objectId: string,
@Query('layoutType') layoutType?: PageLayoutType,
) {
return this.pageLayoutService.findDefaultByObject(tenantId, objectId, layoutType || 'detail');
findDefaultByObject(@TenantId() tenantId: string, @Param('objectId') objectId: string) {
return this.pageLayoutService.findDefaultByObject(tenantId, objectId);
}
@Get(':id')

View File

@@ -1,26 +1,24 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { TenantDatabaseService } from '../tenant/tenant-database.service';
import { CreatePageLayoutDto, UpdatePageLayoutDto, PageLayoutType } from './dto/page-layout.dto';
import { CreatePageLayoutDto, UpdatePageLayoutDto } from './dto/page-layout.dto';
@Injectable()
export class PageLayoutService {
constructor(private tenantDbService: TenantDatabaseService) {}
async create(tenantId: string, createDto: CreatePageLayoutDto) {
const knex = await this.tenantDbService.getTenantKnexById(tenantId);
const layoutType = createDto.layoutType || 'detail';
const knex = await this.tenantDbService.getTenantKnex(tenantId);
// If this layout is set as default, unset other defaults for the same object and layout type
// If this layout is set as default, unset other defaults for the same object
if (createDto.isDefault) {
await knex('page_layouts')
.where({ object_id: createDto.objectId, layout_type: layoutType })
.where({ object_id: createDto.objectId })
.update({ is_default: false });
}
const [id] = await knex('page_layouts').insert({
name: createDto.name,
object_id: createDto.objectId,
layout_type: layoutType,
is_default: createDto.isDefault || false,
layout_config: JSON.stringify(createDto.layoutConfig),
description: createDto.description || null,
@@ -31,8 +29,8 @@ export class PageLayoutService {
return result;
}
async findAll(tenantId: string, objectId?: string, layoutType?: PageLayoutType) {
const knex = await this.tenantDbService.getTenantKnexById(tenantId);
async findAll(tenantId: string, objectId?: string) {
const knex = await this.tenantDbService.getTenantKnex(tenantId);
let query = knex('page_layouts');
@@ -40,16 +38,12 @@ export class PageLayoutService {
query = query.where({ object_id: objectId });
}
if (layoutType) {
query = query.where({ layout_type: layoutType });
}
const layouts = await query.orderByRaw('is_default DESC, name ASC');
return layouts;
}
async findOne(tenantId: string, id: string) {
const knex = await this.tenantDbService.getTenantKnexById(tenantId);
const knex = await this.tenantDbService.getTenantKnex(tenantId);
const layout = await knex('page_layouts').where({ id }).first();
@@ -60,26 +54,27 @@ export class PageLayoutService {
return layout;
}
async findDefaultByObject(tenantId: string, objectId: string, layoutType: PageLayoutType = 'detail') {
const knex = await this.tenantDbService.getTenantKnexById(tenantId);
async findDefaultByObject(tenantId: string, objectId: string) {
const knex = await this.tenantDbService.getTenantKnex(tenantId);
const layout = await knex('page_layouts')
.where({ object_id: objectId, is_default: true, layout_type: layoutType })
.where({ object_id: objectId, is_default: true })
.first();
return layout || null;
}
async update(tenantId: string, id: string, updateDto: UpdatePageLayoutDto) {
const knex = await this.tenantDbService.getTenantKnexById(tenantId);
const knex = await this.tenantDbService.getTenantKnex(tenantId);
// Check if layout exists
const layout = await this.findOne(tenantId, id);
await this.findOne(tenantId, id);
// If setting as default, unset other defaults for the same object and layout type
// If setting as default, unset other defaults for the same object
if (updateDto.isDefault) {
const layout = await this.findOne(tenantId, id);
await knex('page_layouts')
.where({ object_id: layout.object_id, layout_type: layout.layout_type })
.where({ object_id: layout.object_id })
.whereNot({ id })
.update({ is_default: false });
}
@@ -112,7 +107,7 @@ export class PageLayoutService {
}
async remove(tenantId: string, id: string) {
const knex = await this.tenantDbService.getTenantKnexById(tenantId);
const knex = await this.tenantDbService.getTenantKnex(tenantId);
await this.findOne(tenantId, id);

View File

@@ -0,0 +1,63 @@
import { Controller, Get, Post, Patch, Body, Param, Query, UseGuards } from '@nestjs/common';
import { TaskService } from './task.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { TenantId } from '../tenant/tenant.decorator';
@Controller('tasks')
@UseGuards(JwtAuthGuard)
export class TaskController {
constructor(private taskService: TaskService) {}
@Get()
async listTasks(
@TenantId() tenantId: string,
@Query('status') status?: string,
@Query('assignedToId') assignedToId?: string,
@Query('relatedObjectType') relatedObjectType?: string,
@Query('relatedObjectId') relatedObjectId?: string,
) {
return this.taskService.listTasks(tenantId, {
status,
assignedToId,
relatedObjectType,
relatedObjectId,
});
}
@Post()
async createTask(
@TenantId() tenantId: string,
@Body()
body: {
title: string;
description?: string;
status?: string;
priority?: string;
dueAt?: string;
assignedToId?: string;
relatedObjectType?: string;
relatedObjectId?: string;
},
) {
return this.taskService.createTask(tenantId, body);
}
@Patch(':taskId')
async updateTask(
@TenantId() tenantId: string,
@Param('taskId') taskId: string,
@Body()
body: {
title?: string;
description?: string;
status?: string;
priority?: string;
dueAt?: string;
assignedToId?: string;
relatedObjectType?: string;
relatedObjectId?: string;
},
) {
return this.taskService.updateTask(tenantId, taskId, body);
}
}

View File

@@ -0,0 +1,12 @@
import { Module } from '@nestjs/common';
import { TaskController } from './task.controller';
import { TaskService } from './task.service';
import { TenantModule } from '../tenant/tenant.module';
@Module({
imports: [TenantModule],
controllers: [TaskController],
providers: [TaskService],
exports: [TaskService],
})
export class TaskModule {}

View File

@@ -0,0 +1,91 @@
import { Injectable } from '@nestjs/common';
import { TenantDatabaseService } from '../tenant/tenant-database.service';
import { Task } from '../models/task.model';
export interface TaskInput {
title: string;
description?: string;
status?: string;
priority?: string;
dueAt?: string | Date | null;
assignedToId?: string | null;
relatedObjectType?: string | null;
relatedObjectId?: string | null;
}
@Injectable()
export class TaskService {
constructor(private tenantDbService: TenantDatabaseService) {}
private async getKnex(tenantId: string) {
const resolved = await this.tenantDbService.resolveTenantId(tenantId);
return this.tenantDbService.getTenantKnexById(resolved);
}
async listTasks(
tenantId: string,
filters: {
status?: string;
assignedToId?: string;
relatedObjectType?: string;
relatedObjectId?: string;
},
) {
const knex = await this.getKnex(tenantId);
return Task.query(knex)
.modify((qb) => {
if (filters.status) qb.where('status', filters.status);
if (filters.assignedToId) qb.where('assignedToId', filters.assignedToId);
if (filters.relatedObjectType)
qb.where('relatedObjectType', filters.relatedObjectType);
if (filters.relatedObjectId) qb.where('relatedObjectId', filters.relatedObjectId);
})
.orderBy('createdAt', 'desc');
}
async createTask(tenantId: string, input: TaskInput) {
const knex = await this.getKnex(tenantId);
return Task.query(knex).insert({
title: input.title,
description: input.description,
status: input.status ?? 'open',
priority: input.priority,
dueAt: input.dueAt ? new Date(input.dueAt) : null,
assignedToId: input.assignedToId ?? null,
relatedObjectType: input.relatedObjectType ?? null,
relatedObjectId: input.relatedObjectId ?? null,
});
}
async updateTask(tenantId: string, taskId: string, input: Partial<TaskInput>) {
const knex = await this.getKnex(tenantId);
return Task.query(knex).patchAndFetchById(taskId, {
title: input.title,
description: input.description,
status: input.status,
priority: input.priority,
dueAt: input.dueAt ? new Date(input.dueAt) : undefined,
assignedToId: input.assignedToId ?? undefined,
relatedObjectType: input.relatedObjectType ?? undefined,
relatedObjectId: input.relatedObjectId ?? undefined,
});
}
async updateTaskByRelated(
tenantId: string,
relatedObjectType: string,
relatedObjectId: string,
input: Partial<TaskInput>,
) {
const knex = await this.getKnex(tenantId);
return Task.query(knex)
.patch({
status: input.status,
dueAt: input.dueAt ? new Date(input.dueAt) : undefined,
})
.where({
relatedObjectType,
relatedObjectId,
});
}
}

View File

@@ -16,45 +16,26 @@ import { TenantId } from './tenant.decorator';
export class TenantController {
constructor(private readonly tenantDbService: TenantDatabaseService) {}
/**
* Helper to find tenant by ID or domain
*/
private async findTenant(identifier: string) {
const centralPrisma = getCentralPrisma();
// Check if identifier is a CUID (tenant ID) or a domain
const isCUID = /^c[a-z0-9]{24}$/i.test(identifier);
if (isCUID) {
// Look up by tenant ID directly
return centralPrisma.tenant.findUnique({
where: { id: identifier },
select: { id: true, integrationsConfig: true },
});
} else {
// Look up by domain
const domainRecord = await centralPrisma.domain.findUnique({
where: { domain: identifier },
include: { tenant: { select: { id: true, integrationsConfig: true } } },
});
return domainRecord?.tenant;
}
}
/**
* Get integrations configuration for the current tenant
*/
@Get('integrations')
async getIntegrationsConfig(@TenantId() tenantIdentifier: string) {
const tenant = await this.findTenant(tenantIdentifier);
async getIntegrationsConfig(@TenantId() domain: string) {
const centralPrisma = getCentralPrisma();
// Look up tenant by domain
const domainRecord = await centralPrisma.domain.findUnique({
where: { domain },
include: { tenant: { select: { id: true, integrationsConfig: true } } },
});
if (!tenant || !tenant.integrationsConfig) {
if (!domainRecord?.tenant || !domainRecord.tenant.integrationsConfig) {
return { data: null };
}
// Decrypt the config
const config = this.tenantDbService.decryptIntegrationsConfig(
tenant.integrationsConfig as any,
domainRecord.tenant.integrationsConfig as any,
);
// Return config with sensitive fields masked
@@ -68,26 +49,31 @@ export class TenantController {
*/
@Put('integrations')
async updateIntegrationsConfig(
@TenantId() tenantIdentifier: string,
@TenantId() domain: string,
@Body() body: { integrationsConfig: any },
) {
const { integrationsConfig } = body;
if (!tenantIdentifier) {
throw new Error('Tenant identifier is missing from request');
if (!domain) {
throw new Error('Domain is missing from request');
}
const tenant = await this.findTenant(tenantIdentifier);
// Look up tenant by domain
const centralPrisma = getCentralPrisma();
const domainRecord = await centralPrisma.domain.findUnique({
where: { domain },
include: { tenant: { select: { id: true, integrationsConfig: true } } },
});
if (!tenant) {
throw new Error(`Tenant with identifier ${tenantIdentifier} not found`);
if (!domainRecord?.tenant) {
throw new Error(`Tenant with domain ${domain} not found`);
}
// Merge with existing config to preserve masked values
let finalConfig = integrationsConfig;
if (tenant.integrationsConfig) {
if (domainRecord.tenant.integrationsConfig) {
const existingConfig = this.tenantDbService.decryptIntegrationsConfig(
tenant.integrationsConfig as any,
domainRecord.tenant.integrationsConfig as any,
);
// Replace masked values with actual values from existing config
@@ -100,9 +86,8 @@ export class TenantController {
);
// Update in database
const centralPrisma = getCentralPrisma();
await centralPrisma.tenant.update({
where: { id: tenant.id },
where: { id: domainRecord.tenant.id },
data: {
integrationsConfig: encryptedConfig as any,
},

View File

@@ -14,61 +14,61 @@ export class TenantMiddleware implements NestMiddleware {
next: () => void,
) {
try {
// Priority 1: Check x-tenant-subdomain header from Nitro BFF proxy
// This is the primary method when using the BFF architecture
let subdomain = req.headers['x-tenant-subdomain'] as string | null;
// Extract subdomain from hostname
const host = req.headers.host || '';
const hostname = host.split(':')[0]; // Remove port if present
// Check Origin header to get frontend subdomain (for API calls)
const origin = req.headers.origin as string;
const referer = req.headers.referer as string;
let parts = hostname.split('.');
this.logger.log(`Host header: ${host}, hostname: ${hostname}, origin: ${origin}, referer: ${referer}, parts: ${JSON.stringify(parts)}`);
// For local development, accept x-tenant-id header
let tenantId = req.headers['x-tenant-id'] as string;
let subdomain: string | null = null;
if (subdomain) {
this.logger.log(`Using x-tenant-subdomain header: ${subdomain}`);
}
this.logger.log(`Host header: ${host}, hostname: ${hostname}, parts: ${JSON.stringify(parts)}, x-tenant-id: ${tenantId}`);
// Priority 2: Fall back to extracting subdomain from Origin/Host headers
// This supports direct backend access for development/testing
if (!subdomain && !tenantId) {
const host = req.headers.host || '';
const hostname = host.split(':')[0];
const origin = req.headers.origin as string;
const referer = req.headers.referer as string;
let parts = hostname.split('.');
this.logger.log(`Host header: ${host}, hostname: ${hostname}, origin: ${origin}, referer: ${referer}`);
// Try to extract subdomain from Origin header first (for API calls from frontend)
if (origin) {
try {
const originUrl = new URL(origin);
const originHost = originUrl.hostname;
parts = originHost.split('.');
this.logger.log(`Using Origin header hostname: ${originHost}, parts: ${JSON.stringify(parts)}`);
} catch (error) {
this.logger.warn(`Failed to parse origin: ${origin}`);
}
} else if (referer) {
// Fallback to Referer if no Origin
try {
const refererUrl = new URL(referer);
const refererHost = refererUrl.hostname;
parts = refererHost.split('.');
this.logger.log(`Using Referer header hostname: ${refererHost}, parts: ${JSON.stringify(parts)}`);
} catch (error) {
this.logger.warn(`Failed to parse referer: ${referer}`);
}
// Try to extract subdomain from Origin header first (for API calls from frontend)
if (origin) {
try {
const originUrl = new URL(origin);
const originHost = originUrl.hostname;
parts = originHost.split('.');
this.logger.log(`Using Origin header hostname: ${originHost}, parts: ${JSON.stringify(parts)}`);
} catch (error) {
this.logger.warn(`Failed to parse origin: ${origin}`);
}
// Extract subdomain (e.g., "tenant1" from "tenant1.routebox.co")
if (parts.length >= 3) {
subdomain = parts[0];
if (subdomain === 'www') {
subdomain = null;
}
} else if (parts.length === 2 && parts[1] === 'localhost') {
subdomain = parts[0];
} else if (referer && !tenantId) {
// Fallback to Referer if no Origin
try {
const refererUrl = new URL(referer);
const refererHost = refererUrl.hostname;
parts = refererHost.split('.');
this.logger.log(`Using Referer header hostname: ${refererHost}, parts: ${JSON.stringify(parts)}`);
} catch (error) {
this.logger.warn(`Failed to parse referer: ${referer}`);
}
}
this.logger.log(`Extracted subdomain: ${subdomain}, x-tenant-id: ${tenantId}`);
// Extract subdomain (e.g., "tenant1" from "tenant1.routebox.co")
// For production domains with 3+ parts, extract first part as subdomain
if (parts.length >= 3) {
subdomain = parts[0];
// Ignore www subdomain
if (subdomain === 'www') {
subdomain = null;
}
}
// For development (e.g., tenant1.localhost), also check 2 parts
else if (parts.length === 2 && parts[1] === 'localhost') {
subdomain = parts[0];
}
this.logger.log(`Extracted subdomain: ${subdomain}`);
// Always attach subdomain to request if present
if (subdomain) {
@@ -122,7 +122,7 @@ export class TenantMiddleware implements NestMiddleware {
// Attach tenant info to request object
(req as any).tenantId = tenantId;
} else {
this.logger.warn(`No tenant identified from host: ${subdomain}`);
this.logger.warn(`No tenant identified from host: ${hostname}`);
}
next();

View File

@@ -98,75 +98,37 @@ export class VoiceController {
/**
* TwiML for outbound calls from browser (Twilio Device)
* Twilio sends application/x-www-form-urlencoded data
*/
@Post('twiml/outbound')
async outboundTwiml(@Req() req: FastifyRequest, @Res() res: FastifyReply) {
// Parse body - Twilio sends URL-encoded form data
let body = req.body as any;
// Handle case where body might be parsed as JSON key (URL-encoded string as key)
if (body && typeof body === 'object' && Object.keys(body).length === 1) {
const key = Object.keys(body)[0];
if (key.startsWith('{') || key.includes('=')) {
try {
// Try parsing as JSON if it looks like JSON
if (key.startsWith('{')) {
body = JSON.parse(key);
} else {
// Parse as URL-encoded
const params = new URLSearchParams(key);
body = Object.fromEntries(params.entries());
}
} catch (e) {
this.logger.warn(`Failed to re-parse body: ${e.message}`);
}
}
}
const body = req.body as any;
const to = body.To;
const from = body.From; // Format: "client:tenantId:userId"
const from = body.From;
const callSid = body.CallSid;
this.logger.log(`=== TwiML OUTBOUND REQUEST RECEIVED ===`);
this.logger.log(`CallSid: ${callSid}, From: ${from}, To: ${to}`);
this.logger.log(`CallSid: ${callSid}, Body From: ${from}, Body To: ${to}`);
this.logger.log(`Full body: ${JSON.stringify(body)}`);
try {
// Extract tenant ID from the client identity
// Format: "client:tenantId:userId"
let tenantId: string | null = null;
if (from && from.startsWith('client:')) {
const parts = from.replace('client:', '').split(':');
if (parts.length >= 2) {
tenantId = parts[0]; // First part is tenantId
this.logger.log(`Extracted tenantId from client identity: ${tenantId}`);
}
}
if (!tenantId) {
this.logger.error(`Could not extract tenant from From: ${from}`);
throw new Error('Could not determine tenant from call');
}
// Extract tenant domain from Host header
const host = req.headers.host || '';
const tenantDomain = host.split('.')[0]; // e.g., "tenant1" from "tenant1.routebox.co"
this.logger.log(`Extracted tenant domain: ${tenantDomain}`);
// Look up tenant's Twilio phone number from config
let callerId: string | undefined;
let callerId = to; // Fallback (will cause error if not found)
try {
const { config } = await this.voiceService['getTwilioClient'](tenantId);
// Get Twilio config to find the phone number
const { config } = await this.voiceService['getTwilioClient'](tenantDomain);
callerId = config.phoneNumber;
this.logger.log(`Retrieved Twilio phone number for tenant: ${callerId}`);
} catch (error: any) {
this.logger.error(`Failed to get Twilio config: ${error.message}`);
throw error;
}
if (!callerId) {
throw new Error('No caller ID configured for tenant');
}
const dialNumber = to?.trim();
if (!dialNumber) {
throw new Error('No destination number provided');
}
const dialNumber = to;
this.logger.log(`Using callerId: ${callerId}, dialNumber: ${dialNumber}`);
@@ -183,9 +145,10 @@ export class VoiceController {
} catch (error: any) {
this.logger.error(`=== ERROR GENERATING TWIML ===`);
this.logger.error(`Error: ${error.message}`);
this.logger.error(`Stack: ${error.stack}`);
const errorTwiml = `<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Say>An error occurred while processing your call. ${error.message}</Say>
<Say>An error occurred while processing your call.</Say>
</Response>`;
res.type('text/xml').send(errorTwiml);
}
@@ -193,33 +156,13 @@ export class VoiceController {
/**
* TwiML for inbound calls
* Twilio sends application/x-www-form-urlencoded data
*/
@Post('twiml/inbound')
async inboundTwiml(@Req() req: FastifyRequest, @Res() res: FastifyReply) {
// Parse body - Twilio sends URL-encoded form data
let body = req.body as any;
// Handle case where body might be parsed incorrectly
if (body && typeof body === 'object' && Object.keys(body).length === 1) {
const key = Object.keys(body)[0];
if (key.startsWith('{') || key.includes('=')) {
try {
if (key.startsWith('{')) {
body = JSON.parse(key);
} else {
const params = new URLSearchParams(key);
body = Object.fromEntries(params.entries());
}
} catch (e) {
this.logger.warn(`Failed to re-parse body: ${e.message}`);
}
}
}
const body = req.body as any;
const callSid = body.CallSid;
const fromNumber = body.From;
const toNumber = body.To; // This is the Twilio phone number that was called
const toNumber = body.To;
this.logger.log(`\n\n╔════════════════════════════════════════╗`);
this.logger.log(`║ === INBOUND CALL RECEIVED ===`);
@@ -227,28 +170,19 @@ export class VoiceController {
this.logger.log(`CallSid: ${callSid}`);
this.logger.log(`From: ${fromNumber}`);
this.logger.log(`To: ${toNumber}`);
this.logger.log(`Full body: ${JSON.stringify(body)}`);
try {
// Look up tenant by the Twilio phone number that was called
const tenantInfo = await this.voiceService.findTenantByPhoneNumber(toNumber);
// Extract tenant domain from Host header
const host = req.headers.host || '';
const tenantDomain = host.split('.')[0]; // e.g., "tenant1" from "tenant1.routebox.co"
if (!tenantInfo) {
this.logger.error(`No tenant found for phone number: ${toNumber}`);
const twiml = `<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Say>Sorry, this number is not configured. Please contact support.</Say>
<Hangup/>
</Response>`;
return res.type('text/xml').send(twiml);
}
const tenantId = tenantInfo.tenantId;
this.logger.log(`Found tenant: ${tenantId}`);
this.logger.log(`Extracted tenant domain: ${tenantDomain}`);
// Get all connected users for this tenant
const connectedUsers = this.voiceGateway.getConnectedUsers(tenantId);
const connectedUsers = this.voiceGateway.getConnectedUsers(tenantDomain);
this.logger.log(`Connected users for tenant ${tenantId}: ${connectedUsers.length}`);
this.logger.log(`Connected users for tenant ${tenantDomain}: ${connectedUsers.length}`);
if (connectedUsers.length > 0) {
this.logger.log(`Connected user IDs: ${connectedUsers.join(', ')}`);
}
@@ -264,22 +198,20 @@ export class VoiceController {
return res.type('text/xml').send(twiml);
}
// Build TwiML to dial all connected clients
// Client identity format is now: tenantId:userId
const clientElements = connectedUsers.map(userId => ` <Client>${tenantId}:${userId}</Client>`).join('\n');
// Build TwiML to dial all connected clients with Media Streams for AI
const clientElements = connectedUsers.map(userId => ` <Client>${userId}</Client>`).join('\n');
// Log the client identities being dialed
this.logger.log(`Client identities being dialed:`);
connectedUsers.forEach(userId => {
this.logger.log(` - ${tenantId}:${userId}`);
});
// Use wss:// for secure WebSocket
const host = req.headers.host || 'backend.routebox.co';
// Use wss:// for secure WebSocket (Traefik handles HTTPS)
const streamUrl = `wss://${host}/api/voice/media-stream`;
this.logger.log(`Stream URL: ${streamUrl}`);
this.logger.log(`Dialing ${connectedUsers.length} client(s)...`);
this.logger.log(`Client IDs to dial: ${connectedUsers.join(', ')}`);
// Verify we have client IDs in proper format
if (connectedUsers.length > 0) {
this.logger.log(`First Client ID format check: "${connectedUsers[0]}" (length: ${connectedUsers[0].length})`);
}
// Notify connected users about incoming call via Socket.IO
connectedUsers.forEach(userId => {
@@ -287,7 +219,7 @@ export class VoiceController {
callSid,
fromNumber,
toNumber,
tenantId,
tenantDomain,
});
});
@@ -295,7 +227,7 @@ export class VoiceController {
<Response>
<Start>
<Stream url="${streamUrl}">
<Parameter name="tenantId" value="${tenantId}"/>
<Parameter name="tenantId" value="${tenantDomain}"/>
<Parameter name="userId" value="${connectedUsers[0]}"/>
</Stream>
</Start>
@@ -304,7 +236,7 @@ ${clientElements}
</Dial>
</Response>`;
this.logger.log(`✓ Returning inbound TwiML - dialing ${connectedUsers.length} client(s)`);
this.logger.log(`✓ Returning inbound TwiML with Media Streams - dialing ${connectedUsers.length} client(s)`);
this.logger.log(`Generated TwiML:\n${twiml}\n`);
res.type('text/xml').send(twiml);
} catch (error: any) {

View File

@@ -61,41 +61,33 @@ export class VoiceGateway
const payload = await this.jwtService.verifyAsync(token);
// Extract domain from origin header (e.g., http://tenant1.routebox.co:3001)
// The domains table stores just the subdomain part (e.g., "tenant1")
const origin = client.handshake.headers.origin || client.handshake.headers.referer;
let subdomain = 'localhost';
let domain = 'localhost';
if (origin) {
try {
const url = new URL(origin);
const hostname = url.hostname;
subdomain = hostname.split('.')[0];
const hostname = url.hostname; // e.g., tenant1.routebox.co or localhost
// Extract first part of subdomain as domain
// tenant1.routebox.co -> tenant1
// localhost -> localhost
domain = hostname.split('.')[0];
} catch (error) {
this.logger.warn(`Failed to parse origin: ${origin}`);
}
}
// Resolve the actual tenantId (UUID) from the subdomain
let tenantId: string | null = null;
try {
const tenant = await this.tenantDbService.getTenantByDomain(subdomain);
if (tenant) {
tenantId = tenant.id;
this.logger.log(`Resolved tenant ${subdomain} -> ${tenantId}`);
}
} catch (error) {
this.logger.warn(`Failed to resolve tenant for subdomain ${subdomain}: ${error.message}`);
}
// Fall back to subdomain if tenant lookup fails
client.tenantId = tenantId || subdomain;
client.tenantId = domain; // Store the subdomain as tenantId
client.userId = payload.sub;
client.tenantSlug = subdomain;
client.tenantSlug = domain; // Same as subdomain
this.connectedUsers.set(client.userId, client);
this.logger.log(
`✓ Client connected: ${client.id} (User: ${client.userId}, TenantId: ${client.tenantId}, Subdomain: ${subdomain})`,
`✓ Client connected: ${client.id} (User: ${client.userId}, Domain: ${domain})`,
);
this.logger.log(`Total connected users in tenant ${client.tenantId}: ${this.getConnectedUsers(client.tenantId).length}`);
this.logger.log(`Total connected users in ${domain}: ${this.getConnectedUsers(domain).length}`);
// Send current call state if any active call
const activeCallSid = this.activeCallsByUser.get(client.userId);
@@ -311,14 +303,13 @@ export class VoiceGateway
/**
* Get connected users for a tenant
* @param tenantId - The tenant UUID to filter by
*/
getConnectedUsers(tenantId?: string): string[] {
getConnectedUsers(tenantDomain?: string): string[] {
const userIds: string[] = [];
for (const [userId, socket] of this.connectedUsers.entries()) {
// If tenantId specified, filter by tenant
if (!tenantId || socket.tenantId === tenantId) {
// If tenantDomain specified, filter by tenant
if (!tenantDomain || socket.tenantSlug === tenantDomain) {
userIds.push(userId);
}
}

View File

@@ -31,46 +31,46 @@ export class VoiceService {
/**
* Get Twilio client for a tenant
*/
private async getTwilioClient(tenantId: string): Promise<{ client: Twilio.Twilio; config: TwilioConfig; tenantId: string }> {
private async getTwilioClient(tenantIdOrDomain: string): Promise<{ client: Twilio.Twilio; config: TwilioConfig; tenantId: string }> {
// Check cache first
if (this.twilioClients.has(tenantId)) {
if (this.twilioClients.has(tenantIdOrDomain)) {
const centralPrisma = getCentralPrisma();
// Look up tenant by ID
const tenant = await centralPrisma.tenant.findUnique({
where: { id: tenantId },
select: { id: true, integrationsConfig: true },
// Look up tenant by domain
const domainRecord = await centralPrisma.domain.findUnique({
where: { domain: tenantIdOrDomain },
include: { tenant: { select: { id: true, integrationsConfig: true } } },
});
const config = this.getIntegrationConfig(tenant?.integrationsConfig as any);
const config = this.getIntegrationConfig(domainRecord?.tenant?.integrationsConfig as any);
return {
client: this.twilioClients.get(tenantId),
client: this.twilioClients.get(tenantIdOrDomain),
config: config.twilio,
tenantId: tenant.id
tenantId: domainRecord.tenant.id
};
}
// Fetch tenant integrations config
const centralPrisma = getCentralPrisma();
this.logger.log(`Looking up tenant: ${tenantId}`);
this.logger.log(`Looking up domain: ${tenantIdOrDomain}`);
const tenant = await centralPrisma.tenant.findUnique({
where: { id: tenantId },
select: { id: true, integrationsConfig: true },
const domainRecord = await centralPrisma.domain.findUnique({
where: { domain: tenantIdOrDomain },
include: { tenant: { select: { id: true, integrationsConfig: true } } },
});
this.logger.log(`Tenant found: ${!!tenant}, Config: ${!!tenant?.integrationsConfig}`);
this.logger.log(`Domain record found: ${!!domainRecord}, Tenant: ${!!domainRecord?.tenant}, Config: ${!!domainRecord?.tenant?.integrationsConfig}`);
if (!tenant) {
throw new Error(`Tenant ${tenantId} not found`);
if (!domainRecord?.tenant) {
throw new Error(`Domain ${tenantIdOrDomain} not found`);
}
if (!tenant.integrationsConfig) {
if (!domainRecord.tenant.integrationsConfig) {
throw new Error('Tenant integrations config not found. Please configure Twilio credentials in Settings > Integrations');
}
const config = this.getIntegrationConfig(tenant.integrationsConfig as any);
const config = this.getIntegrationConfig(domainRecord.tenant.integrationsConfig as any);
this.logger.log(`Config decrypted: ${!!config.twilio}, AccountSid: ${config.twilio?.accountSid?.substring(0, 10)}..., AuthToken: ${config.twilio?.authToken?.substring(0, 10)}..., Phone: ${config.twilio?.phoneNumber}`);
@@ -79,9 +79,9 @@ export class VoiceService {
}
const client = Twilio.default(config.twilio.accountSid, config.twilio.authToken);
this.twilioClients.set(tenantId, client);
this.twilioClients.set(tenantIdOrDomain, client);
return { client, config: config.twilio, tenantId: tenant.id };
return { client, config: config.twilio, tenantId: domainRecord.tenant.id };
}
/**
@@ -105,64 +105,22 @@ export class VoiceService {
return {};
}
/**
* Find tenant by their configured Twilio phone number
* Used for inbound call routing
*/
async findTenantByPhoneNumber(phoneNumber: string): Promise<{ tenantId: string; config: TwilioConfig } | null> {
const centralPrisma = getCentralPrisma();
// Normalize phone number (remove spaces, ensure + prefix for comparison)
const normalizedPhone = phoneNumber.replace(/\s+/g, '').replace(/^(\d)/, '+$1');
this.logger.log(`Looking up tenant by phone number: ${normalizedPhone}`);
// Get all tenants with integrations config
const tenants = await centralPrisma.tenant.findMany({
where: {
integrationsConfig: { not: null },
},
select: { id: true, integrationsConfig: true },
});
for (const tenant of tenants) {
const config = this.getIntegrationConfig(tenant.integrationsConfig as any);
if (config.twilio?.phoneNumber) {
const tenantPhone = config.twilio.phoneNumber.replace(/\s+/g, '').replace(/^(\d)/, '+$1');
if (tenantPhone === normalizedPhone) {
this.logger.log(`Found tenant ${tenant.id} for phone number ${normalizedPhone}`);
return { tenantId: tenant.id, config: config.twilio };
}
}
}
this.logger.warn(`No tenant found for phone number: ${normalizedPhone}`);
return null;
}
/**
* Generate Twilio access token for browser Voice SDK
*/
async generateAccessToken(tenantId: string, userId: string): Promise<string> {
const { config, tenantId: resolvedTenantId } = await this.getTwilioClient(tenantId);
async generateAccessToken(tenantDomain: string, userId: string): Promise<string> {
const { config, tenantId } = await this.getTwilioClient(tenantDomain);
if (!config.accountSid || !config.apiKey || !config.apiSecret) {
throw new Error('Twilio API credentials not configured. Please add API Key and Secret in Settings > Integrations');
}
// Include tenantId in the identity so we can extract it in TwiML webhooks
// Format: tenantId:userId
const identity = `${resolvedTenantId}:${userId}`;
this.logger.log(`Generating access token with identity: ${identity}`);
this.logger.log(` Input tenantId: ${tenantId}, Resolved tenantId: ${resolvedTenantId}, userId: ${userId}`);
// Create an access token
const token = new AccessToken(
config.accountSid,
config.apiKey,
config.apiSecret,
{ identity, ttl: 3600 } // 1 hour expiry
{ identity: userId, ttl: 3600 } // 1 hour expiry
);
// Create a Voice grant
@@ -478,28 +436,20 @@ export class VoiceService {
const { callSid, tenantId, userId } = params;
try {
// Get OpenAI config - tenantId might be a domain or a tenant ID (UUID or CUID)
// Get OpenAI config - tenantId might be a domain, so look it up
const centralPrisma = getCentralPrisma();
// Detect if tenantId looks like an ID (UUID or CUID) or a domain name
// UUIDs: 8-4-4-4-12 hex format
// CUIDs: 25 character alphanumeric starting with 'c'
const isUUID = /^[0-9a-f]{8}-[0-9a-f]{4}-/i.test(tenantId);
const isCUID = /^c[a-z0-9]{24}$/i.test(tenantId);
const isId = isUUID || isCUID;
// Try to find tenant by domain first (if tenantId is like "tenant1")
let tenant;
if (!isId) {
// Looks like a domain, not an ID
this.logger.log(`Looking up tenant by domain: ${tenantId}`);
if (!tenantId.match(/^[0-9a-f]{8}-[0-9a-f]{4}-/i)) {
// Looks like a domain, not a UUID
const domainRecord = await centralPrisma.domain.findUnique({
where: { domain: tenantId },
include: { tenant: { select: { id: true, integrationsConfig: true } } },
});
tenant = domainRecord?.tenant;
} else {
// It's an ID (UUID or CUID)
this.logger.log(`Looking up tenant by ID: ${tenantId}`);
// It's a UUID
tenant = await centralPrisma.tenant.findUnique({
where: { id: tenantId },
select: { id: true, integrationsConfig: true },

View File

@@ -17,7 +17,7 @@ import {
SidebarRail,
} from '@/components/ui/sidebar'
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible'
import { LayoutGrid, Boxes, Settings, Home, ChevronRight, Database, Layers, LogOut, Users, Globe, Building, Phone } from 'lucide-vue-next'
import { LayoutGrid, Boxes, Settings, Home, ChevronRight, Database, Layers, LogOut, Users, Globe, Building, ClipboardCheck, ListChecks, ClipboardList, Phone } from 'lucide-vue-next'
import { useSoftphone } from '~/composables/useSoftphone'
const { logout } = useAuth()
@@ -100,6 +100,21 @@ const staticMenuItems = [
url: '/',
icon: Home,
},
{
title: 'Approvals',
url: '/approvals',
icon: ClipboardCheck,
},
{
title: 'Tasks',
url: '/tasks',
icon: ListChecks,
},
{
title: 'Activity Log',
url: '/activity-log',
icon: ClipboardList,
},
{
title: 'Setup',
icon: Settings,
@@ -124,6 +139,11 @@ const staticMenuItems = [
url: '/setup/roles',
icon: Layers,
},
{
title: 'Approvals',
url: '/setup/approvals',
icon: ClipboardCheck,
},
{
title: 'Integrations',
url: '/settings/integrations',

View File

@@ -1,264 +0,0 @@
<template>
<div class="list-view-layout-editor">
<div class="flex h-full">
<!-- Selected Fields Area -->
<div class="flex-1 p-4 overflow-auto">
<div class="mb-4 flex justify-between items-center">
<h3 class="text-lg font-semibold">{{ layoutName || 'List View Layout' }}</h3>
<div class="flex gap-2">
<Button variant="outline" size="sm" @click="handleClear">
Clear All
</Button>
<Button size="sm" @click="handleSave">
Save Layout
</Button>
</div>
</div>
<div class="border rounded-lg bg-slate-50 dark:bg-slate-900 p-4 min-h-[400px]">
<p class="text-sm text-muted-foreground mb-4">
Drag fields to reorder them. Fields will appear in the list view in this order.
</p>
<div v-if="selectedFields.length === 0" class="text-center py-8 text-muted-foreground">
<p>No fields selected.</p>
<p class="text-sm">Click or drag fields from the right panel to add them.</p>
</div>
<div
v-else
ref="sortableContainer"
class="space-y-2"
>
<div
v-for="(field, index) in selectedFields"
:key="field.id"
class="p-3 border rounded cursor-move bg-white dark:bg-slate-800 hover:border-primary transition-colors flex items-center justify-between"
draggable="true"
@dragstart="handleDragStart($event, index)"
@dragover.prevent="handleDragOver($event, index)"
@drop="handleDrop($event, index)"
>
<div class="flex items-center gap-3">
<span class="text-muted-foreground cursor-grab">
<GripVertical class="w-4 h-4" />
</span>
<div>
<div class="font-medium text-sm">{{ field.label }}</div>
<div class="text-xs text-muted-foreground">
{{ field.apiName }} {{ formatFieldType(field.type) }}
</div>
</div>
</div>
<Button
variant="ghost"
size="sm"
class="text-destructive hover:text-destructive"
@click="removeField(field.id)"
>
<X class="w-4 h-4" />
</Button>
</div>
</div>
</div>
</div>
<!-- Available Fields Sidebar -->
<div class="w-80 border-l bg-white dark:bg-slate-950 p-4 overflow-auto">
<h3 class="text-lg font-semibold mb-4">Available Fields</h3>
<p class="text-xs text-muted-foreground mb-4">Click or drag to add field to list</p>
<div v-if="availableFields.length === 0" class="text-center py-4 text-muted-foreground text-sm">
All fields have been added to the layout.
</div>
<div v-else class="space-y-2">
<div
v-for="field in availableFields"
:key="field.id"
class="p-3 border rounded cursor-pointer bg-white dark:bg-slate-900 hover:border-primary hover:bg-slate-50 dark:hover:bg-slate-800 transition-colors"
draggable="true"
@dragstart="handleAvailableFieldDragStart($event, field)"
@click="addField(field)"
>
<div class="font-medium text-sm">{{ field.label }}</div>
<div class="text-xs text-muted-foreground">
{{ field.apiName }} {{ formatFieldType(field.type) }}
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { GripVertical, X } from 'lucide-vue-next'
import type { FieldLayoutItem } from '~/types/page-layout'
import type { FieldConfig } from '~/types/field-types'
import { Button } from '@/components/ui/button'
const props = defineProps<{
fields: FieldConfig[]
initialLayout?: FieldLayoutItem[]
layoutName?: string
}>()
const emit = defineEmits<{
save: [layout: { fields: FieldLayoutItem[] }]
}>()
// Selected fields in order
const selectedFieldIds = ref<string[]>([])
const draggedIndex = ref<number | null>(null)
const draggedAvailableField = ref<FieldConfig | null>(null)
// Initialize with initial layout
watch(() => props.initialLayout, (layout) => {
if (layout && layout.length > 0) {
// Sort by order if available, otherwise use array order
const sorted = [...layout].sort((a, b) => (a.order ?? 0) - (b.order ?? 0))
selectedFieldIds.value = sorted.map(item => item.fieldId)
}
}, { immediate: true })
// Computed selected fields in order
const selectedFields = computed(() => {
return selectedFieldIds.value
.map(id => props.fields.find(f => f.id === id))
.filter((f): f is FieldConfig => f !== undefined)
})
// Available fields (not selected)
const availableFields = computed(() => {
const selectedSet = new Set(selectedFieldIds.value)
return props.fields.filter(field => !selectedSet.has(field.id))
})
const formatFieldType = (type: string): string => {
const typeNames: Record<string, string> = {
'TEXT': 'Text',
'LONG_TEXT': 'Textarea',
'EMAIL': 'Email',
'PHONE': 'Phone',
'NUMBER': 'Number',
'CURRENCY': 'Currency',
'PERCENT': 'Percent',
'PICKLIST': 'Picklist',
'MULTI_PICKLIST': 'Multi-select',
'BOOLEAN': 'Checkbox',
'DATE': 'Date',
'DATE_TIME': 'DateTime',
'TIME': 'Time',
'URL': 'URL',
'LOOKUP': 'Lookup',
'FILE': 'File',
'IMAGE': 'Image',
'JSON': 'JSON',
'text': 'Text',
'textarea': 'Textarea',
'email': 'Email',
'number': 'Number',
'currency': 'Currency',
'select': 'Picklist',
'multiSelect': 'Multi-select',
'boolean': 'Checkbox',
'date': 'Date',
'datetime': 'DateTime',
'url': 'URL',
'lookup': 'Lookup',
'belongsTo': 'Lookup',
}
return typeNames[type] || type
}
const addField = (field: FieldConfig) => {
if (!selectedFieldIds.value.includes(field.id)) {
selectedFieldIds.value.push(field.id)
}
}
const removeField = (fieldId: string) => {
selectedFieldIds.value = selectedFieldIds.value.filter(id => id !== fieldId)
}
// Drag and drop for reordering
const handleDragStart = (event: DragEvent, index: number) => {
draggedIndex.value = index
draggedAvailableField.value = null
if (event.dataTransfer) {
event.dataTransfer.effectAllowed = 'move'
}
}
const handleDragOver = (event: DragEvent, index: number) => {
event.preventDefault()
if (event.dataTransfer) {
event.dataTransfer.dropEffect = 'move'
}
}
const handleDrop = (event: DragEvent, targetIndex: number) => {
event.preventDefault()
// Handle drop from available fields
if (draggedAvailableField.value) {
addField(draggedAvailableField.value)
// Move the newly added field to the target position
const newFieldId = draggedAvailableField.value.id
const currentIndex = selectedFieldIds.value.indexOf(newFieldId)
if (currentIndex !== -1 && currentIndex !== targetIndex) {
const ids = [...selectedFieldIds.value]
ids.splice(currentIndex, 1)
ids.splice(targetIndex, 0, newFieldId)
selectedFieldIds.value = ids
}
draggedAvailableField.value = null
return
}
// Handle reordering within selected fields
if (draggedIndex.value === null || draggedIndex.value === targetIndex) {
draggedIndex.value = null
return
}
const ids = [...selectedFieldIds.value]
const [removed] = ids.splice(draggedIndex.value, 1)
ids.splice(targetIndex, 0, removed)
selectedFieldIds.value = ids
draggedIndex.value = null
}
// Drag from available fields
const handleAvailableFieldDragStart = (event: DragEvent, field: FieldConfig) => {
draggedAvailableField.value = field
draggedIndex.value = null
if (event.dataTransfer) {
event.dataTransfer.effectAllowed = 'copy'
}
}
const handleClear = () => {
if (confirm('Are you sure you want to clear all fields from the layout?')) {
selectedFieldIds.value = []
}
}
const handleSave = () => {
const layout: FieldLayoutItem[] = selectedFieldIds.value.map((fieldId, index) => ({
fieldId,
order: index,
}))
emit('save', { fields: layout })
}
</script>
<style scoped>
.list-view-layout-editor {
height: calc(100vh - 300px);
min-height: 500px;
}
</style>

View File

@@ -3,32 +3,90 @@ import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
const config = useRuntimeConfig()
const router = useRouter()
const { toast } = useToast()
const { login, isLoading } = useAuth()
// Cookie for server-side auth check
const tokenCookie = useCookie('token')
// Extract subdomain from hostname (e.g., tenant1.localhost → tenant1)
const getSubdomain = () => {
if (!import.meta.client) return null
const hostname = window.location.hostname
const parts = hostname.split('.')
console.log('Extracting subdomain from:', hostname, 'parts:', parts)
// For localhost development: tenant1.localhost or localhost
if (hostname === 'localhost' || hostname === '127.0.0.1') {
return null // Use default tenant for plain localhost
}
// For subdomains like tenant1.routebox.co or tenant1.localhost
if (parts.length >= 2 && parts[0] !== 'www') {
console.log('Using subdomain:', parts[0])
return parts[0] // Return subdomain
}
return null
}
const subdomain = ref(getSubdomain())
const email = ref('')
const password = ref('')
const loading = ref(false)
const error = ref('')
const handleLogin = async () => {
try {
loading.value = true
error.value = ''
// Use the BFF login endpoint via useAuth
const result = await login(email.value, password.value)
if (result.success) {
toast.success('Login successful!')
// Redirect to home
router.push('/')
} else {
error.value = result.error || 'Login failed'
toast.error(result.error || 'Login failed')
const headers: Record<string, string> = {
'Content-Type': 'application/json',
}
// Only send x-tenant-id if we have a subdomain
if (subdomain.value) {
headers['x-tenant-id'] = subdomain.value
}
const response = await fetch(`${config.public.apiBaseUrl}/api/auth/login`, {
method: 'POST',
headers,
body: JSON.stringify({
email: email.value,
password: password.value,
}),
})
if (!response.ok) {
const data = await response.json()
throw new Error(data.message || 'Login failed')
}
const data = await response.json()
// Store credentials in localStorage
// Store the tenant ID that was used for login
const tenantToStore = subdomain.value || data.user?.tenantId || 'tenant1'
localStorage.setItem('tenantId', tenantToStore)
localStorage.setItem('token', data.access_token)
localStorage.setItem('user', JSON.stringify(data.user))
// Also store token in cookie for server-side auth check
tokenCookie.value = data.access_token
toast.success('Login successful!')
// Redirect to home
router.push('/')
} catch (e: any) {
error.value = e.message || 'Login failed'
toast.error(e.message || 'Login failed')
} finally {
loading.value = false
}
}
</script>
@@ -60,8 +118,8 @@ const handleLogin = async () => {
</div>
<Input id="password" v-model="password" type="password" required />
</div>
<Button type="submit" class="w-full" :disabled="isLoading">
{{ isLoading ? 'Logging in...' : 'Login' }}
<Button type="submit" class="w-full" :disabled="loading">
{{ loading ? 'Logging in...' : 'Login' }}
</Button>
</div>
<div class="text-center text-sm">

View File

@@ -85,31 +85,9 @@ const formatValue = (val: any): string => {
case FieldType.BELONGS_TO:
return relationshipDisplayValue.value
case FieldType.DATE:
try {
const date = val instanceof Date ? val : new Date(val)
return date.toLocaleDateString(undefined, {
year: 'numeric',
month: '2-digit',
day: '2-digit'
})
} catch {
return String(val)
}
return val instanceof Date ? val.toLocaleDateString() : new Date(val).toLocaleDateString()
case FieldType.DATETIME:
try {
const date = val instanceof Date ? val : new Date(val)
return date.toLocaleString(undefined, {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false
})
} catch {
return String(val)
}
return val instanceof Date ? val.toLocaleString() : new Date(val).toLocaleString()
case FieldType.BOOLEAN:
return val ? 'Yes' : 'No'
case FieldType.CURRENCY:

View File

@@ -1,9 +1,5 @@
<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import type { CellValueChangedEvent, ColDef, GridApi, GridReadyEvent } from 'ag-grid-community'
import { AgGridVue } from 'ag-grid-vue3'
import 'ag-grid-community/styles/ag-grid.css'
import 'ag-grid-community/styles/ag-theme-alpine.css'
import {
Table,
TableBody,
@@ -18,7 +14,7 @@ import { Badge } from '@/components/ui/badge'
import { Checkbox } from '@/components/ui/checkbox'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import FieldRenderer from '@/components/fields/FieldRenderer.vue'
import { ListViewConfig, ViewMode, FieldType, FieldConfig } from '@/types/field-types'
import { ListViewConfig, ViewMode, FieldType } from '@/types/field-types'
import { ChevronDown, ChevronUp, Search, Plus, Download, Trash2, Edit } from 'lucide-vue-next'
interface Props {
@@ -29,9 +25,6 @@ interface Props {
baseUrl?: string
totalCount?: number
searchSummary?: string
draftEdits?: Record<string, Record<string, any>>
cellErrors?: Record<string, Record<string, string | boolean>>
savingDrafts?: boolean
}
const props = withDefaults(defineProps<Props>(), {
@@ -40,9 +33,6 @@ const props = withDefaults(defineProps<Props>(), {
selectable: false,
baseUrl: '/runtime/objects',
searchSummary: '',
draftEdits: () => ({}),
cellErrors: () => ({}),
savingDrafts: false,
})
const emit = defineEmits<{
@@ -57,10 +47,6 @@ const emit = defineEmits<{
'refresh': []
'page-change': [page: number, pageSize: number]
'load-more': [page: number, pageSize: number]
'view-change': [mode: 'list' | 'spreadsheet']
'cell-edit': [payload: { row: any; field: FieldConfig; newValue: any; oldValue: any }]
'save-drafts': []
'discard-drafts': []
}>()
// State
@@ -71,8 +57,6 @@ const sortField = ref<string>('')
const sortDirection = ref<'asc' | 'desc'>('asc')
const currentPage = ref(1)
const bulkAction = ref('delete')
const viewMode = ref<'list' | 'spreadsheet'>('list')
const gridApi = ref<GridApi | null>(null)
// Computed
const visibleFields = computed(() =>
@@ -103,7 +87,7 @@ const paginatedData = computed(() => {
})
const pageStart = computed(() => (props.data.length === 0 ? 0 : startIndex.value + 1))
const pageEnd = computed(() => Math.min(startIndex.value + paginatedData.value.length, totalRecords.value))
const showPagination = computed(() => viewMode.value === 'list' && totalRecords.value > pageSize.value)
const showPagination = computed(() => totalRecords.value > pageSize.value)
const canGoPrev = computed(() => currentPage.value > 1)
const canGoNext = computed(() => currentPage.value < availablePages.value)
const showLoadMore = computed(() => (
@@ -111,8 +95,6 @@ const showLoadMore = computed(() => (
Boolean(props.totalCount) &&
props.data.length < totalRecords.value
))
const draftRowCount = computed(() => Object.keys(props.draftEdits).length)
const draftCellCount = computed(() => Object.values(props.draftEdits).reduce((sum, row) => sum + Object.keys(row).length, 0))
const allSelected = computed({
get: () => props.data.length > 0 && selectedRowIds.value.length === props.data.length,
@@ -177,154 +159,6 @@ const handleBulkAction = () => {
emit('action', bulkAction.value, getSelectedRows())
}
const isEditableField = (field: FieldConfig) =>
field.showOnEdit !== false &&
!field.isReadOnly &&
![FieldType.BELONGS_TO, FieldType.HAS_MANY, FieldType.MANY_TO_MANY].includes(field.type)
const getRelationPropertyName = (apiName: string) => apiName.replace(/Id$/, '').toLowerCase()
const formatFieldValue = (field: FieldConfig, value: any, record?: any) => {
if (value === null || value === undefined) return ''
switch (field.type) {
case FieldType.BELONGS_TO: {
const relationPropertyName = getRelationPropertyName(field.apiName)
const relatedObject = record?.[relationPropertyName]
if (relatedObject && typeof relatedObject === 'object') {
const displayField = field.relationDisplayField || 'name'
return relatedObject[displayField] || relatedObject.id || value
}
return value
}
case FieldType.DATE: {
const date = value instanceof Date ? value : new Date(value)
return Number.isNaN(date.getTime())
? String(value)
: date.toLocaleDateString(undefined, { year: 'numeric', month: '2-digit', day: '2-digit' })
}
case FieldType.DATETIME: {
const date = value instanceof Date ? value : new Date(value)
return Number.isNaN(date.getTime())
? String(value)
: date.toLocaleString(undefined, {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false,
})
}
case FieldType.BOOLEAN:
return value ? 'Yes' : 'No'
case FieldType.CURRENCY:
return `${field.prefix || '$'}${Number(value).toFixed(2)}${field.suffix || ''}`
case FieldType.SELECT: {
const option = field.options?.find(opt => opt.value === value)
return option?.label || value
}
case FieldType.MULTI_SELECT:
return Array.isArray(value)
? value
.map(v => field.options?.find(opt => opt.value === v)?.label || v)
.join(', ')
: ''
default:
return String(value)
}
}
const hasOwnProperty = (target: Record<string, any> | undefined, key: string) =>
!!target && Object.prototype.hasOwnProperty.call(target, key)
const isDraftCell = (params: any) => {
const rowId = normalizeId(params?.data?.id)
const field = String(params?.colDef?.field || '')
return hasOwnProperty(props.draftEdits[rowId], field)
}
const isErrorCell = (params: any) => {
const rowId = normalizeId(params?.data?.id)
const field = String(params?.colDef?.field || '')
return hasOwnProperty(props.cellErrors[rowId], field)
}
const getCellClasses = (params: any) => {
const classes: string[] = []
if (isDraftCell(params)) classes.push('cell-draft')
if (isErrorCell(params)) classes.push('cell-error')
return classes
}
const getCellStyle = (params: any) => {
const isDraft = isDraftCell(params)
const isError = isErrorCell(params)
if (!isDraft && !isError) return null
const style: Record<string, string> = {}
if (isDraft) {
style.backgroundColor = 'hsl(var(--accent) / 0.45)'
style.outline = '2px solid hsl(var(--accent))'
style.outlineOffset = '-2px'
}
if (isError) {
style.backgroundColor = 'hsl(var(--destructive) / 0.28)'
style.outline = '2px solid hsl(var(--destructive))'
style.outlineOffset = '-2px'
}
return style
}
const columnDefs = computed<ColDef[]>(() =>
visibleFields.value.map(field => ({
field: field.apiName,
headerName: field.label,
sortable: field.sortable !== false,
editable: isEditableField(field),
valueFormatter: params => formatFieldValue(field, params.value, params.data),
cellClass: params => getCellClasses(params),
cellStyle: params => getCellStyle(params),
cellEditor:
field.type === FieldType.SELECT
? 'agSelectCellEditor'
: field.type === FieldType.MULTI_SELECT
? 'agTextCellEditor'
: field.type === FieldType.NUMBER || field.type === FieldType.CURRENCY
? 'agTextCellEditor'
: undefined,
cellEditorParams:
field.type === FieldType.SELECT
? { values: (field.options || []).map(opt => opt.value) }
: undefined,
valueParser:
field.type === FieldType.NUMBER || field.type === FieldType.CURRENCY
? params => (params.newValue === '' ? null : Number(params.newValue))
: undefined,
flex: 1,
minWidth: 160,
}))
)
const defaultColDef: ColDef = {
resizable: true,
sortable: true,
}
const handleCellValueChanged = (event: CellValueChangedEvent) => {
const field = visibleFields.value.find(item => item.apiName === event.colDef.field)
if (!field || event.newValue === event.oldValue) return
emit('cell-edit', {
row: event.data,
field,
newValue: event.newValue,
oldValue: event.oldValue,
})
}
const handleGridReady = (event: GridReadyEvent) => {
gridApi.value = event.api
}
const goToPage = (page: number) => {
const nextPage = Math.min(Math.max(page, 1), availablePages.value)
if (nextPage !== currentPage.value) {
@@ -359,23 +193,6 @@ watch(
},
{ deep: true }
)
watch(
() => viewMode.value,
(mode) => {
emit('view-change', mode)
}
)
watch(
() => [props.draftEdits, props.cellErrors],
() => {
if (gridApi.value) {
gridApi.value.refreshCells({ force: true })
}
},
{ deep: true }
)
</script>
<template>
@@ -399,35 +216,6 @@ watch(
</div>
<div class="flex items-center gap-2">
<Select v-model="viewMode">
<SelectTrigger class="h-8 w-[180px]">
<SelectValue placeholder="Select view" />
</SelectTrigger>
<SelectContent>
<SelectItem value="list">List view</SelectItem>
<SelectItem value="spreadsheet">Spreadsheet view</SelectItem>
</SelectContent>
</Select>
<template v-if="viewMode === 'spreadsheet'">
<Badge v-if="draftRowCount > 0" variant="secondary" class="px-3 py-1">
{{ draftCellCount }} change{{ draftCellCount === 1 ? '' : 's' }}
</Badge>
<Button
variant="outline"
size="sm"
:disabled="draftRowCount === 0 || savingDrafts"
@click="emit('discard-drafts')"
>
Discard changes
</Button>
<Button
size="sm"
:disabled="draftRowCount === 0 || savingDrafts"
@click="emit('save-drafts')"
>
Save changes ({{ draftRowCount }})
</Button>
</template>
<!-- Bulk Actions -->
<template v-if="selectedRowIds.length > 0">
<Badge variant="secondary" class="px-3 py-1">
@@ -476,7 +264,7 @@ watch(
<!-- Table -->
<div class="border rounded-lg">
<Table v-if="viewMode === 'list'">
<Table>
<TableHeader>
<TableRow>
<TableHead v-if="selectable" class="w-12">
@@ -550,19 +338,6 @@ watch(
</TableRow>
</TableBody>
</Table>
<div v-else class="ag-theme-alpine">
<AgGridVue
:row-data="data"
:column-defs="columnDefs"
:default-col-def="defaultColDef"
dom-layout="autoHeight"
row-selection="multiple"
suppress-row-click-selection
single-click-edit
@cell-value-changed="handleCellValueChanged"
@grid-ready="handleGridReady"
/>
</div>
</div>
<div v-if="showPagination" class="flex flex-wrap items-center justify-between gap-3 text-sm text-muted-foreground">
@@ -600,5 +375,4 @@ watch(
.list-view :deep(input) {
background-color: hsl(var(--background));
}
</style>

View File

@@ -1,25 +1,40 @@
export const useApi = () => {
const config = useRuntimeConfig()
const router = useRouter()
const { toast } = useToast()
const { isLoggedIn, logout } = useAuth()
/**
* API calls now go through the Nitro BFF proxy at /api/*
* The proxy handles:
* - Auth token injection from HTTP-only cookies
* - Tenant subdomain extraction and forwarding
* - Forwarding requests to the NestJS backend
*/
// Use current domain for API calls (same subdomain routing)
const getApiBaseUrl = () => {
// All API calls go through Nitro proxy - works for both SSR and client
return ''
if (import.meta.client) {
// In browser, use current hostname but with port 3000 for API
const currentHost = window.location.hostname
const protocol = window.location.protocol
//return `${protocol}//${currentHost}:3000`
return `${protocol}//${currentHost}`
}
// Fallback for SSR
return config.public.apiBaseUrl
}
const getHeaders = () => {
// Headers are now minimal - auth and tenant are handled by the Nitro proxy
const headers: Record<string, string> = {
'Content-Type': 'application/json',
}
// Add tenant ID from localStorage or state
if (import.meta.client) {
const tenantId = localStorage.getItem('tenantId')
if (tenantId) {
headers['x-tenant-id'] = tenantId
}
const token = localStorage.getItem('token')
if (token) {
headers['Authorization'] = `Bearer ${token}`
}
}
return headers
}

View File

@@ -1,131 +1,61 @@
/**
* Authentication composable using BFF (Backend for Frontend) pattern
* Auth tokens are stored in HTTP-only cookies managed by Nitro server
* Tenant context is stored in a readable cookie for client-side access
*/
export const useAuth = () => {
const tokenCookie = useCookie('token')
const authMessageCookie = useCookie('authMessage')
const tenantCookie = useCookie('routebox_tenant')
const router = useRouter()
const config = useRuntimeConfig()
// Reactive user state - populated from /api/auth/me
const user = useState<any>('auth_user', () => null)
const isAuthenticated = useState<boolean>('auth_is_authenticated', () => false)
const isLoading = useState<boolean>('auth_is_loading', () => false)
/**
* Check if user is logged in
* Uses server-side session validation via /api/auth/me
*/
const isLoggedIn = () => {
return isAuthenticated.value
if (!import.meta.client) return false
const token = localStorage.getItem('token')
const tenantId = localStorage.getItem('tenantId')
return !!(token && tenantId)
}
/**
* Login with email and password
* Calls the Nitro BFF login endpoint which sets HTTP-only cookies
*/
const login = async (email: string, password: string) => {
isLoading.value = true
try {
const response = await $fetch('/api/auth/login', {
method: 'POST',
body: { email, password },
})
if (response.success) {
user.value = response.user
isAuthenticated.value = true
return { success: true, user: response.user }
}
return { success: false, error: 'Login failed' }
} catch (error: any) {
const message = error.data?.message || error.message || 'Login failed'
return { success: false, error: message }
} finally {
isLoading.value = false
}
}
/**
* Logout user
* Calls the Nitro BFF logout endpoint which clears HTTP-only cookies
*/
const logout = async () => {
try {
await $fetch('/api/auth/logout', {
method: 'POST',
})
} catch (error) {
console.error('Logout error:', error)
}
// Clear local state
user.value = null
isAuthenticated.value = false
// Set flash message for login page
authMessageCookie.value = 'Logged out successfully'
// Redirect to login page
router.push('/login')
}
/**
* Check current authentication status
* Validates session with backend via Nitro BFF
*/
const checkAuth = async () => {
isLoading.value = true
try {
const response = await $fetch('/api/auth/me', {
method: 'GET',
})
if (response.authenticated && response.user) {
user.value = response.user
isAuthenticated.value = true
return true
if (import.meta.client) {
// Call backend logout endpoint
try {
const token = localStorage.getItem('token')
const tenantId = localStorage.getItem('tenantId')
if (token) {
await fetch(`${config.public.apiBaseUrl}/api/auth/logout`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
...(tenantId && { 'x-tenant-id': tenantId }),
},
})
}
} catch (error) {
console.error('Logout error:', error)
}
} catch (error) {
// Session invalid or expired
user.value = null
isAuthenticated.value = false
} finally {
isLoading.value = false
// Clear local storage
localStorage.removeItem('token')
localStorage.removeItem('tenantId')
localStorage.removeItem('user')
// Clear cookie for server-side check
tokenCookie.value = null
// Set flash message for login page
authMessageCookie.value = 'Logged out successfully'
// Redirect to login page
router.push('/login')
}
return false
}
/**
* Get current user
*/
const getUser = () => {
return user.value
}
/**
* Get current tenant ID from cookie
*/
const getTenantId = () => {
return tenantCookie.value
if (!import.meta.client) return null
const userStr = localStorage.getItem('user')
return userStr ? JSON.parse(userStr) : null
}
return {
// State
user,
isAuthenticated,
isLoading,
// Methods
isLoggedIn,
login,
logout,
checkAuth,
getUser,
getTenantId,
}
}

View File

@@ -20,9 +20,6 @@ export const useFields = () => {
// Hide system fields and auto-generated fields on edit
const shouldHideOnEdit = isSystemField || isAutoGeneratedField
// Hide 'id' field from list view by default (check both apiName and id field)
const shouldHideOnList = fieldDef.apiName === 'id' || fieldDef.label === 'Id' || fieldDef.label === 'ID'
return {
id: fieldDef.id,
apiName: fieldDef.apiName,
@@ -40,7 +37,7 @@ export const useFields = () => {
validationRules: fieldDef.validationRules || [],
// View options - only hide system and auto-generated fields by default
showOnList: fieldDef.showOnList ?? !shouldHideOnList,
showOnList: fieldDef.showOnList ?? true,
showOnDetail: fieldDef.showOnDetail ?? true,
showOnEdit: fieldDef.showOnEdit ?? !shouldHideOnEdit,
sortable: fieldDef.sortable ?? true,
@@ -70,36 +67,12 @@ export const useFields = () => {
/**
* Build a ListView configuration from object definition
* @param objectDef - The object definition containing fields
* @param customConfig - Optional custom configuration
* @param listLayoutConfig - Optional list view layout configuration from page_layouts
*/
const buildListViewConfig = (
objectDef: any,
customConfig?: Partial<ListViewConfig>,
listLayoutConfig?: { fields: Array<{ fieldId: string; order?: number }> } | null
customConfig?: Partial<ListViewConfig>
): ListViewConfig => {
let fields = objectDef.fields?.map(mapFieldDefinitionToConfig) || []
// If a list layout is provided, filter and order fields according to it
if (listLayoutConfig && listLayoutConfig.fields && listLayoutConfig.fields.length > 0) {
// Sort layout fields by order
const sortedLayoutFields = [...listLayoutConfig.fields].sort((a, b) => (a.order ?? 0) - (b.order ?? 0))
// Map layout fields to actual field configs, preserving order
const orderedFields: FieldConfig[] = []
for (const layoutField of sortedLayoutFields) {
const fieldConfig = fields.find((f: FieldConfig) => f.id === layoutField.fieldId)
if (fieldConfig) {
orderedFields.push(fieldConfig)
}
}
// Use ordered fields if we found any, otherwise fall back to all fields
if (orderedFields.length > 0) {
fields = orderedFields
}
}
const fields = objectDef.fields?.map(mapFieldDefinitionToConfig) || []
return {
objectApiName: objectDef.apiName,

View File

@@ -1,13 +1,11 @@
import type { PageLayout, CreatePageLayoutRequest, UpdatePageLayoutRequest, PageLayoutType } from '~/types/page-layout'
import type { PageLayout, CreatePageLayoutRequest, UpdatePageLayoutRequest } from '~/types/page-layout'
export const usePageLayouts = () => {
const { api } = useApi()
const getPageLayouts = async (objectId?: string, layoutType?: PageLayoutType) => {
const getPageLayouts = async (objectId?: string) => {
try {
const params: Record<string, string> = {}
if (objectId) params.objectId = objectId
if (layoutType) params.layoutType = layoutType
const params = objectId ? { objectId } : {}
const response = await api.get('/page-layouts', { params })
return response
} catch (error) {
@@ -26,11 +24,9 @@ export const usePageLayouts = () => {
}
}
const getDefaultPageLayout = async (objectId: string, layoutType: PageLayoutType = 'detail') => {
const getDefaultPageLayout = async (objectId: string) => {
try {
const response = await api.get(`/page-layouts/default/${objectId}`, {
params: { layoutType }
})
const response = await api.get(`/page-layouts/default/${objectId}`)
return response
} catch (error) {
console.error('Error fetching default page layout:', error)

View File

@@ -1,4 +1,4 @@
import { ref, computed, onMounted, onUnmounted, shallowRef, watch } from 'vue';
import { ref, computed, onMounted, onUnmounted, shallowRef } from 'vue';
import { io, Socket } from 'socket.io-client';
import { Device, Call as TwilioCall } from '@twilio/voice-sdk';
import { useAuth } from './useAuth';
@@ -44,6 +44,17 @@ const volume = ref(100);
export function useSoftphone() {
const auth = useAuth();
// Get token and tenantId from localStorage
const getToken = () => {
if (typeof window === 'undefined') return null;
return localStorage.getItem('token');
};
const getTenantId = () => {
if (typeof window === 'undefined') return null;
return localStorage.getItem('tenantId');
};
// Computed properties
const isInCall = computed(() => currentCall.value !== null);
const hasIncomingCall = computed(() => incomingCall.value !== null);
@@ -82,12 +93,6 @@ export function useSoftphone() {
* Initialize Twilio Device
*/
const initializeTwilioDevice = async () => {
// Prevent re-initialization if device already exists and is registered
if (twilioDevice.value) {
console.log('Twilio Device already exists, skipping initialization');
return;
}
try {
// First, explicitly request microphone permission
const hasPermission = await requestMicrophonePermission();
@@ -102,14 +107,12 @@ export function useSoftphone() {
// Log the token payload to see what identity is being used
try {
const tokenPayload = JSON.parse(atob(token.split('.')[1]));
console.log('📱 Twilio Device identity:', tokenPayload.grants?.identity || tokenPayload.sub);
} catch (e) {
console.log('Could not parse token payload');
}
console.log('📱 Creating new Twilio Device...');
twilioDevice.value = new Device(token, {
logLevel: 1, // Reduce log level (1 = errors only, 3 = debug)
logLevel: 3,
codecPreferences: ['opus', 'pcmu'],
enableImprovedSignalingErrorPrecision: true,
edge: 'ashburn',
@@ -117,12 +120,10 @@ export function useSoftphone() {
// Device events
twilioDevice.value.on('registered', () => {
console.log('✅ Twilio Device registered successfully');
toast.success('Softphone ready');
});
twilioDevice.value.on('unregistered', () => {
console.log('📱 Twilio Device unregistered');
});
twilioDevice.value.on('error', (error) => {
@@ -131,11 +132,6 @@ export function useSoftphone() {
});
twilioDevice.value.on('incoming', (call: TwilioCall) => {
console.log('📞 Twilio Device incoming call event!', {
callSid: call.parameters.CallSid,
from: call.parameters.From,
to: call.parameters.To,
});
twilioCall.value = call;
// Update state
@@ -214,54 +210,35 @@ export function useSoftphone() {
/**
* Initialize WebSocket connection
*/
const connect = async () => {
// Guard against multiple connection attempts
if (socket.value) {
console.log('Softphone: Socket already exists, skipping connection');
const connect = () => {
const token = getToken();
if (socket.value?.connected || !token) {
return;
}
// Check if user is authenticated
if (!auth.isAuthenticated.value) {
// Try to verify authentication first
const isValid = await auth.checkAuth();
if (!isValid) {
console.log('Softphone: User not authenticated, skipping connection');
return;
// Use same pattern as useApi to preserve subdomain for multi-tenant
const getBackendUrl = () => {
if (typeof window !== 'undefined') {
const currentHost = window.location.hostname;
const protocol = window.location.protocol;
return `${protocol}//${currentHost}`;
}
}
return 'http://localhost:3000';
};
try {
// Get WebSocket token from BFF (this retrieves the token from HTTP-only cookie server-side)
const wsAuth = await $fetch('/api/auth/ws-token');
if (!wsAuth.token) {
console.log('Softphone: No WebSocket token available');
return;
}
// Use same pattern as useApi to preserve subdomain for multi-tenant
const getBackendUrl = () => {
if (typeof window !== 'undefined') {
const currentHost = window.location.hostname;
const protocol = window.location.protocol;
return `${protocol}//${currentHost}`;
}
return 'http://localhost:3000';
};
// Connect to /voice namespace with proper auth header
socket.value = io(`${getBackendUrl()}/voice`, {
auth: {
token: wsAuth.token,
},
transports: ['websocket', 'polling'],
reconnection: true,
reconnectionDelay: 1000,
reconnectionDelayMax: 5000,
reconnectionAttempts: 5,
query: {}, // Explicitly set empty query to prevent token leaking
});
// Connect to /voice namespace with proper auth header
socket.value = io(`${getBackendUrl()}/voice`, {
auth: {
token: token,
},
transports: ['websocket', 'polling'],
reconnection: true,
reconnectionDelay: 1000,
reconnectionDelayMax: 5000,
reconnectionAttempts: 5,
query: {}, // Explicitly set empty query to prevent token leaking
});
// Connection events
socket.value.on('connect', () => {
@@ -302,10 +279,6 @@ export function useSoftphone() {
socket.value.on('ai:action', handleAiAction);
isInitialized.value = true;
} catch (error: any) {
console.error('Softphone: Failed to connect:', error);
toast.error('Failed to initialize voice service');
}
};
/**
@@ -596,25 +569,14 @@ export function useSoftphone() {
}
};
// Only set up auto-connect and watchers once (not for every component that uses this composable)
// Use a module-level flag to track if watchers are already set up
if (process.client && !isInitialized.value && !socket.value) {
// Auto-connect if authenticated
if (auth.isAuthenticated.value) {
// Auto-connect on mount if token is available
onMounted(() => {
if (getToken() && !isInitialized.value) {
connect();
}
});
// Watch for authentication changes to connect/disconnect
watch(() => auth.isAuthenticated.value, async (isAuth) => {
if (isAuth && !isInitialized.value && !socket.value) {
await connect();
} else if (!isAuth && isInitialized.value) {
disconnect();
}
});
}
// Cleanup on unmount - only stop ringtone, don't disconnect shared socket
// Cleanup on unmount
onUnmounted(() => {
stopRingtone();
});

View File

@@ -1,4 +1,4 @@
export default defineNuxtRouteMiddleware(async (to, from) => {
export default defineNuxtRouteMiddleware((to, from) => {
// Allow pages to opt-out of auth with definePageMeta({ auth: false })
if (to.meta.auth === false) {
return
@@ -11,45 +11,28 @@ export default defineNuxtRouteMiddleware(async (to, from) => {
return
}
const token = useCookie('token')
const authMessage = useCookie('authMessage')
// Check for tenant cookie (set alongside session cookie on login)
const tenantCookie = useCookie('routebox_tenant')
// Also check for session cookie (HTTP-only, but readable in SSR context)
const sessionCookie = useCookie('routebox_session')
// Routes that don't need a toast message (user knows they need to login)
const silentRoutes = ['/']
// On client side, check the reactive auth state
if (import.meta.client) {
const { isAuthenticated, checkAuth } = useAuth()
// If we already know we're authenticated, allow
if (isAuthenticated.value) {
return
}
// If we have a tenant cookie, try to validate the session
if (tenantCookie.value) {
const isValid = await checkAuth()
if (isValid) {
return
}
}
// Not authenticated
// Check token cookie (works on both server and client)
if (!token.value) {
if (!silentRoutes.includes(to.path)) {
authMessage.value = 'Please login to access this page'
}
return navigateTo('/login')
}
// Server-side: check for both session and tenant cookies
// The session cookie is HTTP-only but can be read in SSR context
if (!sessionCookie.value || !tenantCookie.value) {
if (!silentRoutes.includes(to.path)) {
authMessage.value = 'Please login to access this page'
// On client side, also verify localStorage is in sync
if (import.meta.client) {
const { isLoggedIn } = useAuth()
if (!isLoggedIn()) {
if (!silentRoutes.includes(to.path)) {
authMessage.value = 'Please login to access this page'
}
return navigateTo('/login')
}
return navigateTo('/login')
}
})

View File

@@ -24,9 +24,9 @@ export default defineNuxtConfig({
},
runtimeConfig: {
// Server-only config (not exposed to client)
// Used by Nitro BFF to proxy requests to the NestJS backend
backendUrl: process.env.BACKEND_URL || 'http://localhost:3000',
public: {
apiBaseUrl: process.env.NUXT_PUBLIC_API_BASE_URL || 'http://localhost:3000',
},
},
app: {

File diff suppressed because it is too large Load Diff

View File

@@ -19,8 +19,6 @@
"@nuxtjs/tailwindcss": "^6.11.4",
"@twilio/voice-sdk": "^2.11.2",
"@vueuse/core": "^10.11.1",
"ag-grid-community": "^32.3.4",
"ag-grid-vue3": "^32.3.4",
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.0",
"gridstack": "^12.4.1",

View File

@@ -3,7 +3,6 @@ import { ref, computed, onMounted, onBeforeUnmount, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useApi } from '@/composables/useApi'
import { useFields, useViewState } from '@/composables/useFieldViews'
import { usePageLayouts } from '@/composables/usePageLayouts'
import ListView from '@/components/views/ListView.vue'
import DetailView from '@/components/views/DetailViewEnhanced.vue'
import EditView from '@/components/views/EditViewEnhanced.vue'
@@ -20,7 +19,6 @@ const route = useRoute()
const router = useRouter()
const { api } = useApi()
const { buildListViewConfig, buildDetailViewConfig, buildEditViewConfig } = useFields()
const { getDefaultPageLayout } = usePageLayouts()
// Use breadcrumbs composable
const { setBreadcrumbs } = useBreadcrumbs()
@@ -42,7 +40,6 @@ const view = computed(() => {
// State
const objectDefinition = ref<any>(null)
const listViewLayout = ref<any>(null)
const loading = ref(true)
const error = ref<string | null>(null)
@@ -57,7 +54,6 @@ const {
fetchRecord,
deleteRecord,
deleteRecords,
updateRecord,
handleSave,
} = useViewState(`/runtime/objects/${objectApiName.value}/records`)
@@ -138,13 +134,11 @@ watch([objectDefinition, currentRecord, recordId], () => {
// View configs
const listConfig = computed(() => {
if (!objectDefinition.value) return null
// Pass the list view layout config to buildListViewConfig if available
const layoutConfig = listViewLayout.value?.layout_config || listViewLayout.value?.layoutConfig
return buildListViewConfig(objectDefinition.value, {
searchable: true,
exportable: true,
filterable: true,
}, layoutConfig)
})
})
const detailConfig = computed(() => {
@@ -166,12 +160,6 @@ const deleteDialogOpen = ref(false)
const deleteSubmitting = ref(false)
const pendingDeleteRows = ref<any[]>([])
const deleteSummary = ref<{ deletedIds: string[]; deniedIds: string[] } | null>(null)
const normalizeRecordId = (id: any) => String(id)
const draftEdits = ref<Record<string, Record<string, any>>>({})
const draftOriginals = ref<Record<string, Record<string, any>>>({})
const cellErrors = ref<Record<string, Record<string, string>>>({})
const savingDrafts = ref(false)
const isSearchActive = computed(() => searchQuery.value.trim().length > 0)
const pendingDeleteCount = computed(() => pendingDeleteRows.value.length)
@@ -184,16 +172,6 @@ const fetchObjectDefinition = async () => {
error.value = null
const response = await api.get(`/setup/objects/${objectApiName.value}`)
objectDefinition.value = response
// Fetch the default list view layout for this object
if (response?.id) {
try {
listViewLayout.value = await getDefaultPageLayout(response.id, 'list')
} catch (e) {
// No list view layout configured, will use default behavior
listViewLayout.value = null
}
}
} catch (e: any) {
error.value = e.message || 'Failed to load object definition'
console.error('Error fetching object definition:', e)
@@ -362,22 +340,6 @@ const handleLoadMore = async (page: number, pageSize: number) => {
await loadListRecords(page, { append: true, pageSize })
}
const loadAllListRecords = async () => {
if (!records.value.length) {
await loadListRecords(1)
}
const resolvedTotal = totalCount.value ?? records.value.length
if (resolvedTotal > records.value.length) {
await loadListRecords(1, { append: false, pageSize: resolvedTotal })
}
}
const handleViewChange = async (mode: 'list' | 'spreadsheet') => {
if (mode === 'spreadsheet' && !isSearchActive.value) {
await loadAllListRecords()
}
}
const handleSearch = async (query: string) => {
const trimmed = query.trim()
searchQuery.value = trimmed
@@ -389,140 +351,6 @@ const handleSearch = async (query: string) => {
await searchListRecords(1, { append: false, pageSize: listPageSize.value })
}
const handleCellEdit = async (payload: { row: any; field: any; newValue: any; oldValue: any }) => {
if (!payload?.row?.id || payload.newValue === payload.oldValue) return
const recordKey = normalizeRecordId(payload.row.id)
const fieldName = payload.field.apiName
const originalRow = draftOriginals.value[recordKey]
const originalValue = originalRow && Object.prototype.hasOwnProperty.call(originalRow, fieldName)
? originalRow[fieldName]
: payload.oldValue
if (Object.is(payload.newValue, originalValue)) {
const nextDrafts = { ...draftEdits.value }
const nextRowDrafts = { ...(nextDrafts[recordKey] || {}) }
delete nextRowDrafts[fieldName]
if (Object.keys(nextRowDrafts).length === 0) {
delete nextDrafts[recordKey]
} else {
nextDrafts[recordKey] = nextRowDrafts
}
draftEdits.value = nextDrafts
const nextOriginals = { ...draftOriginals.value }
const nextRowOriginals = { ...(nextOriginals[recordKey] || {}) }
delete nextRowOriginals[fieldName]
if (Object.keys(nextRowOriginals).length === 0) {
delete nextOriginals[recordKey]
} else {
nextOriginals[recordKey] = nextRowOriginals
}
draftOriginals.value = nextOriginals
} else {
draftEdits.value = {
...draftEdits.value,
[recordKey]: {
...(draftEdits.value[recordKey] || {}),
[fieldName]: payload.newValue,
},
}
if (!originalRow || !Object.prototype.hasOwnProperty.call(originalRow, fieldName)) {
draftOriginals.value = {
...draftOriginals.value,
[recordKey]: {
...(draftOriginals.value[recordKey] || {}),
[fieldName]: payload.oldValue,
},
}
}
}
if (cellErrors.value[recordKey]?.[fieldName]) {
const nextErrors = { ...cellErrors.value }
const nextRowErrors = { ...(nextErrors[recordKey] || {}) }
delete nextRowErrors[fieldName]
if (Object.keys(nextRowErrors).length === 0) {
delete nextErrors[recordKey]
} else {
nextErrors[recordKey] = nextRowErrors
}
cellErrors.value = nextErrors
}
}
const handleSaveDrafts = async () => {
if (Object.keys(draftEdits.value).length === 0) return
savingDrafts.value = true
const nextErrors: Record<string, Record<string, string>> = {}
const nextDrafts = { ...draftEdits.value }
const nextOriginals = { ...draftOriginals.value }
for (const [recordKey, changes] of Object.entries(draftEdits.value)) {
const record = records.value.find(item => normalizeRecordId(item.id) === recordKey)
if (!record) {
delete nextDrafts[recordKey]
delete nextOriginals[recordKey]
continue
}
try {
await updateRecord(record.id, changes)
delete nextDrafts[recordKey]
delete nextOriginals[recordKey]
} catch (e: any) {
const message = e.message || 'Failed to update record'
nextErrors[recordKey] = {}
for (const fieldName of Object.keys(changes)) {
nextErrors[recordKey][fieldName] = message
}
}
}
draftEdits.value = nextDrafts
draftOriginals.value = nextOriginals
cellErrors.value = nextErrors
savingDrafts.value = false
if (Object.keys(nextErrors).length > 0) {
error.value = 'Some updates failed. Fix highlighted cells and try again.'
}
}
const handleDiscardDrafts = () => {
for (const [recordKey, fields] of Object.entries(draftOriginals.value)) {
const record = records.value.find(item => normalizeRecordId(item.id) === recordKey)
if (!record) continue
for (const [fieldName, originalValue] of Object.entries(fields)) {
record[fieldName] = originalValue
}
}
draftEdits.value = {}
draftOriginals.value = {}
cellErrors.value = {}
}
watch(
() => records.value.map(record => normalizeRecordId(record.id)),
(ids) => {
const idSet = new Set(ids)
const nextDrafts: Record<string, Record<string, any>> = {}
const nextOriginals: Record<string, Record<string, any>> = {}
const nextErrors: Record<string, Record<string, string>> = {}
for (const [recordKey, fields] of Object.entries(draftEdits.value)) {
if (idSet.has(recordKey)) nextDrafts[recordKey] = fields
}
for (const [recordKey, fields] of Object.entries(draftOriginals.value)) {
if (idSet.has(recordKey)) nextOriginals[recordKey] = fields
}
for (const [recordKey, fields] of Object.entries(cellErrors.value)) {
if (idSet.has(recordKey)) nextErrors[recordKey] = fields
}
draftEdits.value = nextDrafts
draftOriginals.value = nextOriginals
cellErrors.value = nextErrors
}
)
// Watch for route changes
watch(() => route.params, async (newParams, oldParams) => {
// Reset current record when navigating to 'new'
@@ -595,9 +423,6 @@ onMounted(async () => {
:total-count="totalCount"
:search-summary="searchSummary"
:base-url="`/runtime/objects`"
:draft-edits="draftEdits"
:cell-errors="cellErrors"
:saving-drafts="savingDrafts"
selectable
@row-click="handleRowClick"
@create="handleCreate"
@@ -606,10 +431,6 @@ onMounted(async () => {
@search="handleSearch"
@page-change="handlePageChange"
@load-more="handleLoadMore"
@view-change="handleViewChange"
@cell-edit="handleCellEdit"
@save-drafts="handleSaveDrafts"
@discard-drafts="handleDiscardDrafts"
/>
<!-- Detail View -->

View File

@@ -0,0 +1,70 @@
<template>
<div class="min-h-screen bg-background">
<NuxtLayout name="default">
<main class="container mx-auto px-4 py-8">
<div v-if="loading" class="text-center py-12">Loading...</div>
<div v-else-if="error" class="text-destructive">Error: {{ error }}</div>
<div v-else>
<div class="flex items-center justify-between mb-6">
<h1 class="text-3xl font-bold">Activity Log</h1>
<button
@click="fetchActivities"
class="px-4 py-2 bg-secondary text-secondary-foreground rounded-md hover:bg-secondary/90"
>
Refresh
</button>
</div>
<div class="grid gap-4">
<div
v-for="activity in activities"
:key="activity.id"
class="p-6 border rounded-lg bg-card"
>
<div class="flex items-center justify-between mb-2">
<h3 class="text-lg font-semibold">{{ activity.action }}</h3>
<span class="text-xs text-muted-foreground">{{ formatDate(activity.createdAt) }}</span>
</div>
<p class="text-sm text-muted-foreground mb-2">
{{ activity.description || 'No description' }}
</p>
<div class="text-sm text-muted-foreground">
<div>Subject: {{ activity.subjectType }} {{ activity.subjectId }}</div>
<div>Causer: {{ activity.causerId || 'System' }}</div>
</div>
</div>
</div>
</div>
</main>
</NuxtLayout>
</div>
</template>
<script setup lang="ts">
const { api } = useApi()
const activities = ref<any[]>([])
const loading = ref(true)
const error = ref<string | null>(null)
const formatDate = (value?: string) => {
if (!value) return '—'
const date = new Date(value)
return date.toLocaleString()
}
const fetchActivities = async () => {
try {
loading.value = true
activities.value = await api.get('/activity-log')
} catch (e: any) {
error.value = e.message
} finally {
loading.value = false
}
}
onMounted(() => {
fetchActivities()
})
</script>

View File

@@ -3,7 +3,6 @@ import { ref, computed, onMounted, onBeforeUnmount, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useApi } from '@/composables/useApi'
import { useFields, useViewState } from '@/composables/useFieldViews'
import { usePageLayouts } from '@/composables/usePageLayouts'
import ListView from '@/components/views/ListView.vue'
import DetailView from '@/components/views/DetailView.vue'
import EditView from '@/components/views/EditView.vue'
@@ -12,7 +11,6 @@ const route = useRoute()
const router = useRouter()
const { api } = useApi()
const { buildListViewConfig, buildDetailViewConfig, buildEditViewConfig } = useFields()
const { getDefaultPageLayout } = usePageLayouts()
// Get object API name from route
const objectApiName = computed(() => route.params.objectName as string)
@@ -27,7 +25,6 @@ const view = computed(() => {
// State
const objectDefinition = ref<any>(null)
const listViewLayout = ref<any>(null)
const loading = ref(true)
const error = ref<string | null>(null)
@@ -42,7 +39,6 @@ const {
fetchRecord,
deleteRecord,
deleteRecords,
updateRecord,
handleSave,
} = useViewState(`/runtime/objects/${objectApiName.value}/records`)
@@ -70,13 +66,11 @@ onBeforeUnmount(() => {
// View configs
const listConfig = computed(() => {
if (!objectDefinition.value) return null
// Pass the list view layout config to buildListViewConfig if available
const layoutConfig = listViewLayout.value?.layout_config || listViewLayout.value?.layoutConfig
return buildListViewConfig(objectDefinition.value, {
searchable: true,
exportable: true,
filterable: true,
}, layoutConfig)
})
})
const detailConfig = computed(() => {
@@ -91,12 +85,6 @@ const editConfig = computed(() => {
const listPageSize = computed(() => listConfig.value?.pageSize ?? 25)
const maxFrontendRecords = computed(() => listConfig.value?.maxFrontendRecords ?? 500)
const normalizeRecordId = (id: any) => String(id)
const draftEdits = ref<Record<string, Record<string, any>>>({})
const draftOriginals = ref<Record<string, Record<string, any>>>({})
const cellErrors = ref<Record<string, Record<string, string>>>({})
const savingDrafts = ref(false)
// Fetch object definition
const fetchObjectDefinition = async () => {
@@ -105,16 +93,6 @@ const fetchObjectDefinition = async () => {
error.value = null
const response = await api.get(`/setup/objects/${objectApiName.value}`)
objectDefinition.value = response
// Fetch the default list view layout for this object
if (response?.id) {
try {
listViewLayout.value = await getDefaultPageLayout(response.id, 'list')
} catch (e) {
// No list view layout configured, will use default behavior
listViewLayout.value = null
}
}
} catch (e: any) {
error.value = e.message || 'Failed to load object definition'
console.error('Error fetching object definition:', e)
@@ -219,156 +197,6 @@ const handleLoadMore = async (page: number, pageSize: number) => {
await loadListRecords(page, { append: true, pageSize })
}
const loadAllListRecords = async () => {
if (!records.value.length) {
await loadListRecords(1)
}
const resolvedTotal = totalCount.value ?? records.value.length
if (resolvedTotal > records.value.length) {
await loadListRecords(1, { append: false, pageSize: resolvedTotal })
}
}
const handleViewChange = async (mode: 'list' | 'spreadsheet') => {
if (mode === 'spreadsheet') {
await loadAllListRecords()
}
}
const handleCellEdit = async (payload: { row: any; field: any; newValue: any; oldValue: any }) => {
if (!payload?.row?.id || payload.newValue === payload.oldValue) return
const recordKey = normalizeRecordId(payload.row.id)
const fieldName = payload.field.apiName
const originalRow = draftOriginals.value[recordKey]
const originalValue = originalRow && Object.prototype.hasOwnProperty.call(originalRow, fieldName)
? originalRow[fieldName]
: payload.oldValue
if (Object.is(payload.newValue, originalValue)) {
const nextDrafts = { ...draftEdits.value }
const nextRowDrafts = { ...(nextDrafts[recordKey] || {}) }
delete nextRowDrafts[fieldName]
if (Object.keys(nextRowDrafts).length === 0) {
delete nextDrafts[recordKey]
} else {
nextDrafts[recordKey] = nextRowDrafts
}
draftEdits.value = nextDrafts
const nextOriginals = { ...draftOriginals.value }
const nextRowOriginals = { ...(nextOriginals[recordKey] || {}) }
delete nextRowOriginals[fieldName]
if (Object.keys(nextRowOriginals).length === 0) {
delete nextOriginals[recordKey]
} else {
nextOriginals[recordKey] = nextRowOriginals
}
draftOriginals.value = nextOriginals
} else {
draftEdits.value = {
...draftEdits.value,
[recordKey]: {
...(draftEdits.value[recordKey] || {}),
[fieldName]: payload.newValue,
},
}
if (!originalRow || !Object.prototype.hasOwnProperty.call(originalRow, fieldName)) {
draftOriginals.value = {
...draftOriginals.value,
[recordKey]: {
...(draftOriginals.value[recordKey] || {}),
[fieldName]: payload.oldValue,
},
}
}
}
if (cellErrors.value[recordKey]?.[fieldName]) {
const nextErrors = { ...cellErrors.value }
const nextRowErrors = { ...(nextErrors[recordKey] || {}) }
delete nextRowErrors[fieldName]
if (Object.keys(nextRowErrors).length === 0) {
delete nextErrors[recordKey]
} else {
nextErrors[recordKey] = nextRowErrors
}
cellErrors.value = nextErrors
}
}
const handleSaveDrafts = async () => {
if (Object.keys(draftEdits.value).length === 0) return
savingDrafts.value = true
const nextErrors: Record<string, Record<string, string>> = {}
const nextDrafts = { ...draftEdits.value }
const nextOriginals = { ...draftOriginals.value }
for (const [recordKey, changes] of Object.entries(draftEdits.value)) {
const record = records.value.find(item => normalizeRecordId(item.id) === recordKey)
if (!record) {
delete nextDrafts[recordKey]
delete nextOriginals[recordKey]
continue
}
try {
await updateRecord(record.id, changes)
delete nextDrafts[recordKey]
delete nextOriginals[recordKey]
} catch (e: any) {
const message = e.message || 'Failed to update record'
nextErrors[recordKey] = {}
for (const fieldName of Object.keys(changes)) {
nextErrors[recordKey][fieldName] = message
}
}
}
draftEdits.value = nextDrafts
draftOriginals.value = nextOriginals
cellErrors.value = nextErrors
savingDrafts.value = false
if (Object.keys(nextErrors).length > 0) {
error.value = 'Some updates failed. Fix highlighted cells and try again.'
}
}
const handleDiscardDrafts = () => {
for (const [recordKey, fields] of Object.entries(draftOriginals.value)) {
const record = records.value.find(item => normalizeRecordId(item.id) === recordKey)
if (!record) continue
for (const [fieldName, originalValue] of Object.entries(fields)) {
record[fieldName] = originalValue
}
}
draftEdits.value = {}
draftOriginals.value = {}
cellErrors.value = {}
}
watch(
() => records.value.map(record => normalizeRecordId(record.id)),
(ids) => {
const idSet = new Set(ids)
const nextDrafts: Record<string, Record<string, any>> = {}
const nextOriginals: Record<string, Record<string, any>> = {}
const nextErrors: Record<string, Record<string, string>> = {}
for (const [recordKey, fields] of Object.entries(draftEdits.value)) {
if (idSet.has(recordKey)) nextDrafts[recordKey] = fields
}
for (const [recordKey, fields] of Object.entries(draftOriginals.value)) {
if (idSet.has(recordKey)) nextOriginals[recordKey] = fields
}
for (const [recordKey, fields] of Object.entries(cellErrors.value)) {
if (idSet.has(recordKey)) nextErrors[recordKey] = fields
}
draftEdits.value = nextDrafts
draftOriginals.value = nextOriginals
cellErrors.value = nextErrors
}
)
// Watch for route changes
watch(() => route.params, async (newParams, oldParams) => {
// Reset current record when navigating to 'new'
@@ -435,9 +263,6 @@ onMounted(async () => {
:data="records"
:loading="dataLoading"
:total-count="totalCount"
:draft-edits="draftEdits"
:cell-errors="cellErrors"
:saving-drafts="savingDrafts"
selectable
@row-click="handleRowClick"
@create="handleCreate"
@@ -445,10 +270,6 @@ onMounted(async () => {
@delete="handleDelete"
@page-change="handlePageChange"
@load-more="handleLoadMore"
@view-change="handleViewChange"
@cell-edit="handleCellEdit"
@save-drafts="handleSaveDrafts"
@discard-drafts="handleDiscardDrafts"
/>
<!-- Detail View -->

View File

@@ -0,0 +1,232 @@
<template>
<div class="min-h-screen bg-background">
<NuxtLayout name="default">
<main class="container mx-auto px-4 py-8">
<div v-if="loading" class="text-center py-12">Loading...</div>
<div v-else-if="error" class="text-destructive">Error: {{ error }}</div>
<div v-else>
<div class="flex items-center justify-between mb-6">
<h1 class="text-3xl font-bold">Approval Requests</h1>
<button
@click="showCreateForm = true"
class="px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary/90"
>
New Request
</button>
</div>
<div v-if="showCreateForm" class="mb-6 p-6 border rounded-lg bg-card">
<h2 class="text-xl font-semibold mb-4">Create Approval Request</h2>
<form @submit.prevent="createRequest" class="space-y-4">
<div>
<label class="block text-sm font-medium mb-2">Definition</label>
<select
v-model="newRequest.definitionId"
required
class="w-full px-3 py-2 border rounded-md bg-background"
>
<option value="" disabled>Select a definition</option>
<option v-for="definition in definitions" :key="definition.id" :value="definition.id">
{{ definition.name }}
</option>
</select>
</div>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<label class="block text-sm font-medium mb-2">Target Object Type</label>
<input
v-model="newRequest.targetObjectType"
type="text"
required
class="w-full px-3 py-2 border rounded-md bg-background"
placeholder="Expense"
/>
</div>
<div>
<label class="block text-sm font-medium mb-2">Target Object ID</label>
<input
v-model="newRequest.targetObjectId"
type="text"
required
class="w-full px-3 py-2 border rounded-md bg-background"
placeholder="record-id"
/>
</div>
</div>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<label class="block text-sm font-medium mb-2">Action</label>
<input
v-model="newRequest.action"
type="text"
class="w-full px-3 py-2 border rounded-md bg-background"
placeholder="submit"
/>
</div>
<div>
<label class="block text-sm font-medium mb-2">Submitted By (User ID)</label>
<input
v-model="newRequest.submittedById"
type="text"
class="w-full px-3 py-2 border rounded-md bg-background"
placeholder="user-id"
/>
</div>
</div>
<div>
<label class="block text-sm font-medium mb-2">Snapshot (JSON)</label>
<textarea
v-model="newRequest.snapshot"
class="w-full px-3 py-2 border rounded-md bg-background font-mono text-sm"
rows="3"
placeholder='{"amount": 1200, "currency": "USD"}'
/>
</div>
<div>
<label class="block text-sm font-medium mb-2">Field Changes (JSON)</label>
<textarea
v-model="newRequest.fieldChanges"
class="w-full px-3 py-2 border rounded-md bg-background font-mono text-sm"
rows="3"
placeholder='{"amount": {"from": 500, "to": 1200}}'
/>
</div>
<div class="flex gap-2">
<button
type="submit"
class="px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary/90"
>
Create
</button>
<button
type="button"
@click="showCreateForm = false"
class="px-4 py-2 bg-secondary text-secondary-foreground rounded-md hover:bg-secondary/90"
>
Cancel
</button>
</div>
</form>
</div>
<div class="grid gap-4">
<div
v-for="request in requests"
:key="request.id"
class="p-6 border rounded-lg bg-card"
>
<div class="flex items-center justify-between mb-4">
<div>
<h3 class="text-lg font-semibold">{{ request.definition?.name || 'Approval Request' }}</h3>
<p class="text-sm text-muted-foreground">
{{ request.targetObjectType }} {{ request.targetObjectId }}
</p>
</div>
<span
class="text-xs px-2 py-1 rounded"
:class="statusClass(request.status)"
>
{{ request.status }}
</span>
</div>
<div class="text-sm text-muted-foreground">
<div>Steps: {{ request.steps?.length || 0 }}</div>
<div>Submitted: {{ formatDate(request.submittedAt) }}</div>
</div>
</div>
</div>
</div>
</main>
</NuxtLayout>
</div>
</template>
<script setup lang="ts">
const { api } = useApi()
const requests = ref<any[]>([])
const definitions = ref<any[]>([])
const loading = ref(true)
const error = ref<string | null>(null)
const showCreateForm = ref(false)
const newRequest = ref({
definitionId: '',
targetObjectType: '',
targetObjectId: '',
action: '',
submittedById: '',
snapshot: '',
fieldChanges: '',
})
const parseJson = (value: string) => {
if (!value) return undefined
try {
return JSON.parse(value)
} catch (err) {
return undefined
}
}
const statusClass = (status: string) => {
if (status === 'approved') return 'bg-primary/10 text-primary'
if (status === 'rejected') return 'bg-destructive/10 text-destructive'
return 'bg-muted text-muted-foreground'
}
const formatDate = (value?: string) => {
if (!value) return '—'
const date = new Date(value)
return date.toLocaleString()
}
const fetchRequests = async () => {
try {
loading.value = true
requests.value = await api.get('/approvals')
} catch (e: any) {
error.value = e.message
} finally {
loading.value = false
}
}
const fetchDefinitions = async () => {
try {
definitions.value = await api.get('/setup/approvals')
} catch (e) {
definitions.value = []
}
}
const createRequest = async () => {
try {
await api.post('/approvals', {
definitionId: newRequest.value.definitionId,
targetObjectType: newRequest.value.targetObjectType,
targetObjectId: newRequest.value.targetObjectId,
action: newRequest.value.action || undefined,
submittedById: newRequest.value.submittedById || undefined,
snapshot: parseJson(newRequest.value.snapshot),
fieldChanges: parseJson(newRequest.value.fieldChanges),
})
showCreateForm.value = false
newRequest.value = {
definitionId: '',
targetObjectType: '',
targetObjectId: '',
action: '',
submittedById: '',
snapshot: '',
fieldChanges: '',
}
await fetchRequests()
} catch (e: any) {
alert('Error creating approval request: ' + e.message)
}
}
onMounted(async () => {
await Promise.all([fetchRequests(), fetchDefinitions()])
})
</script>

View File

@@ -74,8 +74,24 @@ definePageMeta({
auth: false
})
const config = useRuntimeConfig()
const router = useRouter()
// Extract subdomain from hostname
const getSubdomain = () => {
if (!import.meta.client) return null
const hostname = window.location.hostname
const parts = hostname.split('.')
if (hostname === 'localhost' || hostname === '127.0.0.1') {
return null
}
if (parts.length > 1 && parts[0] !== 'www') {
return parts[0]
}
return null
}
const subdomain = ref(getSubdomain())
const email = ref('')
const password = ref('')
const firstName = ref('')
@@ -90,17 +106,30 @@ const handleRegister = async () => {
error.value = ''
success.value = false
// Use BFF proxy - subdomain/tenant is handled automatically by Nitro
await $fetch('/api/auth/register', {
const headers: Record<string, string> = {
'Content-Type': 'application/json',
}
if (subdomain.value) {
headers['x-tenant-id'] = subdomain.value
}
const response = await fetch(`${config.public.apiBaseUrl}/api/auth/register`, {
method: 'POST',
body: {
headers,
body: JSON.stringify({
email: email.value,
password: password.value,
firstName: firstName.value || undefined,
lastName: lastName.value || undefined,
},
}),
})
if (!response.ok) {
const data = await response.json()
throw new Error(data.message || 'Registration failed')
}
success.value = true
// Redirect to login after 2 seconds
@@ -108,10 +137,9 @@ const handleRegister = async () => {
router.push('/login')
}, 2000)
} catch (e: any) {
error.value = e.data?.message || e.message || 'Registration failed'
error.value = e.message || 'Registration failed'
} finally {
loading.value = false
}
}
</script>

View File

@@ -0,0 +1,241 @@
<template>
<div class="min-h-screen bg-background">
<NuxtLayout name="default">
<main class="container mx-auto px-4 py-8">
<div v-if="loading" class="text-center py-12">Loading...</div>
<div v-else-if="error" class="text-destructive">Error: {{ error }}</div>
<div v-else>
<div class="flex items-center justify-between mb-6">
<h1 class="text-3xl font-bold">Approval Definitions</h1>
<button
@click="showCreateForm = true"
class="px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary/90"
>
New Definition
</button>
</div>
<div v-if="showCreateForm" class="mb-6 p-6 border rounded-lg bg-card">
<h2 class="text-xl font-semibold mb-4">Create Approval Definition</h2>
<form @submit.prevent="createDefinition" class="space-y-4">
<div>
<label class="block text-sm font-medium mb-2">Name</label>
<input
v-model="newDefinition.name"
type="text"
required
class="w-full px-3 py-2 border rounded-md bg-background"
placeholder="Expense Approval"
/>
</div>
<div>
<label class="block text-sm font-medium mb-2">Trigger Type</label>
<select
v-model="newDefinition.triggerType"
required
class="w-full px-3 py-2 border rounded-md bg-background"
>
<option value="action">Action</option>
<option value="state_transition">State Transition</option>
<option value="field_change">Field Change</option>
</select>
</div>
<div>
<label class="block text-sm font-medium mb-2">Target Object Type</label>
<input
v-model="newDefinition.targetObjectType"
type="text"
class="w-full px-3 py-2 border rounded-md bg-background"
placeholder="Expense"
/>
</div>
<div>
<label class="block text-sm font-medium mb-2">Description</label>
<textarea
v-model="newDefinition.description"
class="w-full px-3 py-2 border rounded-md bg-background"
rows="2"
/>
</div>
<div>
<label class="block text-sm font-medium mb-2">Entry Criteria (JSON)</label>
<textarea
v-model="newDefinition.entryCriteria"
class="w-full px-3 py-2 border rounded-md bg-background font-mono text-sm"
rows="3"
placeholder='{"amount": {"gte": 500}}'
/>
</div>
<div>
<label class="block text-sm font-medium mb-2">Steps (JSON Array)</label>
<textarea
v-model="newDefinition.steps"
class="w-full px-3 py-2 border rounded-md bg-background font-mono text-sm"
rows="4"
placeholder='[{"key":"manager","name":"Manager Review","assignees":[]}]'
/>
</div>
<div>
<label class="block text-sm font-medium mb-2">Voting Policy (JSON)</label>
<textarea
v-model="newDefinition.votingPolicy"
class="w-full px-3 py-2 border rounded-md bg-background font-mono text-sm"
rows="3"
placeholder='{"type":"majority"}'
/>
</div>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<label class="block text-sm font-medium mb-2">Rejection Rule</label>
<input
v-model="newDefinition.rejectionRule"
type="text"
class="w-full px-3 py-2 border rounded-md bg-background"
placeholder="any"
/>
</div>
<div>
<label class="block text-sm font-medium mb-2">Material Change Policy</label>
<input
v-model="newDefinition.materialChangePolicy"
type="text"
class="w-full px-3 py-2 border rounded-md bg-background"
placeholder="invalidate"
/>
</div>
</div>
<div class="flex items-center gap-2">
<input id="isActive" v-model="newDefinition.isActive" type="checkbox" />
<label for="isActive" class="text-sm">Active</label>
</div>
<div class="flex gap-2">
<button
type="submit"
class="px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary/90"
>
Create
</button>
<button
type="button"
@click="showCreateForm = false"
class="px-4 py-2 bg-secondary text-secondary-foreground rounded-md hover:bg-secondary/90"
>
Cancel
</button>
</div>
</form>
</div>
<div class="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
<div
v-for="definition in definitions"
:key="definition.id"
class="p-6 border rounded-lg bg-card"
>
<div class="flex items-start justify-between mb-2">
<h3 class="text-xl font-semibold">{{ definition.name }}</h3>
<span
class="text-xs px-2 py-1 rounded"
:class="definition.isActive ? 'bg-primary/10 text-primary' : 'bg-muted text-muted-foreground'"
>
{{ definition.isActive ? 'Active' : 'Inactive' }}
</span>
</div>
<p class="text-sm text-muted-foreground mb-4">
{{ definition.description || 'No description' }}
</p>
<div class="text-sm space-y-1">
<div><span class="text-muted-foreground">Trigger:</span> {{ definition.triggerType }}</div>
<div>
<span class="text-muted-foreground">Target:</span>
{{ definition.targetObjectType || 'Any' }}
</div>
<div>
<span class="text-muted-foreground">Version:</span> {{ definition.version }}
</div>
</div>
</div>
</div>
</div>
</main>
</NuxtLayout>
</div>
</template>
<script setup lang="ts">
const { api } = useApi()
const definitions = ref<any[]>([])
const loading = ref(true)
const error = ref<string | null>(null)
const showCreateForm = ref(false)
const newDefinition = ref({
name: '',
triggerType: 'action',
targetObjectType: '',
description: '',
entryCriteria: '',
steps: '',
votingPolicy: '',
rejectionRule: 'any',
materialChangePolicy: 'invalidate',
isActive: true,
})
const parseJson = (value: string) => {
if (!value) return undefined
try {
return JSON.parse(value)
} catch (err) {
return undefined
}
}
const fetchDefinitions = async () => {
try {
loading.value = true
definitions.value = await api.get('/setup/approvals')
} catch (e: any) {
error.value = e.message
} finally {
loading.value = false
}
}
const createDefinition = async () => {
try {
await api.post('/setup/approvals', {
name: newDefinition.value.name,
triggerType: newDefinition.value.triggerType,
targetObjectType: newDefinition.value.targetObjectType || undefined,
description: newDefinition.value.description || undefined,
entryCriteria: parseJson(newDefinition.value.entryCriteria),
steps: parseJson(newDefinition.value.steps),
votingPolicy: parseJson(newDefinition.value.votingPolicy),
rejectionRule: newDefinition.value.rejectionRule || undefined,
materialChangePolicy: newDefinition.value.materialChangePolicy || undefined,
isActive: newDefinition.value.isActive,
})
showCreateForm.value = false
newDefinition.value = {
name: '',
triggerType: 'action',
targetObjectType: '',
description: '',
entryCriteria: '',
steps: '',
votingPolicy: '',
rejectionRule: 'any',
materialChangePolicy: 'invalidate',
isActive: true,
}
await fetchDefinitions()
} catch (e: any) {
alert('Error creating approval definition: ' + e.message)
}
}
onMounted(() => {
fetchDefinitions()
})
</script>

View File

@@ -16,11 +16,10 @@
<!-- Tabs -->
<div class="mb-8">
<Tabs v-model="activeTab" default-value="fields" class="w-full">
<TabsList class="grid w-full grid-cols-4 max-w-2xl">
<TabsList class="grid w-full grid-cols-3 max-w-2xl">
<TabsTrigger value="fields">Fields</TabsTrigger>
<TabsTrigger value="access">Access</TabsTrigger>
<TabsTrigger value="layouts">Page Layouts</TabsTrigger>
<TabsTrigger value="listLayouts">List View Layouts</TabsTrigger>
</TabsList>
<!-- Fields Tab -->
@@ -149,7 +148,7 @@
</div>
<div class="flex items-center gap-2">
<span
v-if="layout.isDefault || layout.is_default"
v-if="layout.isDefault"
class="px-2 py-1 bg-primary/10 text-primary rounded text-xs"
>
Default
@@ -186,84 +185,6 @@
/>
</div>
</TabsContent>
<!-- List View Layouts Tab -->
<TabsContent value="listLayouts" class="mt-6">
<div v-if="!selectedListLayout" class="space-y-4">
<div class="flex justify-between items-center mb-4">
<h2 class="text-xl font-semibold">List View Layouts</h2>
<Button @click="handleCreateListLayout">
<Plus class="w-4 h-4 mr-2" />
New List Layout
</Button>
</div>
<p class="text-sm text-muted-foreground mb-4">
Configure which fields appear in list views and their order.
</p>
<div v-if="loadingListLayouts" class="text-center py-8">
Loading list layouts...
</div>
<div v-else-if="listLayouts.length === 0" class="text-center py-8 text-muted-foreground">
No list view layouts yet. Create one to customize your list views.
</div>
<div v-else class="space-y-2">
<div
v-for="layout in listLayouts"
:key="layout.id"
class="p-4 border rounded-lg bg-card hover:border-primary cursor-pointer transition-colors"
@click="handleSelectListLayout(layout)"
>
<div class="flex items-center justify-between">
<div>
<h3 class="font-semibold">{{ layout.name }}</h3>
<p v-if="layout.description" class="text-sm text-muted-foreground">
{{ layout.description }}
</p>
<p class="text-xs text-muted-foreground mt-1">
{{ getListLayoutFieldCount(layout) }} fields configured
</p>
</div>
<div class="flex items-center gap-2">
<span
v-if="layout.isDefault || layout.is_default"
class="px-2 py-1 bg-primary/10 text-primary rounded text-xs"
>
Default
</span>
<Button
variant="ghost"
size="sm"
@click.stop="handleDeleteListLayout(layout.id)"
>
<Trash2 class="w-4 h-4" />
</Button>
</div>
</div>
</div>
</div>
</div>
<!-- List Layout Editor -->
<div v-else>
<div class="mb-4">
<Button variant="outline" @click="selectedListLayout = null">
<ArrowLeft class="w-4 h-4 mr-2" />
Back to List Layouts
</Button>
</div>
<ListViewLayoutEditor
:fields="object.fields"
:initial-layout="(selectedListLayout.layoutConfig || selectedListLayout.layout_config)?.fields || []"
:layout-name="selectedListLayout.name"
@save="handleSaveListLayout"
/>
</div>
</TabsContent>
</Tabs>
</div>
</div>
@@ -378,7 +299,6 @@ import { Plus, Trash2, ArrowLeft } from 'lucide-vue-next'
import { Button } from '@/components/ui/button'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import PageLayoutEditor from '@/components/PageLayoutEditor.vue'
import ListViewLayoutEditor from '@/components/ListViewLayoutEditor.vue'
import ObjectAccessSettings from '@/components/ObjectAccessSettings.vue'
import FieldTypeSelector from '@/components/fields/FieldTypeSelector.vue'
import FieldAttributesCommon from '@/components/fields/FieldAttributesCommon.vue'
@@ -395,16 +315,11 @@ const loading = ref(true)
const error = ref<string | null>(null)
const activeTab = ref('fields')
// Page layouts state (detail/edit layouts)
// Page layouts state
const layouts = ref<PageLayout[]>([])
const loadingLayouts = ref(false)
const selectedLayout = ref<PageLayout | null>(null)
// List view layouts state
const listLayouts = ref<PageLayout[]>([])
const loadingListLayouts = ref(false)
const selectedListLayout = ref<PageLayout | null>(null)
// Field management state
const showFieldDialog = ref(false)
const fieldDialogMode = ref<'create' | 'edit'>('create')
@@ -505,8 +420,7 @@ const fetchLayouts = async () => {
try {
loadingLayouts.value = true
// Fetch only detail layouts (default type)
layouts.value = await getPageLayouts(object.value.id, 'detail')
layouts.value = await getPageLayouts(object.value.id)
} catch (e: any) {
console.error('Error fetching layouts:', e)
toast.error('Failed to load page layouts')
@@ -515,20 +429,6 @@ const fetchLayouts = async () => {
}
}
const fetchListLayouts = async () => {
if (!object.value) return
try {
loadingListLayouts.value = true
listLayouts.value = await getPageLayouts(object.value.id, 'list')
} catch (e: any) {
console.error('Error fetching list layouts:', e)
toast.error('Failed to load list view layouts')
} finally {
loadingListLayouts.value = false
}
}
const openFieldDialog = async (mode: 'create' | 'edit', field?: any) => {
fieldDialogMode.value = mode
fieldDialogError.value = null
@@ -784,7 +684,6 @@ const handleCreateLayout = async () => {
const newLayout = await createPageLayout({
name,
objectId: object.value.id,
layoutType: 'detail',
isDefault: layouts.value.length === 0,
layoutConfig: { fields: [], relatedLists: [] },
})
@@ -837,73 +736,6 @@ const handleDeleteLayout = async (layoutId: string) => {
}
}
// List View Layout methods
const handleCreateListLayout = async () => {
const name = prompt('Enter a name for the new list view layout:')
if (!name) return
try {
const newLayout = await createPageLayout({
name,
objectId: object.value.id,
layoutType: 'list',
isDefault: listLayouts.value.length === 0,
layoutConfig: { fields: [] },
})
listLayouts.value.push(newLayout)
selectedListLayout.value = newLayout
toast.success('List view layout created successfully')
} catch (e: any) {
console.error('Error creating list layout:', e)
toast.error('Failed to create list view layout')
}
}
const handleSelectListLayout = (layout: PageLayout) => {
selectedListLayout.value = layout
}
const handleSaveListLayout = async (layoutConfig: { fields: FieldLayoutItem[] }) => {
if (!selectedListLayout.value) return
try {
const updated = await updatePageLayout(selectedListLayout.value.id, {
layoutConfig,
})
// Update the layout in the list
const index = listLayouts.value.findIndex(l => l.id === selectedListLayout.value!.id)
if (index !== -1) {
listLayouts.value[index] = updated
}
selectedListLayout.value = updated
toast.success('List view layout saved successfully')
} catch (e: any) {
console.error('Error saving list layout:', e)
toast.error('Failed to save list view layout')
}
}
const handleDeleteListLayout = async (layoutId: string) => {
if (!confirm('Are you sure you want to delete this list view layout?')) return
try {
await deletePageLayout(layoutId)
listLayouts.value = listLayouts.value.filter(l => l.id !== layoutId)
toast.success('List view layout deleted successfully')
} catch (e: any) {
console.error('Error deleting list layout:', e)
toast.error('Failed to delete list view layout')
}
}
const getListLayoutFieldCount = (layout: PageLayout): number => {
const config = layout.layoutConfig || layout.layout_config
return config?.fields?.length || 0
}
const handleAccessUpdate = (orgWideDefault: string) => {
if (object.value) {
object.value.orgWideDefault = orgWideDefault
@@ -915,9 +747,6 @@ watch(activeTab, (newTab) => {
if (newTab === 'layouts' && layouts.value.length === 0 && !loadingLayouts.value) {
fetchLayouts()
}
if (newTab === 'listLayouts' && listLayouts.value.length === 0 && !loadingListLayouts.value) {
fetchListLayouts()
}
})
onMounted(async () => {
@@ -926,8 +755,5 @@ onMounted(async () => {
if (activeTab.value === 'layouts') {
await fetchLayouts()
}
if (activeTab.value === 'listLayouts') {
await fetchListLayouts()
}
})
</script>

View File

@@ -0,0 +1,186 @@
<template>
<div class="min-h-screen bg-background">
<NuxtLayout name="default">
<main class="container mx-auto px-4 py-8">
<div v-if="loading" class="text-center py-12">Loading...</div>
<div v-else-if="error" class="text-destructive">Error: {{ error }}</div>
<div v-else>
<div class="flex items-center justify-between mb-6">
<h1 class="text-3xl font-bold">Tasks</h1>
<button
@click="showCreateForm = true"
class="px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary/90"
>
New Task
</button>
</div>
<div v-if="showCreateForm" class="mb-6 p-6 border rounded-lg bg-card">
<h2 class="text-xl font-semibold mb-4">Create Task</h2>
<form @submit.prevent="createTask" class="space-y-4">
<div>
<label class="block text-sm font-medium mb-2">Title</label>
<input
v-model="newTask.title"
type="text"
required
class="w-full px-3 py-2 border rounded-md bg-background"
placeholder="Follow up on approval"
/>
</div>
<div>
<label class="block text-sm font-medium mb-2">Description</label>
<textarea
v-model="newTask.description"
class="w-full px-3 py-2 border rounded-md bg-background"
rows="2"
/>
</div>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<label class="block text-sm font-medium mb-2">Assigned To (User ID)</label>
<input
v-model="newTask.assignedToId"
type="text"
class="w-full px-3 py-2 border rounded-md bg-background"
/>
</div>
<div>
<label class="block text-sm font-medium mb-2">Due At</label>
<input
v-model="newTask.dueAt"
type="datetime-local"
class="w-full px-3 py-2 border rounded-md bg-background"
/>
</div>
</div>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<label class="block text-sm font-medium mb-2">Related Object Type</label>
<input
v-model="newTask.relatedObjectType"
type="text"
class="w-full px-3 py-2 border rounded-md bg-background"
placeholder="ApprovalAssignment"
/>
</div>
<div>
<label class="block text-sm font-medium mb-2">Related Object ID</label>
<input
v-model="newTask.relatedObjectId"
type="text"
class="w-full px-3 py-2 border rounded-md bg-background"
/>
</div>
</div>
<div class="flex gap-2">
<button
type="submit"
class="px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary/90"
>
Create
</button>
<button
type="button"
@click="showCreateForm = false"
class="px-4 py-2 bg-secondary text-secondary-foreground rounded-md hover:bg-secondary/90"
>
Cancel
</button>
</div>
</form>
</div>
<div class="grid gap-4">
<div
v-for="task in tasks"
:key="task.id"
class="p-6 border rounded-lg bg-card"
>
<div class="flex items-center justify-between mb-2">
<h3 class="text-lg font-semibold">{{ task.title }}</h3>
<span
class="text-xs px-2 py-1 rounded"
:class="task.status === 'completed' ? 'bg-primary/10 text-primary' : 'bg-muted text-muted-foreground'"
>
{{ task.status }}
</span>
</div>
<p class="text-sm text-muted-foreground mb-2">
{{ task.description || 'No description' }}
</p>
<div class="text-sm text-muted-foreground">
<div>Assigned: {{ task.assignedToId || 'Unassigned' }}</div>
<div>Due: {{ formatDate(task.dueAt) }}</div>
</div>
</div>
</div>
</div>
</main>
</NuxtLayout>
</div>
</template>
<script setup lang="ts">
const { api } = useApi()
const tasks = ref<any[]>([])
const loading = ref(true)
const error = ref<string | null>(null)
const showCreateForm = ref(false)
const newTask = ref({
title: '',
description: '',
assignedToId: '',
dueAt: '',
relatedObjectType: '',
relatedObjectId: '',
})
const formatDate = (value?: string) => {
if (!value) return '—'
const date = new Date(value)
return date.toLocaleString()
}
const fetchTasks = async () => {
try {
loading.value = true
tasks.value = await api.get('/tasks')
} catch (e: any) {
console.log('here');
error.value = e.message
} finally {
loading.value = false
}
}
const createTask = async () => {
try {
await api.post('/tasks', {
title: newTask.value.title,
description: newTask.value.description || undefined,
assignedToId: newTask.value.assignedToId || undefined,
dueAt: newTask.value.dueAt || undefined,
relatedObjectType: newTask.value.relatedObjectType || undefined,
relatedObjectId: newTask.value.relatedObjectId || undefined,
})
showCreateForm.value = false
newTask.value = {
title: '',
description: '',
assignedToId: '',
dueAt: '',
relatedObjectType: '',
relatedObjectId: '',
}
await fetchTasks()
} catch (e: any) {
alert('Error creating task: ' + e.message)
}
}
onMounted(() => {
fetchTasks()
})
</script>

View File

@@ -1,119 +0,0 @@
import { defineEventHandler, getMethod, readBody, getQuery, createError, getHeader } from 'h3'
import { getSubdomainFromRequest } from '~/server/utils/tenant'
import { getSessionToken } from '~/server/utils/session'
/**
* Catch-all API proxy that forwards requests to the NestJS backend
* Injects x-tenant-subdomain header and Authorization from HTTP-only cookie
*/
export default defineEventHandler(async (event) => {
const config = useRuntimeConfig()
const method = getMethod(event)
const path = event.context.params?.path || ''
// Get subdomain and session token
const subdomain = getSubdomainFromRequest(event)
const token = getSessionToken(event)
const backendUrl = config.backendUrl || 'http://localhost:3000'
// Build the full URL with query parameters
const query = getQuery(event)
const queryString = new URLSearchParams(query as Record<string, string>).toString()
const fullUrl = `${backendUrl}/api/${path}${queryString ? `?${queryString}` : ''}`
console.log(`[BFF Proxy] ${method} ${fullUrl} (subdomain: ${subdomain}, hasToken: ${!!token})`)
// Build headers to forward
const headers: Record<string, string> = {
'Content-Type': getHeader(event, 'content-type') || 'application/json',
}
// Add subdomain header for backend tenant resolution
if (subdomain) {
headers['x-tenant-subdomain'] = subdomain
}
// Add auth token from HTTP-only cookie
if (token) {
headers['Authorization'] = `Bearer ${token}`
}
// Forward additional headers that might be needed
const acceptHeader = getHeader(event, 'accept')
if (acceptHeader) {
headers['Accept'] = acceptHeader
}
try {
// Prepare fetch options
const fetchOptions: RequestInit = {
method,
headers,
}
// Add body for methods that support it
if (['POST', 'PUT', 'PATCH'].includes(method)) {
const body = await readBody(event)
if (body) {
fetchOptions.body = JSON.stringify(body)
}
}
// Make request to backend
const response = await fetch(fullUrl, fetchOptions)
// Handle non-JSON responses (like file downloads)
const contentType = response.headers.get('content-type')
if (!response.ok) {
// Try to get error details
let errorMessage = `Backend error: ${response.status}`
let errorData = null
try {
errorData = await response.json()
errorMessage = errorData.message || errorMessage
} catch {
// Response wasn't JSON
try {
const text = await response.text()
console.error(`[BFF Proxy] Backend error (non-JSON): ${text}`)
} catch {}
}
console.error(`[BFF Proxy] Backend returned ${response.status}: ${errorMessage}`, errorData)
throw createError({
statusCode: response.status,
statusMessage: errorMessage,
data: errorData,
})
}
// Return empty response for 204 No Content
if (response.status === 204) {
return null
}
// Handle JSON responses
if (contentType?.includes('application/json')) {
return await response.json()
}
// Handle other content types (text, etc.)
return await response.text()
} catch (error: any) {
// Re-throw H3 errors
if (error.statusCode) {
throw error
}
console.error(`Proxy error for ${method} /api/${path}:`, error)
throw createError({
statusCode: 502,
statusMessage: 'Failed to connect to backend service',
})
}
})

View File

@@ -1,81 +0,0 @@
import { defineEventHandler, readBody, createError } from 'h3'
import { getSubdomainFromRequest, isCentralSubdomain } from '~/server/utils/tenant'
import { setSessionCookie, setTenantIdCookie } from '~/server/utils/session'
export default defineEventHandler(async (event) => {
const config = useRuntimeConfig()
const body = await readBody(event)
// Extract subdomain from the request
const subdomain = getSubdomainFromRequest(event)
if (!subdomain) {
throw createError({
statusCode: 400,
statusMessage: 'Unable to determine tenant from subdomain',
})
}
// Determine the backend URL based on whether this is central admin or tenant
const isCentral = isCentralSubdomain(subdomain)
const backendUrl = config.backendUrl || 'http://localhost:3000'
const loginEndpoint = isCentral ? '/api/auth/central/login' : '/api/auth/login'
try {
// Forward login request to NestJS backend with subdomain header
const response = await fetch(`${backendUrl}${loginEndpoint}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-tenant-subdomain': subdomain,
},
body: JSON.stringify(body),
})
const data = await response.json()
if (!response.ok) {
throw createError({
statusCode: response.status,
statusMessage: data.message || 'Login failed',
data: data,
})
}
// Extract token and tenant info from response
const { access_token, user, tenantId } = data
if (!access_token) {
throw createError({
statusCode: 500,
statusMessage: 'No access token received from backend',
})
}
// Set HTTP-only cookie with the JWT token
setSessionCookie(event, access_token)
// Set tenant ID cookie (readable by client for context)
// Use tenantId from response, or fall back to subdomain
const tenantToStore = tenantId || subdomain
setTenantIdCookie(event, tenantToStore)
// Return user info (but NOT the token - it's in HTTP-only cookie)
return {
success: true,
user,
tenantId: tenantToStore,
}
} catch (error: any) {
// Re-throw H3 errors
if (error.statusCode) {
throw error
}
console.error('Login proxy error:', error)
throw createError({
statusCode: 500,
statusMessage: 'Failed to connect to authentication service',
})
}
})

View File

@@ -1,37 +0,0 @@
import { defineEventHandler, createError } from 'h3'
import { getSubdomainFromRequest } from '~/server/utils/tenant'
import { getSessionToken, clearSessionCookie, clearTenantIdCookie } from '~/server/utils/session'
export default defineEventHandler(async (event) => {
const config = useRuntimeConfig()
const subdomain = getSubdomainFromRequest(event)
const token = getSessionToken(event)
const backendUrl = config.backendUrl || 'http://localhost:3000'
try {
// Call backend logout endpoint if we have a token
if (token) {
await fetch(`${backendUrl}/api/auth/logout`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`,
...(subdomain && { 'x-tenant-subdomain': subdomain }),
},
})
}
} catch (error) {
// Log but don't fail - we still want to clear cookies
console.error('Backend logout error:', error)
}
// Always clear cookies regardless of backend response
clearSessionCookie(event)
clearTenantIdCookie(event)
return {
success: true,
message: 'Logged out successfully',
}
})

View File

@@ -1,60 +0,0 @@
import { defineEventHandler, createError } from 'h3'
import { getSubdomainFromRequest } from '~/server/utils/tenant'
import { getSessionToken } from '~/server/utils/session'
export default defineEventHandler(async (event) => {
const config = useRuntimeConfig()
const subdomain = getSubdomainFromRequest(event)
const token = getSessionToken(event)
if (!token) {
throw createError({
statusCode: 401,
statusMessage: 'Not authenticated',
})
}
const backendUrl = config.backendUrl || 'http://localhost:3000'
try {
// Fetch current user from backend
const response = await fetch(`${backendUrl}/api/auth/me`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`,
...(subdomain && { 'x-tenant-subdomain': subdomain }),
},
})
if (!response.ok) {
if (response.status === 401) {
throw createError({
statusCode: 401,
statusMessage: 'Session expired',
})
}
throw createError({
statusCode: response.status,
statusMessage: 'Failed to fetch user',
})
}
const user = await response.json()
return {
authenticated: true,
user,
}
} catch (error: any) {
if (error.statusCode) {
throw error
}
console.error('Auth check error:', error)
throw createError({
statusCode: 500,
statusMessage: 'Failed to verify authentication',
})
}
})

View File

@@ -1,26 +0,0 @@
import { defineEventHandler, createError } from 'h3'
import { getSubdomainFromRequest } from '~/server/utils/tenant'
import { getSessionToken } from '~/server/utils/session'
/**
* Get a short-lived token for WebSocket authentication
* This is needed because socket.io cannot use HTTP-only cookies directly
*/
export default defineEventHandler(async (event) => {
const subdomain = getSubdomainFromRequest(event)
const token = getSessionToken(event)
if (!token) {
throw createError({
statusCode: 401,
statusMessage: 'Not authenticated',
})
}
// Return the token for WebSocket use
// The token is already validated by being in the HTTP-only cookie
return {
token,
subdomain,
}
})

View File

@@ -1,94 +0,0 @@
import type { H3Event } from 'h3'
import { getCookie, setCookie, deleteCookie, getHeader } from 'h3'
const SESSION_COOKIE_NAME = 'routebox_session'
const SESSION_MAX_AGE = 60 * 60 * 24 * 7 // 7 days
export interface SessionData {
token: string
tenantId: string
userId: string
email: string
}
/**
* Determine if the request is over a secure connection
* Checks both direct HTTPS and proxy headers
*/
function isSecureRequest(event: H3Event): boolean {
// Check x-forwarded-proto header (set by reverse proxies)
const forwardedProto = getHeader(event, 'x-forwarded-proto')
if (forwardedProto === 'https') {
return true
}
// Check if NODE_ENV is production (assume HTTPS in production)
if (process.env.NODE_ENV === 'production') {
return true
}
return false
}
/**
* Get the session token from HTTP-only cookie
*/
export function getSessionToken(event: H3Event): string | null {
return getCookie(event, SESSION_COOKIE_NAME) || null
}
/**
* Set the session token in an HTTP-only cookie
*/
export function setSessionCookie(event: H3Event, token: string): void {
const secure = isSecureRequest(event)
setCookie(event, SESSION_COOKIE_NAME, token, {
httpOnly: true,
secure,
sameSite: 'lax',
maxAge: SESSION_MAX_AGE,
path: '/',
})
}
/**
* Clear the session cookie
*/
export function clearSessionCookie(event: H3Event): void {
deleteCookie(event, SESSION_COOKIE_NAME, {
path: '/',
})
}
/**
* Get tenant ID from a separate cookie (for SSR access)
* This is NOT the auth token - just tenant context
*/
export function getTenantIdFromCookie(event: H3Event): string | null {
return getCookie(event, 'routebox_tenant') || null
}
/**
* Set tenant ID cookie (readable by client for context)
*/
export function setTenantIdCookie(event: H3Event, tenantId: string): void {
const secure = isSecureRequest(event)
setCookie(event, 'routebox_tenant', tenantId, {
httpOnly: false, // Allow client to read tenant context
secure,
sameSite: 'lax',
maxAge: SESSION_MAX_AGE,
path: '/',
})
}
/**
* Clear tenant ID cookie
*/
export function clearTenantIdCookie(event: H3Event): void {
deleteCookie(event, 'routebox_tenant', {
path: '/',
})
}

View File

@@ -1,39 +0,0 @@
import type { H3Event } from 'h3'
import { getHeader } from 'h3'
/**
* Extract subdomain from the request Host header
* Handles production domains (tenant1.routebox.co) and development (tenant1.localhost)
*/
export function getSubdomainFromRequest(event: H3Event): string | null {
const host = getHeader(event, 'host') || ''
const hostname = host.split(':')[0] // Remove port if present
const parts = hostname.split('.')
// For production domains with 3+ parts (e.g., tenant1.routebox.co)
if (parts.length >= 3) {
const subdomain = parts[0]
// Ignore www subdomain
if (subdomain === 'www') {
return null
}
return subdomain
}
// For development (e.g., tenant1.localhost)
if (parts.length === 2 && parts[1] === 'localhost') {
return parts[0]
}
return null
}
/**
* Check if the subdomain is a central/admin subdomain
*/
export function isCentralSubdomain(subdomain: string | null): boolean {
if (!subdomain) return false
const centralSubdomains = (process.env.CENTRAL_SUBDOMAINS || 'central,admin').split(',')
return centralSubdomains.includes(subdomain)
}

View File

@@ -1,15 +1,11 @@
export interface FieldLayoutItem {
fieldId: string;
x?: number;
y?: number;
w?: number;
h?: number;
// For list layouts: field order (optional)
order?: number;
x: number;
y: number;
w: number;
h: number;
}
export type PageLayoutType = 'detail' | 'list';
export interface PageLayoutConfig {
fields: FieldLayoutItem[];
relatedLists?: string[];
@@ -19,23 +15,16 @@ export interface PageLayout {
id: string;
name: string;
objectId: string;
layoutType: PageLayoutType;
isDefault: boolean;
layoutConfig: PageLayoutConfig;
description?: string;
createdAt?: string;
updatedAt?: string;
// Database column names (snake_case) - used when data comes directly from DB
layout_type?: PageLayoutType;
layout_config?: PageLayoutConfig;
object_id?: string;
is_default?: boolean;
}
export interface CreatePageLayoutRequest {
name: string;
objectId: string;
layoutType?: PageLayoutType;
isDefault?: boolean;
layoutConfig: PageLayoutConfig;
description?: string;