RBAC: Phase 1-3, Total Salary fix, employee creation fix, permission groups, backup script
Made-with: Cursor
This commit is contained in:
BIN
assets/capture--admin-1771758081055.png
Normal file
BIN
assets/capture--admin-1771758081055.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 233 KiB |
BIN
assets/capture--dashboard-1771758051783.png
Normal file
BIN
assets/capture--dashboard-1771758051783.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 262 KiB |
BIN
assets/capture--dashboard-1771758179639.png
Normal file
BIN
assets/capture--dashboard-1771758179639.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 328 KiB |
BIN
assets/capture--dashboard-1771759025109.png
Normal file
BIN
assets/capture--dashboard-1771759025109.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 302 KiB |
BIN
assets/capture-latest.png
Normal file
BIN
assets/capture-latest.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 300 KiB |
@@ -9,13 +9,13 @@
|
|||||||
"start": "node dist/server.js",
|
"start": "node dist/server.js",
|
||||||
"prisma:generate": "prisma generate",
|
"prisma:generate": "prisma generate",
|
||||||
"prisma:migrate": "prisma migrate dev",
|
"prisma:migrate": "prisma migrate dev",
|
||||||
"prisma:seed": "ts-node prisma/seed.ts",
|
"prisma:seed": "node prisma/seed.js",
|
||||||
"prisma:studio": "prisma studio",
|
"prisma:studio": "prisma studio",
|
||||||
"db:clean-and-seed": "node prisma/clean-and-seed.js",
|
"db:clean-and-seed": "node prisma/clean-and-seed.js",
|
||||||
"test": "jest"
|
"test": "jest"
|
||||||
},
|
},
|
||||||
"prisma": {
|
"prisma": {
|
||||||
"seed": "ts-node prisma/seed.ts"
|
"seed": "node prisma/seed.js"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@prisma/client": "^5.8.0",
|
"@prisma/client": "^5.8.0",
|
||||||
|
|||||||
@@ -83,7 +83,7 @@ async function main() {
|
|||||||
|
|
||||||
console.log('\n🌱 Running seed...\n');
|
console.log('\n🌱 Running seed...\n');
|
||||||
const backendDir = path.resolve(__dirname, '..');
|
const backendDir = path.resolve(__dirname, '..');
|
||||||
execSync('node prisma/seed-prod.js', {
|
execSync('node prisma/seed.js', {
|
||||||
stdio: 'inherit',
|
stdio: 'inherit',
|
||||||
cwd: backendDir,
|
cwd: backendDir,
|
||||||
env: process.env,
|
env: process.env,
|
||||||
|
|||||||
12
backend/prisma/ensure-gm-permissions.sql
Normal file
12
backend/prisma/ensure-gm-permissions.sql
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
-- Ensure GM has all module permissions
|
||||||
|
-- Run: npx prisma db execute --file prisma/ensure-gm-permissions.sql
|
||||||
|
|
||||||
|
INSERT INTO position_permissions (id, "positionId", module, resource, actions, "createdAt", "updatedAt")
|
||||||
|
SELECT gen_random_uuid(), p.id, m.module, '*', '["*"]', NOW(), NOW()
|
||||||
|
FROM positions p
|
||||||
|
CROSS JOIN (VALUES ('contacts'), ('crm'), ('inventory'), ('projects'), ('hr'), ('marketing'), ('admin')) AS m(module)
|
||||||
|
WHERE p.code = 'GM'
|
||||||
|
AND NOT EXISTS (
|
||||||
|
SELECT 1 FROM position_permissions pp
|
||||||
|
WHERE pp."positionId" = p.id AND pp.module = m.module AND pp.resource = '*'
|
||||||
|
);
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "roles" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"name" TEXT NOT NULL,
|
||||||
|
"nameAr" TEXT,
|
||||||
|
"description" TEXT,
|
||||||
|
"isActive" BOOLEAN NOT NULL DEFAULT true,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "roles_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "role_permissions" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"roleId" TEXT NOT NULL,
|
||||||
|
"module" TEXT NOT NULL,
|
||||||
|
"resource" TEXT NOT NULL,
|
||||||
|
"actions" JSONB NOT NULL,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "role_permissions_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "user_roles" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"userId" TEXT NOT NULL,
|
||||||
|
"roleId" TEXT NOT NULL,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "user_roles_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "roles_name_key" ON "roles"("name");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "role_permissions_roleId_module_resource_key" ON "role_permissions"("roleId", "module", "resource");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "user_roles_userId_idx" ON "user_roles"("userId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "user_roles_roleId_idx" ON "user_roles"("roleId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "user_roles_userId_roleId_key" ON "user_roles"("userId", "roleId");
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "role_permissions" ADD CONSTRAINT "role_permissions_roleId_fkey" FOREIGN KEY ("roleId") REFERENCES "roles"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "user_roles" ADD CONSTRAINT "user_roles_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "user_roles" ADD CONSTRAINT "user_roles_roleId_fkey" FOREIGN KEY ("roleId") REFERENCES "roles"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
@@ -69,10 +69,59 @@ model User {
|
|||||||
assignedTasks Task[]
|
assignedTasks Task[]
|
||||||
projectMembers ProjectMember[]
|
projectMembers ProjectMember[]
|
||||||
campaigns Campaign[]
|
campaigns Campaign[]
|
||||||
|
userRoles UserRole[]
|
||||||
|
|
||||||
@@map("users")
|
@@map("users")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Optional roles - user can belong to multiple permission groups (Phase 3 multi-group)
|
||||||
|
model Role {
|
||||||
|
id String @id @default(uuid())
|
||||||
|
name String @unique
|
||||||
|
nameAr String?
|
||||||
|
description String?
|
||||||
|
isActive Boolean @default(true)
|
||||||
|
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
updatedAt DateTime @updatedAt
|
||||||
|
|
||||||
|
permissions RolePermission[]
|
||||||
|
userRoles UserRole[]
|
||||||
|
|
||||||
|
@@map("roles")
|
||||||
|
}
|
||||||
|
|
||||||
|
model RolePermission {
|
||||||
|
id String @id @default(uuid())
|
||||||
|
roleId String
|
||||||
|
role Role @relation(fields: [roleId], references: [id], onDelete: Cascade)
|
||||||
|
module String
|
||||||
|
resource String
|
||||||
|
actions Json // ["read", "create", "update", "delete", ...]
|
||||||
|
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
updatedAt DateTime @updatedAt
|
||||||
|
|
||||||
|
@@unique([roleId, module, resource])
|
||||||
|
@@map("role_permissions")
|
||||||
|
}
|
||||||
|
|
||||||
|
model UserRole {
|
||||||
|
id String @id @default(uuid())
|
||||||
|
userId String
|
||||||
|
roleId String
|
||||||
|
|
||||||
|
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||||
|
role Role @relation(fields: [roleId], references: [id], onDelete: Cascade)
|
||||||
|
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
|
||||||
|
@@unique([userId, roleId])
|
||||||
|
@@index([userId])
|
||||||
|
@@index([roleId])
|
||||||
|
@@map("user_roles")
|
||||||
|
}
|
||||||
|
|
||||||
model Employee {
|
model Employee {
|
||||||
id String @id @default(uuid())
|
id String @id @default(uuid())
|
||||||
uniqueEmployeeId String @unique // رقم الموظف الموحد
|
uniqueEmployeeId String @unique // رقم الموظف الموحد
|
||||||
|
|||||||
146
backend/prisma/seed.js
Normal file
146
backend/prisma/seed.js
Normal file
@@ -0,0 +1,146 @@
|
|||||||
|
/**
|
||||||
|
* Minimal seed - System Administrator only.
|
||||||
|
* Run with: node prisma/seed.js
|
||||||
|
*/
|
||||||
|
const { PrismaClient } = require('@prisma/client');
|
||||||
|
const bcrypt = require('bcryptjs');
|
||||||
|
|
||||||
|
const prisma = new PrismaClient();
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
console.log('🌱 Starting database seeding (minimal - System Administrator only)...');
|
||||||
|
|
||||||
|
const adminDept = await prisma.department.create({
|
||||||
|
data: {
|
||||||
|
name: 'Administration',
|
||||||
|
nameAr: 'الإدارة',
|
||||||
|
code: 'ADMIN',
|
||||||
|
description: 'System administration and configuration',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const sysAdminPosition = await prisma.position.create({
|
||||||
|
data: {
|
||||||
|
title: 'System Administrator',
|
||||||
|
titleAr: 'مدير النظام',
|
||||||
|
code: 'SYS_ADMIN',
|
||||||
|
departmentId: adminDept.id,
|
||||||
|
level: 1,
|
||||||
|
description: 'Full system access - configure and manage all modules',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const modules = ['contacts', 'crm', 'inventory', 'projects', 'hr', 'marketing', 'admin'];
|
||||||
|
for (const module of modules) {
|
||||||
|
await prisma.positionPermission.create({
|
||||||
|
data: {
|
||||||
|
positionId: sysAdminPosition.id,
|
||||||
|
module,
|
||||||
|
resource: '*',
|
||||||
|
actions: ['*'],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create Sales Department and restricted positions
|
||||||
|
const salesDept = await prisma.department.create({
|
||||||
|
data: {
|
||||||
|
name: 'Sales',
|
||||||
|
nameAr: 'المبيعات',
|
||||||
|
code: 'SALES',
|
||||||
|
description: 'Sales and business development',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const salesRepPosition = await prisma.position.create({
|
||||||
|
data: {
|
||||||
|
title: 'Sales Representative',
|
||||||
|
titleAr: 'مندوب مبيعات',
|
||||||
|
code: 'SALES_REP',
|
||||||
|
departmentId: salesDept.id,
|
||||||
|
level: 3,
|
||||||
|
description: 'Limited access - Contacts and CRM deals',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await prisma.positionPermission.createMany({
|
||||||
|
data: [
|
||||||
|
{ positionId: salesRepPosition.id, module: 'contacts', resource: '*', actions: ['read', 'create', 'update'] },
|
||||||
|
{ positionId: salesRepPosition.id, module: 'crm', resource: 'deals', actions: ['read', 'create', 'update'] },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
const accountantPosition = await prisma.position.create({
|
||||||
|
data: {
|
||||||
|
title: 'Accountant',
|
||||||
|
titleAr: 'محاسب',
|
||||||
|
code: 'ACCOUNTANT',
|
||||||
|
departmentId: adminDept.id,
|
||||||
|
level: 2,
|
||||||
|
description: 'HR read, inventory read, contacts read',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await prisma.positionPermission.createMany({
|
||||||
|
data: [
|
||||||
|
{ positionId: accountantPosition.id, module: 'contacts', resource: '*', actions: ['read'] },
|
||||||
|
{ positionId: accountantPosition.id, module: 'crm', resource: '*', actions: ['read'] },
|
||||||
|
{ positionId: accountantPosition.id, module: 'inventory', resource: '*', actions: ['read'] },
|
||||||
|
{ positionId: accountantPosition.id, module: 'hr', resource: '*', actions: ['read'] },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log('✅ Created position and permissions');
|
||||||
|
|
||||||
|
const sysAdminEmployee = await prisma.employee.create({
|
||||||
|
data: {
|
||||||
|
uniqueEmployeeId: 'SYS-001',
|
||||||
|
firstName: 'System',
|
||||||
|
lastName: 'Administrator',
|
||||||
|
firstNameAr: 'مدير',
|
||||||
|
lastNameAr: 'النظام',
|
||||||
|
email: 'admin@system.local',
|
||||||
|
mobile: '+966500000000',
|
||||||
|
dateOfBirth: new Date('1990-01-01'),
|
||||||
|
gender: 'MALE',
|
||||||
|
nationality: 'Saudi',
|
||||||
|
employmentType: 'Full-time',
|
||||||
|
contractType: 'Unlimited',
|
||||||
|
hireDate: new Date(),
|
||||||
|
departmentId: adminDept.id,
|
||||||
|
positionId: sysAdminPosition.id,
|
||||||
|
basicSalary: 0,
|
||||||
|
status: 'ACTIVE',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const hashedPassword = await bcrypt.hash('Admin@123', 10);
|
||||||
|
await prisma.user.create({
|
||||||
|
data: {
|
||||||
|
email: 'admin@system.local',
|
||||||
|
username: 'admin',
|
||||||
|
password: hashedPassword,
|
||||||
|
employeeId: sysAdminEmployee.id,
|
||||||
|
isActive: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log('✅ Created System Administrator');
|
||||||
|
console.log('\n🎉 Database seeding completed!\n');
|
||||||
|
console.log('📋 System Administrator:');
|
||||||
|
console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
|
||||||
|
console.log(' Email: admin@system.local');
|
||||||
|
console.log(' Username: admin');
|
||||||
|
console.log(' Password: Admin@123');
|
||||||
|
console.log(' Access: Full system access (all modules)');
|
||||||
|
console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
main()
|
||||||
|
.catch((e) => {
|
||||||
|
console.error('❌ Error seeding database:', e);
|
||||||
|
process.exit(1);
|
||||||
|
})
|
||||||
|
.finally(async () => {
|
||||||
|
await prisma.$disconnect();
|
||||||
|
});
|
||||||
@@ -4,58 +4,50 @@ import bcrypt from 'bcryptjs';
|
|||||||
const prisma = new PrismaClient();
|
const prisma = new PrismaClient();
|
||||||
|
|
||||||
async function main() {
|
async function main() {
|
||||||
console.log('🌱 Starting database seeding...');
|
console.log('🌱 Starting database seeding (minimal - System Administrator only)...');
|
||||||
|
|
||||||
// Create Departments
|
// Create Administration Department
|
||||||
|
const adminDept = await prisma.department.create({
|
||||||
|
data: {
|
||||||
|
name: 'Administration',
|
||||||
|
nameAr: 'الإدارة',
|
||||||
|
code: 'ADMIN',
|
||||||
|
description: 'System administration and configuration',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// Create System Administrator Position
|
||||||
|
const sysAdminPosition = await prisma.position.create({
|
||||||
|
data: {
|
||||||
|
title: 'System Administrator',
|
||||||
|
titleAr: 'مدير النظام',
|
||||||
|
code: 'SYS_ADMIN',
|
||||||
|
departmentId: adminDept.id,
|
||||||
|
level: 1,
|
||||||
|
description: 'Full system access - configure and manage all modules',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// Create full permissions for all modules
|
||||||
|
const modules = ['contacts', 'crm', 'inventory', 'projects', 'hr', 'marketing', 'admin'];
|
||||||
|
for (const module of modules) {
|
||||||
|
await prisma.positionPermission.create({
|
||||||
|
data: {
|
||||||
|
positionId: sysAdminPosition.id,
|
||||||
|
module,
|
||||||
|
resource: '*',
|
||||||
|
actions: ['*'],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create Sales Department and restricted positions
|
||||||
const salesDept = await prisma.department.create({
|
const salesDept = await prisma.department.create({
|
||||||
data: {
|
data: {
|
||||||
name: 'Sales Department',
|
name: 'Sales',
|
||||||
nameAr: 'قسم المبيعات',
|
nameAr: 'المبيعات',
|
||||||
code: 'SALES',
|
code: 'SALES',
|
||||||
description: 'Sales and Business Development',
|
description: 'Sales and business development',
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const itDept = await prisma.department.create({
|
|
||||||
data: {
|
|
||||||
name: 'IT Department',
|
|
||||||
nameAr: 'قسم تقنية المعلومات',
|
|
||||||
code: 'IT',
|
|
||||||
description: 'Information Technology',
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const hrDept = await prisma.department.create({
|
|
||||||
data: {
|
|
||||||
name: 'HR Department',
|
|
||||||
nameAr: 'قسم الموارد البشرية',
|
|
||||||
code: 'HR',
|
|
||||||
description: 'Human Resources',
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
console.log('✅ Created departments');
|
|
||||||
|
|
||||||
// Create Positions
|
|
||||||
const gmPosition = await prisma.position.create({
|
|
||||||
data: {
|
|
||||||
title: 'General Manager',
|
|
||||||
titleAr: 'المدير العام',
|
|
||||||
code: 'GM',
|
|
||||||
departmentId: salesDept.id,
|
|
||||||
level: 1,
|
|
||||||
description: 'Chief Executive - Full Access',
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const salesManagerPosition = await prisma.position.create({
|
|
||||||
data: {
|
|
||||||
title: 'Sales Manager',
|
|
||||||
titleAr: 'مدير المبيعات',
|
|
||||||
code: 'SALES_MGR',
|
|
||||||
departmentId: salesDept.id,
|
|
||||||
level: 2,
|
|
||||||
description: 'Sales Department Manager',
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -66,286 +58,83 @@ async function main() {
|
|||||||
code: 'SALES_REP',
|
code: 'SALES_REP',
|
||||||
departmentId: salesDept.id,
|
departmentId: salesDept.id,
|
||||||
level: 3,
|
level: 3,
|
||||||
description: 'Sales Representative',
|
description: 'Limited access - Contacts and CRM deals',
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
console.log('✅ Created positions');
|
await prisma.positionPermission.createMany({
|
||||||
|
data: [
|
||||||
|
{ positionId: salesRepPosition.id, module: 'contacts', resource: '*', actions: ['read', 'create', 'update'] },
|
||||||
|
{ positionId: salesRepPosition.id, module: 'crm', resource: 'deals', actions: ['read', 'create', 'update'] },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
// Create Permissions for GM (Full Access)
|
const accountantPosition = await prisma.position.create({
|
||||||
const modules = ['contacts', 'crm', 'inventory', 'projects', 'hr', 'marketing'];
|
|
||||||
const resources = ['*'];
|
|
||||||
const actions = ['*'];
|
|
||||||
|
|
||||||
for (const module of modules) {
|
|
||||||
await prisma.positionPermission.create({
|
|
||||||
data: {
|
|
||||||
positionId: gmPosition.id,
|
|
||||||
module,
|
|
||||||
resource: resources[0],
|
|
||||||
actions,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// Admin permission for GM
|
|
||||||
await prisma.positionPermission.create({
|
|
||||||
data: {
|
data: {
|
||||||
positionId: gmPosition.id,
|
title: 'Accountant',
|
||||||
module: 'admin',
|
titleAr: 'محاسب',
|
||||||
resource: '*',
|
code: 'ACCOUNTANT',
|
||||||
actions: ['*'],
|
departmentId: adminDept.id,
|
||||||
|
level: 2,
|
||||||
|
description: 'HR read, inventory read, contacts read',
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
// Create Permissions for Sales Manager
|
|
||||||
await prisma.positionPermission.createMany({
|
await prisma.positionPermission.createMany({
|
||||||
data: [
|
data: [
|
||||||
{
|
{ positionId: accountantPosition.id, module: 'contacts', resource: '*', actions: ['read'] },
|
||||||
positionId: salesManagerPosition.id,
|
{ positionId: accountantPosition.id, module: 'crm', resource: '*', actions: ['read'] },
|
||||||
module: 'contacts',
|
{ positionId: accountantPosition.id, module: 'inventory', resource: '*', actions: ['read'] },
|
||||||
resource: 'contacts',
|
{ positionId: accountantPosition.id, module: 'hr', resource: '*', actions: ['read'] },
|
||||||
actions: ['create', 'read', 'update', 'merge'],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
positionId: salesManagerPosition.id,
|
|
||||||
module: 'crm',
|
|
||||||
resource: 'deals',
|
|
||||||
actions: ['create', 'read', 'update', 'approve'],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
positionId: salesManagerPosition.id,
|
|
||||||
module: 'crm',
|
|
||||||
resource: 'quotes',
|
|
||||||
actions: ['create', 'read', 'update', 'approve'],
|
|
||||||
},
|
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
|
|
||||||
// Create Permissions for Sales Rep
|
console.log('✅ Created position and permissions');
|
||||||
await prisma.positionPermission.createMany({
|
|
||||||
data: [
|
|
||||||
{
|
|
||||||
positionId: salesRepPosition.id,
|
|
||||||
module: 'contacts',
|
|
||||||
resource: 'contacts',
|
|
||||||
actions: ['create', 'read', 'update'],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
positionId: salesRepPosition.id,
|
|
||||||
module: 'crm',
|
|
||||||
resource: 'deals',
|
|
||||||
actions: ['create', 'read', 'update'],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
positionId: salesRepPosition.id,
|
|
||||||
module: 'crm',
|
|
||||||
resource: 'quotes',
|
|
||||||
actions: ['create', 'read'],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
});
|
|
||||||
|
|
||||||
console.log('✅ Created permissions');
|
// Create minimal Employee for System Administrator
|
||||||
|
const sysAdminEmployee = await prisma.employee.create({
|
||||||
// Create Employees
|
|
||||||
const gmEmployee = await prisma.employee.create({
|
|
||||||
data: {
|
data: {
|
||||||
uniqueEmployeeId: 'EMP-2024-0001',
|
uniqueEmployeeId: 'SYS-001',
|
||||||
firstName: 'Ahmed',
|
firstName: 'System',
|
||||||
lastName: 'Al-Mutairi',
|
lastName: 'Administrator',
|
||||||
firstNameAr: 'أحمد',
|
firstNameAr: 'مدير',
|
||||||
lastNameAr: 'المطيري',
|
lastNameAr: 'النظام',
|
||||||
email: 'gm@atmata.com',
|
email: 'admin@system.local',
|
||||||
mobile: '+966500000001',
|
mobile: '+966500000000',
|
||||||
dateOfBirth: new Date('1980-01-01'),
|
dateOfBirth: new Date('1990-01-01'),
|
||||||
gender: 'MALE',
|
gender: 'MALE',
|
||||||
nationality: 'Saudi',
|
nationality: 'Saudi',
|
||||||
employmentType: 'Full-time',
|
employmentType: 'Full-time',
|
||||||
contractType: 'Unlimited',
|
contractType: 'Unlimited',
|
||||||
hireDate: new Date('2020-01-01'),
|
hireDate: new Date(),
|
||||||
departmentId: salesDept.id,
|
departmentId: adminDept.id,
|
||||||
positionId: gmPosition.id,
|
positionId: sysAdminPosition.id,
|
||||||
basicSalary: 50000,
|
basicSalary: 0,
|
||||||
status: 'ACTIVE',
|
status: 'ACTIVE',
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const salesManagerEmployee = await prisma.employee.create({
|
// Create System Administrator User
|
||||||
data: {
|
|
||||||
uniqueEmployeeId: 'EMP-2024-0002',
|
|
||||||
firstName: 'Fatima',
|
|
||||||
lastName: 'Al-Zahrani',
|
|
||||||
firstNameAr: 'فاطمة',
|
|
||||||
lastNameAr: 'الزهراني',
|
|
||||||
email: 'sales.manager@atmata.com',
|
|
||||||
mobile: '+966500000002',
|
|
||||||
dateOfBirth: new Date('1985-05-15'),
|
|
||||||
gender: 'FEMALE',
|
|
||||||
nationality: 'Saudi',
|
|
||||||
employmentType: 'Full-time',
|
|
||||||
contractType: 'Unlimited',
|
|
||||||
hireDate: new Date('2021-06-01'),
|
|
||||||
departmentId: salesDept.id,
|
|
||||||
positionId: salesManagerPosition.id,
|
|
||||||
reportingToId: gmEmployee.id,
|
|
||||||
basicSalary: 25000,
|
|
||||||
status: 'ACTIVE',
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const salesRepEmployee = await prisma.employee.create({
|
|
||||||
data: {
|
|
||||||
uniqueEmployeeId: 'EMP-2024-0003',
|
|
||||||
firstName: 'Mohammed',
|
|
||||||
lastName: 'Al-Qahtani',
|
|
||||||
firstNameAr: 'محمد',
|
|
||||||
lastNameAr: 'القحطاني',
|
|
||||||
email: 'sales.rep@atmata.com',
|
|
||||||
mobile: '+966500000003',
|
|
||||||
dateOfBirth: new Date('1992-08-20'),
|
|
||||||
gender: 'MALE',
|
|
||||||
nationality: 'Saudi',
|
|
||||||
employmentType: 'Full-time',
|
|
||||||
contractType: 'Fixed',
|
|
||||||
hireDate: new Date('2023-01-15'),
|
|
||||||
departmentId: salesDept.id,
|
|
||||||
positionId: salesRepPosition.id,
|
|
||||||
reportingToId: salesManagerEmployee.id,
|
|
||||||
basicSalary: 12000,
|
|
||||||
status: 'ACTIVE',
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
console.log('✅ Created employees');
|
|
||||||
|
|
||||||
// Create Users
|
|
||||||
const hashedPassword = await bcrypt.hash('Admin@123', 10);
|
const hashedPassword = await bcrypt.hash('Admin@123', 10);
|
||||||
|
await prisma.user.create({
|
||||||
const gmUser = await prisma.user.create({
|
|
||||||
data: {
|
data: {
|
||||||
email: 'gm@atmata.com',
|
email: 'admin@system.local',
|
||||||
username: 'admin',
|
username: 'admin',
|
||||||
password: hashedPassword,
|
password: hashedPassword,
|
||||||
employeeId: gmEmployee.id,
|
employeeId: sysAdminEmployee.id,
|
||||||
isActive: true,
|
isActive: true,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const salesManagerUser = await prisma.user.create({
|
console.log('✅ Created System Administrator');
|
||||||
data: {
|
|
||||||
email: 'sales.manager@atmata.com',
|
|
||||||
username: 'salesmanager',
|
|
||||||
password: hashedPassword,
|
|
||||||
employeeId: salesManagerEmployee.id,
|
|
||||||
isActive: true,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const salesRepUser = await prisma.user.create({
|
console.log('\n🎉 Database seeding completed!\n');
|
||||||
data: {
|
console.log('📋 System Administrator:');
|
||||||
email: 'sales.rep@atmata.com',
|
|
||||||
username: 'salesrep',
|
|
||||||
password: hashedPassword,
|
|
||||||
employeeId: salesRepEmployee.id,
|
|
||||||
isActive: true,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
console.log('✅ Created users');
|
|
||||||
|
|
||||||
// Create Contact Categories
|
|
||||||
await prisma.contactCategory.createMany({
|
|
||||||
data: [
|
|
||||||
{ name: 'Customer', nameAr: 'عميل', description: 'Paying customers' },
|
|
||||||
{ name: 'Supplier', nameAr: 'مورد', description: 'Product/Service suppliers' },
|
|
||||||
{ name: 'Partner', nameAr: 'شريك', description: 'Business partners' },
|
|
||||||
{ name: 'Lead', nameAr: 'عميل محتمل', description: 'Potential customers' },
|
|
||||||
{ name: 'Company Employee', nameAr: 'موظف الشركة', description: 'Internal company staff' },
|
|
||||||
],
|
|
||||||
});
|
|
||||||
|
|
||||||
console.log('✅ Created contact categories');
|
|
||||||
|
|
||||||
// Create Product Categories
|
|
||||||
await prisma.productCategory.createMany({
|
|
||||||
data: [
|
|
||||||
{ name: 'Electronics', nameAr: 'إلكترونيات', code: 'ELEC' },
|
|
||||||
{ name: 'Software', nameAr: 'برمجيات', code: 'SOFT' },
|
|
||||||
{ name: 'Services', nameAr: 'خدمات', code: 'SERV' },
|
|
||||||
],
|
|
||||||
});
|
|
||||||
|
|
||||||
console.log('✅ Created product categories');
|
|
||||||
|
|
||||||
// Create Pipelines
|
|
||||||
await prisma.pipeline.create({
|
|
||||||
data: {
|
|
||||||
name: 'B2B Sales Pipeline',
|
|
||||||
nameAr: 'مسار مبيعات الشركات',
|
|
||||||
structure: 'B2B',
|
|
||||||
stages: [
|
|
||||||
{ name: 'OPEN', nameAr: 'مفتوحة', order: 1 },
|
|
||||||
{ name: 'QUALIFIED', nameAr: 'مؤهلة', order: 2 },
|
|
||||||
{ name: 'NEGOTIATION', nameAr: 'تفاوض', order: 3 },
|
|
||||||
{ name: 'PROPOSAL', nameAr: 'عرض سعر', order: 4 },
|
|
||||||
{ name: 'WON', nameAr: 'فازت', order: 5 },
|
|
||||||
{ name: 'LOST', nameAr: 'خسرت', order: 6 },
|
|
||||||
],
|
|
||||||
isActive: true,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
await prisma.pipeline.create({
|
|
||||||
data: {
|
|
||||||
name: 'B2C Sales Pipeline',
|
|
||||||
nameAr: 'مسار مبيعات الأفراد',
|
|
||||||
structure: 'B2C',
|
|
||||||
stages: [
|
|
||||||
{ name: 'LEAD', nameAr: 'عميل محتمل', order: 1 },
|
|
||||||
{ name: 'CONTACTED', nameAr: 'تم التواصل', order: 2 },
|
|
||||||
{ name: 'QUALIFIED', nameAr: 'مؤهل', order: 3 },
|
|
||||||
{ name: 'WON', nameAr: 'بيع', order: 4 },
|
|
||||||
{ name: 'LOST', nameAr: 'خسارة', order: 5 },
|
|
||||||
],
|
|
||||||
isActive: true,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
console.log('✅ Created pipelines');
|
|
||||||
|
|
||||||
// Create sample warehouse
|
|
||||||
await prisma.warehouse.create({
|
|
||||||
data: {
|
|
||||||
code: 'WH-MAIN',
|
|
||||||
name: 'Main Warehouse',
|
|
||||||
nameAr: 'المستودع الرئيسي',
|
|
||||||
type: 'MAIN',
|
|
||||||
city: 'Riyadh',
|
|
||||||
country: 'Saudi Arabia',
|
|
||||||
isActive: true,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
console.log('✅ Created warehouse');
|
|
||||||
|
|
||||||
console.log('\n🎉 Database seeding completed successfully!\n');
|
|
||||||
console.log('📋 Default Users Created:');
|
|
||||||
console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
|
console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
|
||||||
console.log('1. General Manager');
|
console.log(' Email: admin@system.local');
|
||||||
console.log(' Email: gm@atmata.com');
|
console.log(' Username: admin');
|
||||||
console.log(' Password: Admin@123');
|
console.log(' Password: Admin@123');
|
||||||
console.log(' Access: Full System Access');
|
console.log(' Access: Full system access (all modules)');
|
||||||
console.log('');
|
|
||||||
console.log('2. Sales Manager');
|
|
||||||
console.log(' Email: sales.manager@atmata.com');
|
|
||||||
console.log(' Password: Admin@123');
|
|
||||||
console.log(' Access: Contacts, CRM with approvals');
|
|
||||||
console.log('');
|
|
||||||
console.log('3. Sales Representative');
|
|
||||||
console.log(' Email: sales.rep@atmata.com');
|
|
||||||
console.log(' Password: Admin@123');
|
|
||||||
console.log(' Access: Basic Contacts and CRM');
|
|
||||||
console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
|
console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -357,4 +146,3 @@ main()
|
|||||||
.finally(async () => {
|
.finally(async () => {
|
||||||
await prisma.$disconnect();
|
await prisma.$disconnect();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
51
backend/scripts/ensure-gm-permissions.ts
Normal file
51
backend/scripts/ensure-gm-permissions.ts
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
/**
|
||||||
|
* Ensure GM position has all module permissions.
|
||||||
|
* Adds any missing permissions for: contacts, crm, inventory, projects, hr, marketing, admin
|
||||||
|
*/
|
||||||
|
import { PrismaClient } from '@prisma/client';
|
||||||
|
|
||||||
|
const prisma = new PrismaClient();
|
||||||
|
|
||||||
|
const GM_MODULES = ['contacts', 'crm', 'inventory', 'projects', 'hr', 'marketing', 'admin'];
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
const gmPosition = await prisma.position.findFirst({ where: { code: 'GM' } });
|
||||||
|
if (!gmPosition) {
|
||||||
|
console.log('GM position not found.');
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const existing = await prisma.positionPermission.findMany({
|
||||||
|
where: { positionId: gmPosition.id },
|
||||||
|
select: { module: true },
|
||||||
|
});
|
||||||
|
const existingModules = new Set(existing.map((p) => p.module));
|
||||||
|
|
||||||
|
let added = 0;
|
||||||
|
for (const module of GM_MODULES) {
|
||||||
|
if (existingModules.has(module)) continue;
|
||||||
|
await prisma.positionPermission.create({
|
||||||
|
data: {
|
||||||
|
positionId: gmPosition.id,
|
||||||
|
module,
|
||||||
|
resource: '*',
|
||||||
|
actions: ['*'],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
console.log(`Added permission: ${module}`);
|
||||||
|
added++;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (added === 0) {
|
||||||
|
console.log('All GM permissions already exist.');
|
||||||
|
} else {
|
||||||
|
console.log(`Added ${added} permission(s).`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
main()
|
||||||
|
.catch((e) => {
|
||||||
|
console.error(e);
|
||||||
|
process.exit(1);
|
||||||
|
})
|
||||||
|
.finally(() => prisma.$disconnect());
|
||||||
@@ -53,4 +53,4 @@ npm run db:clean-and-seed
|
|||||||
|
|
||||||
echo ""
|
echo ""
|
||||||
echo "✅ Done. Restart the application so it uses the cleaned database."
|
echo "✅ Done. Restart the application so it uses the cleaned database."
|
||||||
echo " Default logins: gm@atmata.com / sales.manager@atmata.com / sales.rep@atmata.com (Password: Admin@123)"
|
echo " System Administrator: admin@system.local (Password: Admin@123)"
|
||||||
|
|||||||
@@ -134,6 +134,40 @@ class AdminController {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async createPosition(req: AuthRequest, res: Response, next: NextFunction) {
|
||||||
|
try {
|
||||||
|
const position = await adminService.createPosition({
|
||||||
|
title: req.body.title,
|
||||||
|
titleAr: req.body.titleAr,
|
||||||
|
code: req.body.code,
|
||||||
|
departmentId: req.body.departmentId,
|
||||||
|
level: req.body.level,
|
||||||
|
description: req.body.description,
|
||||||
|
isActive: req.body.isActive,
|
||||||
|
});
|
||||||
|
res.status(201).json(ResponseFormatter.success(position));
|
||||||
|
} catch (error) {
|
||||||
|
next(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async updatePosition(req: AuthRequest, res: Response, next: NextFunction) {
|
||||||
|
try {
|
||||||
|
const position = await adminService.updatePosition(req.params.id, {
|
||||||
|
title: req.body.title,
|
||||||
|
titleAr: req.body.titleAr,
|
||||||
|
code: req.body.code,
|
||||||
|
departmentId: req.body.departmentId,
|
||||||
|
level: req.body.level,
|
||||||
|
description: req.body.description,
|
||||||
|
isActive: req.body.isActive,
|
||||||
|
});
|
||||||
|
res.json(ResponseFormatter.success(position));
|
||||||
|
} catch (error) {
|
||||||
|
next(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async updatePositionPermissions(req: AuthRequest, res: Response, next: NextFunction) {
|
async updatePositionPermissions(req: AuthRequest, res: Response, next: NextFunction) {
|
||||||
try {
|
try {
|
||||||
const position = await adminService.updatePositionPermissions(
|
const position = await adminService.updatePositionPermissions(
|
||||||
@@ -145,6 +179,74 @@ class AdminController {
|
|||||||
next(error);
|
next(error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ========== PERMISSION GROUPS (Phase 3) ==========
|
||||||
|
|
||||||
|
async getPermissionGroups(req: AuthRequest, res: Response, next: NextFunction) {
|
||||||
|
try {
|
||||||
|
const groups = await adminService.getPermissionGroups();
|
||||||
|
res.json(ResponseFormatter.success(groups));
|
||||||
|
} catch (error) {
|
||||||
|
next(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async createPermissionGroup(req: AuthRequest, res: Response, next: NextFunction) {
|
||||||
|
try {
|
||||||
|
const group = await adminService.createPermissionGroup(req.body);
|
||||||
|
res.status(201).json(ResponseFormatter.success(group));
|
||||||
|
} catch (error) {
|
||||||
|
next(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async updatePermissionGroup(req: AuthRequest, res: Response, next: NextFunction) {
|
||||||
|
try {
|
||||||
|
const group = await adminService.updatePermissionGroup(req.params.id, req.body);
|
||||||
|
res.json(ResponseFormatter.success(group));
|
||||||
|
} catch (error) {
|
||||||
|
next(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async updatePermissionGroupPermissions(req: AuthRequest, res: Response, next: NextFunction) {
|
||||||
|
try {
|
||||||
|
const group = await adminService.updatePermissionGroupPermissions(
|
||||||
|
req.params.id,
|
||||||
|
req.body.permissions
|
||||||
|
);
|
||||||
|
res.json(ResponseFormatter.success(group));
|
||||||
|
} catch (error) {
|
||||||
|
next(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async getUserRoles(req: AuthRequest, res: Response, next: NextFunction) {
|
||||||
|
try {
|
||||||
|
const roles = await adminService.getUserRoles(req.params.userId);
|
||||||
|
res.json(ResponseFormatter.success(roles));
|
||||||
|
} catch (error) {
|
||||||
|
next(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async assignUserRole(req: AuthRequest, res: Response, next: NextFunction) {
|
||||||
|
try {
|
||||||
|
const userRole = await adminService.assignUserRole(req.params.userId, req.body.roleId);
|
||||||
|
res.status(201).json(ResponseFormatter.success(userRole));
|
||||||
|
} catch (error) {
|
||||||
|
next(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async removeUserRole(req: AuthRequest, res: Response, next: NextFunction) {
|
||||||
|
try {
|
||||||
|
await adminService.removeUserRole(req.params.userId, req.params.roleId);
|
||||||
|
res.json(ResponseFormatter.success({ success: true }));
|
||||||
|
} catch (error) {
|
||||||
|
next(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const adminController = new AdminController();
|
export const adminController = new AdminController();
|
||||||
|
|||||||
@@ -89,6 +89,33 @@ router.get(
|
|||||||
adminController.getPositions
|
adminController.getPositions
|
||||||
);
|
);
|
||||||
|
|
||||||
|
router.post(
|
||||||
|
'/positions',
|
||||||
|
authorize('admin', 'roles', 'create'),
|
||||||
|
[
|
||||||
|
body('title').notEmpty().trim(),
|
||||||
|
body('code').notEmpty().trim(),
|
||||||
|
body('departmentId').isUUID(),
|
||||||
|
body('level').optional().isInt({ min: 1 }),
|
||||||
|
],
|
||||||
|
validate,
|
||||||
|
adminController.createPosition
|
||||||
|
);
|
||||||
|
|
||||||
|
router.put(
|
||||||
|
'/positions/:id',
|
||||||
|
authorize('admin', 'roles', 'update'),
|
||||||
|
[
|
||||||
|
param('id').isUUID(),
|
||||||
|
body('title').optional().notEmpty().trim(),
|
||||||
|
body('code').optional().notEmpty().trim(),
|
||||||
|
body('departmentId').optional().isUUID(),
|
||||||
|
body('level').optional().isInt({ min: 1 }),
|
||||||
|
],
|
||||||
|
validate,
|
||||||
|
adminController.updatePosition
|
||||||
|
);
|
||||||
|
|
||||||
router.put(
|
router.put(
|
||||||
'/positions/:id/permissions',
|
'/positions/:id/permissions',
|
||||||
authorize('admin', 'roles', 'update'),
|
authorize('admin', 'roles', 'update'),
|
||||||
@@ -100,4 +127,68 @@ router.put(
|
|||||||
adminController.updatePositionPermissions
|
adminController.updatePositionPermissions
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// ========== PERMISSION GROUPS (Phase 3 - multi-group) ==========
|
||||||
|
|
||||||
|
router.get(
|
||||||
|
'/permission-groups',
|
||||||
|
authorize('admin', 'roles', 'read'),
|
||||||
|
adminController.getPermissionGroups
|
||||||
|
);
|
||||||
|
|
||||||
|
router.post(
|
||||||
|
'/permission-groups',
|
||||||
|
authorize('admin', 'roles', 'create'),
|
||||||
|
[
|
||||||
|
body('name').notEmpty().trim(),
|
||||||
|
],
|
||||||
|
validate,
|
||||||
|
adminController.createPermissionGroup
|
||||||
|
);
|
||||||
|
|
||||||
|
router.put(
|
||||||
|
'/permission-groups/:id',
|
||||||
|
authorize('admin', 'roles', 'update'),
|
||||||
|
[param('id').isUUID()],
|
||||||
|
validate,
|
||||||
|
adminController.updatePermissionGroup
|
||||||
|
);
|
||||||
|
|
||||||
|
router.put(
|
||||||
|
'/permission-groups/:id/permissions',
|
||||||
|
authorize('admin', 'roles', 'update'),
|
||||||
|
[
|
||||||
|
param('id').isUUID(),
|
||||||
|
body('permissions').isArray(),
|
||||||
|
],
|
||||||
|
validate,
|
||||||
|
adminController.updatePermissionGroupPermissions
|
||||||
|
);
|
||||||
|
|
||||||
|
router.get(
|
||||||
|
'/users/:userId/roles',
|
||||||
|
authorize('admin', 'users', 'read'),
|
||||||
|
[param('userId').isUUID()],
|
||||||
|
validate,
|
||||||
|
adminController.getUserRoles
|
||||||
|
);
|
||||||
|
|
||||||
|
router.post(
|
||||||
|
'/users/:userId/roles',
|
||||||
|
authorize('admin', 'users', 'update'),
|
||||||
|
[
|
||||||
|
param('userId').isUUID(),
|
||||||
|
body('roleId').isUUID(),
|
||||||
|
],
|
||||||
|
validate,
|
||||||
|
adminController.assignUserRole
|
||||||
|
);
|
||||||
|
|
||||||
|
router.delete(
|
||||||
|
'/users/:userId/roles/:roleId',
|
||||||
|
authorize('admin', 'users', 'update'),
|
||||||
|
[param('userId').isUUID(), param('roleId').isUUID()],
|
||||||
|
validate,
|
||||||
|
adminController.removeUserRole
|
||||||
|
);
|
||||||
|
|
||||||
export default router;
|
export default router;
|
||||||
|
|||||||
@@ -406,6 +406,102 @@ class AdminService {
|
|||||||
return withUserCount;
|
return withUserCount;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async createPosition(data: {
|
||||||
|
title: string;
|
||||||
|
titleAr?: string;
|
||||||
|
code: string;
|
||||||
|
departmentId: string;
|
||||||
|
level?: number;
|
||||||
|
description?: string;
|
||||||
|
isActive?: boolean;
|
||||||
|
}) {
|
||||||
|
const existing = await prisma.position.findUnique({
|
||||||
|
where: { code: data.code },
|
||||||
|
});
|
||||||
|
if (existing) {
|
||||||
|
throw new AppError(400, 'كود الدور مستخدم - Position code already exists');
|
||||||
|
}
|
||||||
|
|
||||||
|
const dept = await prisma.department.findUnique({
|
||||||
|
where: { id: data.departmentId },
|
||||||
|
});
|
||||||
|
if (!dept) {
|
||||||
|
throw new AppError(400, 'القسم غير موجود - Department not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
return prisma.position.create({
|
||||||
|
data: {
|
||||||
|
title: data.title,
|
||||||
|
titleAr: data.titleAr,
|
||||||
|
code: data.code.trim().toUpperCase().replace(/\s+/g, '_'),
|
||||||
|
departmentId: data.departmentId,
|
||||||
|
level: data.level ?? 5,
|
||||||
|
description: data.description,
|
||||||
|
isActive: data.isActive ?? true,
|
||||||
|
},
|
||||||
|
include: {
|
||||||
|
department: { select: { name: true, nameAr: true } },
|
||||||
|
permissions: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async updatePosition(
|
||||||
|
positionId: string,
|
||||||
|
data: {
|
||||||
|
title?: string;
|
||||||
|
titleAr?: string;
|
||||||
|
code?: string;
|
||||||
|
departmentId?: string;
|
||||||
|
level?: number;
|
||||||
|
description?: string;
|
||||||
|
isActive?: boolean;
|
||||||
|
}
|
||||||
|
) {
|
||||||
|
const position = await prisma.position.findUnique({
|
||||||
|
where: { id: positionId },
|
||||||
|
});
|
||||||
|
if (!position) {
|
||||||
|
throw new AppError(404, 'الدور غير موجود - Position not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (data.code && data.code !== position.code) {
|
||||||
|
const existing = await prisma.position.findUnique({
|
||||||
|
where: { code: data.code },
|
||||||
|
});
|
||||||
|
if (existing) {
|
||||||
|
throw new AppError(400, 'كود الدور مستخدم - Position code already exists');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (data.departmentId && data.departmentId !== position.departmentId) {
|
||||||
|
const dept = await prisma.department.findUnique({
|
||||||
|
where: { id: data.departmentId },
|
||||||
|
});
|
||||||
|
if (!dept) {
|
||||||
|
throw new AppError(400, 'القسم غير موجود - Department not found');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const updateData: Record<string, any> = {};
|
||||||
|
if (data.title !== undefined) updateData.title = data.title;
|
||||||
|
if (data.titleAr !== undefined) updateData.titleAr = data.titleAr;
|
||||||
|
if (data.code !== undefined) updateData.code = data.code.trim().toUpperCase().replace(/\s+/g, '_');
|
||||||
|
if (data.departmentId !== undefined) updateData.departmentId = data.departmentId;
|
||||||
|
if (data.level !== undefined) updateData.level = data.level;
|
||||||
|
if (data.description !== undefined) updateData.description = data.description;
|
||||||
|
if (data.isActive !== undefined) updateData.isActive = data.isActive;
|
||||||
|
|
||||||
|
return prisma.position.update({
|
||||||
|
where: { id: positionId },
|
||||||
|
data: updateData,
|
||||||
|
include: {
|
||||||
|
department: { select: { name: true, nameAr: true } },
|
||||||
|
permissions: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
async updatePositionPermissions(positionId: string, permissions: Array<{ module: string; resource: string; actions: string[] }>) {
|
async updatePositionPermissions(positionId: string, permissions: Array<{ module: string; resource: string; actions: string[] }>) {
|
||||||
const position = await prisma.position.findUnique({ where: { id: positionId } });
|
const position = await prisma.position.findUnique({ where: { id: positionId } });
|
||||||
if (!position) {
|
if (!position) {
|
||||||
@@ -429,6 +525,116 @@ class AdminService {
|
|||||||
|
|
||||||
return this.getPositions().then((pos) => pos.find((p) => p.id === positionId) || position);
|
return this.getPositions().then((pos) => pos.find((p) => p.id === positionId) || position);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ========== PERMISSION GROUPS (Phase 3 - optional roles for multi-group) ==========
|
||||||
|
|
||||||
|
async getPermissionGroups() {
|
||||||
|
return prisma.role.findMany({
|
||||||
|
where: { isActive: true },
|
||||||
|
include: {
|
||||||
|
permissions: true,
|
||||||
|
_count: { select: { userRoles: true } },
|
||||||
|
},
|
||||||
|
orderBy: { name: 'asc' },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async createPermissionGroup(data: { name: string; nameAr?: string; description?: string }) {
|
||||||
|
const existing = await prisma.role.findUnique({ where: { name: data.name } });
|
||||||
|
if (existing) {
|
||||||
|
throw new AppError(400, 'اسم المجموعة مستخدم - Group name already exists');
|
||||||
|
}
|
||||||
|
return prisma.role.create({
|
||||||
|
data: {
|
||||||
|
name: data.name,
|
||||||
|
nameAr: data.nameAr,
|
||||||
|
description: data.description,
|
||||||
|
},
|
||||||
|
include: { permissions: true },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async updatePermissionGroup(
|
||||||
|
id: string,
|
||||||
|
data: { name?: string; nameAr?: string; description?: string; isActive?: boolean }
|
||||||
|
) {
|
||||||
|
const role = await prisma.role.findUnique({ where: { id } });
|
||||||
|
if (!role) {
|
||||||
|
throw new AppError(404, 'المجموعة غير موجودة - Group not found');
|
||||||
|
}
|
||||||
|
if (data.name && data.name !== role.name) {
|
||||||
|
const existing = await prisma.role.findUnique({ where: { name: data.name } });
|
||||||
|
if (existing) {
|
||||||
|
throw new AppError(400, 'اسم المجموعة مستخدم - Group name already exists');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return prisma.role.update({
|
||||||
|
where: { id },
|
||||||
|
data,
|
||||||
|
include: { permissions: true },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async updatePermissionGroupPermissions(
|
||||||
|
roleId: string,
|
||||||
|
permissions: Array<{ module: string; resource: string; actions: string[] }>
|
||||||
|
) {
|
||||||
|
await prisma.rolePermission.deleteMany({ where: { roleId } });
|
||||||
|
if (permissions.length > 0) {
|
||||||
|
await prisma.rolePermission.createMany({
|
||||||
|
data: permissions.map((p) => ({
|
||||||
|
roleId,
|
||||||
|
module: p.module,
|
||||||
|
resource: p.resource,
|
||||||
|
actions: p.actions,
|
||||||
|
})),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return prisma.role.findUnique({
|
||||||
|
where: { id: roleId },
|
||||||
|
include: { permissions: true },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async getUserRoles(userId: string) {
|
||||||
|
return prisma.userRole.findMany({
|
||||||
|
where: { userId },
|
||||||
|
include: {
|
||||||
|
role: { include: { permissions: true } },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async assignUserRole(userId: string, roleId: string) {
|
||||||
|
const [user, role] = await Promise.all([
|
||||||
|
prisma.user.findUnique({ where: { id: userId } }),
|
||||||
|
prisma.role.findFirst({ where: { id: roleId, isActive: true } }),
|
||||||
|
]);
|
||||||
|
if (!user) throw new AppError(404, 'المستخدم غير موجود - User not found');
|
||||||
|
if (!role) throw new AppError(404, 'المجموعة غير موجودة - Group not found');
|
||||||
|
|
||||||
|
const existing = await prisma.userRole.findUnique({
|
||||||
|
where: { userId_roleId: { userId, roleId } },
|
||||||
|
});
|
||||||
|
if (existing) {
|
||||||
|
throw new AppError(400, 'المستخدم منتمي بالفعل لهذه المجموعة - User already in group');
|
||||||
|
}
|
||||||
|
|
||||||
|
return prisma.userRole.create({
|
||||||
|
data: { userId, roleId },
|
||||||
|
include: { role: true },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async removeUserRole(userId: string, roleId: string) {
|
||||||
|
const deleted = await prisma.userRole.deleteMany({
|
||||||
|
where: { userId, roleId },
|
||||||
|
});
|
||||||
|
if (deleted.count === 0) {
|
||||||
|
throw new AppError(404, 'لم يتم العثور على الانتماء - User not in group');
|
||||||
|
}
|
||||||
|
return { success: true };
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const adminService = new AdminService();
|
export const adminService = new AdminService();
|
||||||
|
|||||||
35
backend/src/modules/dashboard/dashboard.controller.ts
Normal file
35
backend/src/modules/dashboard/dashboard.controller.ts
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
import { Response } from 'express';
|
||||||
|
import prisma from '../../config/database';
|
||||||
|
import { AuthRequest } from '../../shared/middleware/auth';
|
||||||
|
import { ResponseFormatter } from '../../shared/utils/responseFormatter';
|
||||||
|
|
||||||
|
class DashboardController {
|
||||||
|
async getStats(req: AuthRequest, res: Response) {
|
||||||
|
const userId = req.user!.id;
|
||||||
|
|
||||||
|
const [contactsCount, activeTasksCount, unreadNotificationsCount] = await Promise.all([
|
||||||
|
prisma.contact.count(),
|
||||||
|
prisma.task.count({
|
||||||
|
where: {
|
||||||
|
status: { notIn: ['COMPLETED', 'CANCELLED'] },
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
prisma.notification.count({
|
||||||
|
where: {
|
||||||
|
userId,
|
||||||
|
isRead: false,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
|
||||||
|
res.json(
|
||||||
|
ResponseFormatter.success({
|
||||||
|
contacts: contactsCount,
|
||||||
|
activeTasks: activeTasksCount,
|
||||||
|
notifications: unreadNotificationsCount,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default new DashboardController();
|
||||||
9
backend/src/modules/dashboard/dashboard.routes.ts
Normal file
9
backend/src/modules/dashboard/dashboard.routes.ts
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
import { Router } from 'express';
|
||||||
|
import { authenticate } from '../../shared/middleware/auth';
|
||||||
|
import dashboardController from './dashboard.controller';
|
||||||
|
|
||||||
|
const router = Router();
|
||||||
|
|
||||||
|
router.get('/stats', authenticate, dashboardController.getStats.bind(dashboardController));
|
||||||
|
|
||||||
|
export default router;
|
||||||
@@ -19,14 +19,20 @@ export class HRController {
|
|||||||
|
|
||||||
async findAllEmployees(req: AuthRequest, res: Response, next: NextFunction) {
|
async findAllEmployees(req: AuthRequest, res: Response, next: NextFunction) {
|
||||||
try {
|
try {
|
||||||
const page = parseInt(req.query.page as string) || 1;
|
const rawPage = parseInt(req.query.page as string, 10);
|
||||||
const pageSize = parseInt(req.query.pageSize as string) || 20;
|
const rawPageSize = parseInt(req.query.pageSize as string, 10);
|
||||||
|
const page = Number.isNaN(rawPage) || rawPage < 1 ? 1 : rawPage;
|
||||||
|
const pageSize = Number.isNaN(rawPageSize) || rawPageSize < 1 || rawPageSize > 100 ? 20 : rawPageSize;
|
||||||
|
|
||||||
const filters = {
|
const rawSearch = req.query.search as string;
|
||||||
search: req.query.search,
|
const rawDepartmentId = req.query.departmentId as string;
|
||||||
departmentId: req.query.departmentId,
|
const rawStatus = req.query.status as string;
|
||||||
status: req.query.status,
|
const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||||
};
|
|
||||||
|
const filters: Record<string, string | undefined> = {};
|
||||||
|
if (rawSearch && typeof rawSearch === 'string' && rawSearch.trim()) filters.search = rawSearch.trim();
|
||||||
|
if (rawDepartmentId && uuidRegex.test(rawDepartmentId)) filters.departmentId = rawDepartmentId;
|
||||||
|
if (rawStatus && rawStatus !== 'all' && rawStatus.trim()) filters.status = rawStatus;
|
||||||
|
|
||||||
const result = await hrService.findAllEmployees(filters, page, pageSize);
|
const result = await hrService.findAllEmployees(filters, page, pageSize);
|
||||||
res.json(ResponseFormatter.paginated(result.employees, result.total, result.page, result.pageSize));
|
res.json(ResponseFormatter.paginated(result.employees, result.total, result.page, result.pageSize));
|
||||||
@@ -135,6 +141,42 @@ export class HRController {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async getDepartmentsHierarchy(req: AuthRequest, res: Response, next: NextFunction) {
|
||||||
|
try {
|
||||||
|
const tree = await hrService.getDepartmentsHierarchy();
|
||||||
|
res.json(ResponseFormatter.success(tree));
|
||||||
|
} catch (error) {
|
||||||
|
next(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async createDepartment(req: AuthRequest, res: Response, next: NextFunction) {
|
||||||
|
try {
|
||||||
|
const department = await hrService.createDepartment(req.body, req.user!.id);
|
||||||
|
res.status(201).json(ResponseFormatter.success(department, 'تم إضافة القسم بنجاح - Department created'));
|
||||||
|
} catch (error) {
|
||||||
|
next(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async updateDepartment(req: AuthRequest, res: Response, next: NextFunction) {
|
||||||
|
try {
|
||||||
|
const department = await hrService.updateDepartment(req.params.id, req.body, req.user!.id);
|
||||||
|
res.json(ResponseFormatter.success(department, 'تم تحديث القسم - Department updated'));
|
||||||
|
} catch (error) {
|
||||||
|
next(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async deleteDepartment(req: AuthRequest, res: Response, next: NextFunction) {
|
||||||
|
try {
|
||||||
|
await hrService.deleteDepartment(req.params.id, req.user!.id);
|
||||||
|
res.json(ResponseFormatter.success({ success: true }, 'تم حذف القسم - Department deleted'));
|
||||||
|
} catch (error) {
|
||||||
|
next(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// ========== POSITIONS ==========
|
// ========== POSITIONS ==========
|
||||||
|
|
||||||
async findAllPositions(req: AuthRequest, res: Response, next: NextFunction) {
|
async findAllPositions(req: AuthRequest, res: Response, next: NextFunction) {
|
||||||
|
|||||||
@@ -32,6 +32,10 @@ router.post('/salaries/process', authorize('hr', 'salaries', 'process'), hrContr
|
|||||||
// ========== DEPARTMENTS ==========
|
// ========== DEPARTMENTS ==========
|
||||||
|
|
||||||
router.get('/departments', authorize('hr', 'all', 'read'), hrController.findAllDepartments);
|
router.get('/departments', authorize('hr', 'all', 'read'), hrController.findAllDepartments);
|
||||||
|
router.get('/departments/hierarchy', authorize('hr', 'all', 'read'), hrController.getDepartmentsHierarchy);
|
||||||
|
router.post('/departments', authorize('hr', 'all', 'create'), hrController.createDepartment);
|
||||||
|
router.put('/departments/:id', authorize('hr', 'all', 'update'), hrController.updateDepartment);
|
||||||
|
router.delete('/departments/:id', authorize('hr', 'all', 'delete'), hrController.deleteDepartment);
|
||||||
|
|
||||||
// ========== POSITIONS ==========
|
// ========== POSITIONS ==========
|
||||||
|
|
||||||
|
|||||||
@@ -5,14 +5,52 @@ import { AuditLogger } from '../../shared/utils/auditLogger';
|
|||||||
class HRService {
|
class HRService {
|
||||||
// ========== EMPLOYEES ==========
|
// ========== EMPLOYEES ==========
|
||||||
|
|
||||||
|
private normalizeEmployeeData(data: any): Record<string, any> {
|
||||||
|
const toStr = (v: any) => (v != null && String(v).trim()) ? String(v).trim() : undefined;
|
||||||
|
const toDate = (v: any) => {
|
||||||
|
if (!v || !String(v).trim()) return undefined;
|
||||||
|
const d = new Date(v);
|
||||||
|
return isNaN(d.getTime()) ? undefined : d;
|
||||||
|
};
|
||||||
|
const toNum = (v: any) => (v != null && v !== '') ? Number(v) : undefined;
|
||||||
|
|
||||||
|
const raw: Record<string, any> = {
|
||||||
|
firstName: toStr(data.firstName),
|
||||||
|
lastName: toStr(data.lastName),
|
||||||
|
firstNameAr: toStr(data.firstNameAr),
|
||||||
|
lastNameAr: toStr(data.lastNameAr),
|
||||||
|
email: toStr(data.email),
|
||||||
|
phone: toStr(data.phone),
|
||||||
|
mobile: toStr(data.mobile),
|
||||||
|
dateOfBirth: toDate(data.dateOfBirth),
|
||||||
|
gender: toStr(data.gender),
|
||||||
|
nationality: toStr(data.nationality),
|
||||||
|
nationalId: toStr(data.nationalId),
|
||||||
|
employmentType: toStr(data.employmentType),
|
||||||
|
contractType: toStr(data.contractType),
|
||||||
|
hireDate: toDate(data.hireDate),
|
||||||
|
departmentId: toStr(data.departmentId),
|
||||||
|
positionId: toStr(data.positionId),
|
||||||
|
reportingToId: toStr(data.reportingToId) || undefined,
|
||||||
|
basicSalary: toNum(data.baseSalary ?? data.basicSalary) ?? 0,
|
||||||
|
};
|
||||||
|
return Object.fromEntries(Object.entries(raw).filter(([, v]) => v !== undefined));
|
||||||
|
}
|
||||||
|
|
||||||
async createEmployee(data: any, userId: string) {
|
async createEmployee(data: any, userId: string) {
|
||||||
const uniqueEmployeeId = await this.generateEmployeeId();
|
const uniqueEmployeeId = await this.generateEmployeeId();
|
||||||
|
const payload = this.normalizeEmployeeData(data);
|
||||||
|
|
||||||
|
if (!payload.firstName || !payload.lastName || !payload.email || !payload.mobile ||
|
||||||
|
!payload.hireDate || !payload.departmentId || !payload.positionId) {
|
||||||
|
throw new AppError(400, 'بيانات غير مكتملة - Missing required fields: firstName, lastName, email, mobile, hireDate, departmentId, positionId');
|
||||||
|
}
|
||||||
|
|
||||||
const employee = await prisma.employee.create({
|
const employee = await prisma.employee.create({
|
||||||
data: {
|
data: {
|
||||||
uniqueEmployeeId,
|
uniqueEmployeeId,
|
||||||
...data,
|
...payload,
|
||||||
},
|
} as any,
|
||||||
include: {
|
include: {
|
||||||
department: true,
|
department: true,
|
||||||
position: true,
|
position: true,
|
||||||
@@ -132,9 +170,10 @@ class HRService {
|
|||||||
throw new AppError(404, 'الموظف غير موجود - Employee not found');
|
throw new AppError(404, 'الموظف غير موجود - Employee not found');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const payload = this.normalizeEmployeeData(data);
|
||||||
const employee = await prisma.employee.update({
|
const employee = await prisma.employee.update({
|
||||||
where: { id },
|
where: { id },
|
||||||
data,
|
data: payload,
|
||||||
include: {
|
include: {
|
||||||
department: true,
|
department: true,
|
||||||
position: true,
|
position: true,
|
||||||
@@ -383,11 +422,112 @@ class HRService {
|
|||||||
async findAllDepartments() {
|
async findAllDepartments() {
|
||||||
const departments = await prisma.department.findMany({
|
const departments = await prisma.department.findMany({
|
||||||
where: { isActive: true },
|
where: { isActive: true },
|
||||||
|
include: {
|
||||||
|
parent: { select: { id: true, name: true, nameAr: true } },
|
||||||
|
_count: { select: { children: true, employees: true } }
|
||||||
|
},
|
||||||
orderBy: { name: 'asc' }
|
orderBy: { name: 'asc' }
|
||||||
});
|
});
|
||||||
return departments;
|
return departments;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async getDepartmentsHierarchy() {
|
||||||
|
const departments = await prisma.department.findMany({
|
||||||
|
where: { isActive: true },
|
||||||
|
include: {
|
||||||
|
parent: { select: { id: true, name: true, nameAr: true } },
|
||||||
|
employees: {
|
||||||
|
where: { status: 'ACTIVE' },
|
||||||
|
select: { id: true, firstName: true, lastName: true, firstNameAr: true, lastNameAr: true, position: { select: { title: true, titleAr: true } } }
|
||||||
|
},
|
||||||
|
positions: { select: { id: true, title: true, titleAr: true } },
|
||||||
|
_count: { select: { children: true, employees: true } }
|
||||||
|
},
|
||||||
|
orderBy: { name: 'asc' }
|
||||||
|
});
|
||||||
|
const buildTree = (parentId: string | null): any[] =>
|
||||||
|
departments
|
||||||
|
.filter((d) => d.parentId === parentId)
|
||||||
|
.map((d) => ({
|
||||||
|
id: d.id,
|
||||||
|
name: d.name,
|
||||||
|
nameAr: d.nameAr,
|
||||||
|
code: d.code,
|
||||||
|
parentId: d.parentId,
|
||||||
|
description: d.description,
|
||||||
|
employees: d.employees,
|
||||||
|
positions: d.positions,
|
||||||
|
_count: d._count,
|
||||||
|
children: buildTree(d.id)
|
||||||
|
}));
|
||||||
|
return buildTree(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
async createDepartment(data: { name: string; nameAr?: string; code: string; parentId?: string; description?: string }, userId: string) {
|
||||||
|
const existing = await prisma.department.findUnique({ where: { code: data.code } });
|
||||||
|
if (existing) {
|
||||||
|
throw new AppError(400, 'كود القسم مستخدم مسبقاً - Department code already exists');
|
||||||
|
}
|
||||||
|
if (data.parentId) {
|
||||||
|
const parent = await prisma.department.findUnique({ where: { id: data.parentId } });
|
||||||
|
if (!parent) {
|
||||||
|
throw new AppError(400, 'القسم الأب غير موجود - Parent department not found');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const department = await prisma.department.create({
|
||||||
|
data: {
|
||||||
|
name: data.name,
|
||||||
|
nameAr: data.nameAr,
|
||||||
|
code: data.code,
|
||||||
|
parentId: data.parentId || null,
|
||||||
|
description: data.description
|
||||||
|
}
|
||||||
|
});
|
||||||
|
await AuditLogger.log({ entityType: 'DEPARTMENT', entityId: department.id, action: 'CREATE', userId, changes: { created: department } });
|
||||||
|
return department;
|
||||||
|
}
|
||||||
|
|
||||||
|
async updateDepartment(id: string, data: { name?: string; nameAr?: string; code?: string; parentId?: string; description?: string; isActive?: boolean }, userId: string) {
|
||||||
|
const existing = await prisma.department.findUnique({ where: { id } });
|
||||||
|
if (!existing) {
|
||||||
|
throw new AppError(404, 'القسم غير موجود - Department not found');
|
||||||
|
}
|
||||||
|
if (data.code && data.code !== existing.code) {
|
||||||
|
const duplicate = await prisma.department.findUnique({ where: { code: data.code } });
|
||||||
|
if (duplicate) {
|
||||||
|
throw new AppError(400, 'كود القسم مستخدم مسبقاً - Department code already exists');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (data.parentId === id) {
|
||||||
|
throw new AppError(400, 'لا يمكن تعيين القسم كأب لنفسه - Department cannot be its own parent');
|
||||||
|
}
|
||||||
|
const department = await prisma.department.update({
|
||||||
|
where: { id },
|
||||||
|
data: { name: data.name, nameAr: data.nameAr, code: data.code, parentId: data.parentId ?? undefined, description: data.description, isActive: data.isActive }
|
||||||
|
});
|
||||||
|
await AuditLogger.log({ entityType: 'DEPARTMENT', entityId: id, action: 'UPDATE', userId, changes: { before: existing, after: department } });
|
||||||
|
return department;
|
||||||
|
}
|
||||||
|
|
||||||
|
async deleteDepartment(id: string, userId: string) {
|
||||||
|
const dept = await prisma.department.findUnique({
|
||||||
|
where: { id },
|
||||||
|
include: { _count: { select: { children: true, employees: true } } }
|
||||||
|
});
|
||||||
|
if (!dept) {
|
||||||
|
throw new AppError(404, 'القسم غير موجود - Department not found');
|
||||||
|
}
|
||||||
|
if (dept._count.children > 0) {
|
||||||
|
throw new AppError(400, 'لا يمكن حذف قسم يحتوي على أقسام فرعية - Cannot delete department with sub-departments');
|
||||||
|
}
|
||||||
|
if (dept._count.employees > 0) {
|
||||||
|
throw new AppError(400, 'لا يمكن حذف قسم فيه موظفون - Cannot delete department with employees');
|
||||||
|
}
|
||||||
|
await prisma.department.delete({ where: { id } });
|
||||||
|
await AuditLogger.log({ entityType: 'DEPARTMENT', entityId: id, action: 'DELETE', userId });
|
||||||
|
return { success: true };
|
||||||
|
}
|
||||||
|
|
||||||
// ========== POSITIONS ==========
|
// ========== POSITIONS ==========
|
||||||
|
|
||||||
async findAllPositions() {
|
async findAllPositions() {
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import adminRoutes from '../modules/admin/admin.routes';
|
|||||||
import authRoutes from '../modules/auth/auth.routes';
|
import authRoutes from '../modules/auth/auth.routes';
|
||||||
import contactsRoutes from '../modules/contacts/contacts.routes';
|
import contactsRoutes from '../modules/contacts/contacts.routes';
|
||||||
import crmRoutes from '../modules/crm/crm.routes';
|
import crmRoutes from '../modules/crm/crm.routes';
|
||||||
|
import dashboardRoutes from '../modules/dashboard/dashboard.routes';
|
||||||
import hrRoutes from '../modules/hr/hr.routes';
|
import hrRoutes from '../modules/hr/hr.routes';
|
||||||
import inventoryRoutes from '../modules/inventory/inventory.routes';
|
import inventoryRoutes from '../modules/inventory/inventory.routes';
|
||||||
import projectsRoutes from '../modules/projects/projects.routes';
|
import projectsRoutes from '../modules/projects/projects.routes';
|
||||||
@@ -12,6 +13,7 @@ const router = Router();
|
|||||||
|
|
||||||
// Module routes
|
// Module routes
|
||||||
router.use('/admin', adminRoutes);
|
router.use('/admin', adminRoutes);
|
||||||
|
router.use('/dashboard', dashboardRoutes);
|
||||||
router.use('/auth', authRoutes);
|
router.use('/auth', authRoutes);
|
||||||
router.use('/contacts', contactsRoutes);
|
router.use('/contacts', contactsRoutes);
|
||||||
router.use('/crm', crmRoutes);
|
router.use('/crm', crmRoutes);
|
||||||
|
|||||||
@@ -4,12 +4,47 @@ import { config } from '../../config';
|
|||||||
import { AppError } from './errorHandler';
|
import { AppError } from './errorHandler';
|
||||||
import prisma from '../../config/database';
|
import prisma from '../../config/database';
|
||||||
|
|
||||||
|
export interface EffectivePermission {
|
||||||
|
module: string;
|
||||||
|
resource: string;
|
||||||
|
actions: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
function mergePermissions(
|
||||||
|
positionPerms: { module: string; resource: string; actions: unknown }[],
|
||||||
|
rolePerms: { module: string; resource: string; actions: unknown }[]
|
||||||
|
): EffectivePermission[] {
|
||||||
|
const key = (m: string, r: string) => `${m}:${r}`;
|
||||||
|
const map = new Map<string, Set<string>>();
|
||||||
|
|
||||||
|
const add = (m: string, r: string, actions: unknown) => {
|
||||||
|
const arr = Array.isArray(actions) ? actions : [];
|
||||||
|
const actionSet = new Set<string>(arr.map(String));
|
||||||
|
const k = key(m, r);
|
||||||
|
const existing = map.get(k);
|
||||||
|
if (existing) {
|
||||||
|
actionSet.forEach((a) => existing.add(a));
|
||||||
|
} else {
|
||||||
|
map.set(k, actionSet);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
(positionPerms || []).forEach((p) => add(p.module, p.resource, p.actions));
|
||||||
|
(rolePerms || []).forEach((p) => add(p.module, p.resource, p.actions));
|
||||||
|
|
||||||
|
return Array.from(map.entries()).map(([k, actions]) => {
|
||||||
|
const [module, resource] = k.split(':');
|
||||||
|
return { module, resource, actions: Array.from(actions) };
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
export interface AuthRequest extends Request {
|
export interface AuthRequest extends Request {
|
||||||
user?: {
|
user?: {
|
||||||
id: string;
|
id: string;
|
||||||
email: string;
|
email: string;
|
||||||
employeeId?: string;
|
employeeId?: string;
|
||||||
employee?: any;
|
employee?: any;
|
||||||
|
effectivePermissions?: EffectivePermission[];
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -33,7 +68,7 @@ export const authenticate = async (
|
|||||||
email: string;
|
email: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
// Get user with employee info
|
// Get user with employee + roles (Phase 3: multi-group)
|
||||||
const user = await prisma.user.findUnique({
|
const user = await prisma.user.findUnique({
|
||||||
where: { id: decoded.id },
|
where: { id: decoded.id },
|
||||||
include: {
|
include: {
|
||||||
@@ -47,6 +82,14 @@ export const authenticate = async (
|
|||||||
department: true,
|
department: true,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
userRoles: {
|
||||||
|
where: { role: { isActive: true } },
|
||||||
|
include: {
|
||||||
|
role: {
|
||||||
|
include: { permissions: true },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -59,12 +102,18 @@ export const authenticate = async (
|
|||||||
throw new AppError(403, 'الوصول مرفوض - Access denied. Active employee record required.');
|
throw new AppError(403, 'الوصول مرفوض - Access denied. Active employee record required.');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Attach user to request
|
const positionPerms = user.employee?.position?.permissions ?? [];
|
||||||
|
const rolePerms = (user as any).userRoles?.flatMap(
|
||||||
|
(ur: any) => ur.role?.permissions ?? []
|
||||||
|
) ?? [];
|
||||||
|
const effectivePermissions = mergePermissions(positionPerms, rolePerms);
|
||||||
|
|
||||||
req.user = {
|
req.user = {
|
||||||
id: user.id,
|
id: user.id,
|
||||||
email: user.email,
|
email: user.email,
|
||||||
employeeId: user.employeeId || undefined,
|
employeeId: user.employeeId || undefined,
|
||||||
employee: user.employee,
|
employee: user.employee,
|
||||||
|
effectivePermissions,
|
||||||
};
|
};
|
||||||
|
|
||||||
next();
|
next();
|
||||||
@@ -76,25 +125,24 @@ export const authenticate = async (
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Permission checking middleware
|
// Permission checking middleware (Position + Role permissions merged)
|
||||||
export const authorize = (module: string, resource: string, action: string) => {
|
export const authorize = (module: string, resource: string, action: string) => {
|
||||||
return async (req: AuthRequest, res: Response, next: NextFunction) => {
|
return async (req: AuthRequest, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
if (!req.user?.employee?.position?.permissions) {
|
const perms = req.user?.effectivePermissions;
|
||||||
|
if (!perms || perms.length === 0) {
|
||||||
throw new AppError(403, 'الوصول مرفوض - Access denied');
|
throw new AppError(403, 'الوصول مرفوض - Access denied');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Find permission for this module and resource (check exact match or wildcard)
|
const permission = perms.find(
|
||||||
const permission = req.user.employee.position.permissions.find(
|
(p) => p.module === module && (p.resource === resource || p.resource === '*' || p.resource === 'all')
|
||||||
(p: any) => p.module === module && (p.resource === resource || p.resource === '*' || p.resource === 'all')
|
|
||||||
);
|
);
|
||||||
|
|
||||||
if (!permission) {
|
if (!permission) {
|
||||||
throw new AppError(403, 'الوصول مرفوض - Access denied');
|
throw new AppError(403, 'الوصول مرفوض - Access denied');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if action is allowed (check exact match or wildcard)
|
const actions = permission.actions;
|
||||||
const actions = permission.actions as string[];
|
|
||||||
if (!actions.includes(action) && !actions.includes('*') && !actions.includes('all')) {
|
if (!actions.includes(action) && !actions.includes('*') && !actions.includes('all')) {
|
||||||
throw new AppError(403, 'الوصول مرفوض - Access denied');
|
throw new AppError(403, 'الوصول مرفوض - Access denied');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -40,10 +40,12 @@ export const errorHandler = (
|
|||||||
|
|
||||||
// Handle validation errors
|
// Handle validation errors
|
||||||
if (err instanceof Prisma.PrismaClientValidationError) {
|
if (err instanceof Prisma.PrismaClientValidationError) {
|
||||||
|
const detail = process.env.NODE_ENV !== 'production' ? err.message : undefined;
|
||||||
return res.status(400).json({
|
return res.status(400).json({
|
||||||
success: false,
|
success: false,
|
||||||
message: 'بيانات غير صالحة - Invalid data',
|
message: 'بيانات غير صالحة - Invalid data',
|
||||||
error: 'VALIDATION_ERROR',
|
error: 'VALIDATION_ERROR',
|
||||||
|
...(detail && { detail }),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -5,8 +5,8 @@
|
|||||||
Clean the production database so you can load **new real data** that will reflect across the system at all levels. This removes existing (e.g. test/demo) data and leaves the database in a state where:
|
Clean the production database so you can load **new real data** that will reflect across the system at all levels. This removes existing (e.g. test/demo) data and leaves the database in a state where:
|
||||||
|
|
||||||
- Schema and migrations are unchanged
|
- Schema and migrations are unchanged
|
||||||
- Base configuration is restored (pipelines, categories, departments, roles, default users)
|
- One System Administrator user remains for configuration
|
||||||
- All business data (contacts, deals, quotes, projects, etc.) is removed so you can enter new real data
|
- All business data (contacts, deals, quotes, projects, etc.) is removed so you can enter new real data manually
|
||||||
|
|
||||||
## ⚠️ Important
|
## ⚠️ Important
|
||||||
|
|
||||||
@@ -21,7 +21,7 @@ Clean the production database so you can load **new real data** that will reflec
|
|||||||
This truncates all tables and then runs the seed so you get:
|
This truncates all tables and then runs the seed so you get:
|
||||||
|
|
||||||
- Empty business data (contacts, deals, quotes, projects, inventory, etc.)
|
- Empty business data (contacts, deals, quotes, projects, inventory, etc.)
|
||||||
- Restored base data: departments, positions, permissions, employees, users, contact categories, product categories, pipelines, one warehouse
|
- One System Administrator user (admin@system.local) with full access to all modules
|
||||||
|
|
||||||
### Steps on production server
|
### Steps on production server
|
||||||
|
|
||||||
@@ -87,19 +87,17 @@ All rows are removed from every table, including:
|
|||||||
- Audit logs, notifications, approvals
|
- Audit logs, notifications, approvals
|
||||||
- Users, employees, departments, positions, permissions
|
- Users, employees, departments, positions, permissions
|
||||||
|
|
||||||
Then the **seed** recreates only the base data (users, departments, positions, permissions, employees, contact/product categories, pipelines, one warehouse).
|
Then the **seed** recreates only the base data (one System Administrator user with full access). No categories, pipelines, or warehouses—you configure these manually.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Default users after re-seed
|
## Default user after re-seed
|
||||||
|
|
||||||
| Role | Email | Password | Access |
|
| Role | Email | Password | Access |
|
||||||
|-------------------|--------------------------|-----------|---------------|
|
|-------------------|----------------------|-----------|-------------|
|
||||||
| General Manager | gm@atmata.com | Admin@123 | Full system |
|
| System Administrator | admin@system.local | Admin@123 | Full system |
|
||||||
| Sales Manager | sales.manager@atmata.com | Admin@123 | Contacts, CRM |
|
|
||||||
| Sales Representative | sales.rep@atmata.com | Admin@123 | Basic CRM |
|
|
||||||
|
|
||||||
Change these passwords after first login in production.
|
Change the password after first login in production.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -43,8 +43,8 @@ export default function AuditLogs() {
|
|||||||
fetchLogs();
|
fetchLogs();
|
||||||
}, [fetchLogs]);
|
}, [fetchLogs]);
|
||||||
|
|
||||||
const formatDate = (d: string) =>
|
const formatDate = (d: string | null | undefined) =>
|
||||||
new Date(d).toLocaleString('ar-SA', { dateStyle: 'medium', timeStyle: 'short' });
|
d ? new Date(d).toLocaleString('ar-SA', { dateStyle: 'medium', timeStyle: 'short' }) : '-';
|
||||||
|
|
||||||
const getActionLabel = (a: string) => {
|
const getActionLabel = (a: string) => {
|
||||||
const labels: Record<string, string> = {
|
const labels: Record<string, string> = {
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import { usePathname } from 'next/navigation'
|
|||||||
import {
|
import {
|
||||||
Users,
|
Users,
|
||||||
Shield,
|
Shield,
|
||||||
|
UsersRound,
|
||||||
Database,
|
Database,
|
||||||
Settings,
|
Settings,
|
||||||
FileText,
|
FileText,
|
||||||
@@ -27,6 +28,7 @@ function AdminLayoutContent({ children }: { children: React.ReactNode }) {
|
|||||||
{ icon: LayoutDashboard, label: 'لوحة التحكم', href: '/admin', exact: true },
|
{ icon: LayoutDashboard, label: 'لوحة التحكم', href: '/admin', exact: true },
|
||||||
{ icon: Users, label: 'إدارة المستخدمين', href: '/admin/users' },
|
{ icon: Users, label: 'إدارة المستخدمين', href: '/admin/users' },
|
||||||
{ icon: Shield, label: 'الأدوار والصلاحيات', href: '/admin/roles' },
|
{ icon: Shield, label: 'الأدوار والصلاحيات', href: '/admin/roles' },
|
||||||
|
{ icon: UsersRound, label: 'مجموعات الصلاحيات', href: '/admin/permission-groups' },
|
||||||
{ icon: Database, label: 'النسخ الاحتياطي', href: '/admin/backup' },
|
{ icon: Database, label: 'النسخ الاحتياطي', href: '/admin/backup' },
|
||||||
{ icon: Settings, label: 'إعدادات النظام', href: '/admin/settings' },
|
{ icon: Settings, label: 'إعدادات النظام', href: '/admin/settings' },
|
||||||
{ icon: FileText, label: 'سجل العمليات', href: '/admin/audit-logs' },
|
{ icon: FileText, label: 'سجل العمليات', href: '/admin/audit-logs' },
|
||||||
|
|||||||
@@ -50,7 +50,8 @@ export default function AdminDashboard() {
|
|||||||
return labels[a] || a;
|
return labels[a] || a;
|
||||||
};
|
};
|
||||||
|
|
||||||
const formatTime = (d: string) => {
|
const formatTime = (d: string | null | undefined) => {
|
||||||
|
if (!d) return '-';
|
||||||
const diff = Date.now() - new Date(d).getTime();
|
const diff = Date.now() - new Date(d).getTime();
|
||||||
const mins = Math.floor(diff / 60000);
|
const mins = Math.floor(diff / 60000);
|
||||||
const hours = Math.floor(diff / 3600000);
|
const hours = Math.floor(diff / 3600000);
|
||||||
|
|||||||
371
frontend/src/app/admin/permission-groups/page.tsx
Normal file
371
frontend/src/app/admin/permission-groups/page.tsx
Normal file
@@ -0,0 +1,371 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useState, useEffect, useCallback } from 'react';
|
||||||
|
import { UsersRound, Edit, Users, Check, X, Plus } from 'lucide-react';
|
||||||
|
import { permissionGroupsAPI } from '@/lib/api/admin';
|
||||||
|
import type { PermissionGroup } from '@/lib/api/admin';
|
||||||
|
import Modal from '@/components/Modal';
|
||||||
|
import LoadingSpinner from '@/components/LoadingSpinner';
|
||||||
|
|
||||||
|
const MODULES = [
|
||||||
|
{ id: 'contacts', name: 'إدارة جهات الاتصال', nameEn: 'Contact Management' },
|
||||||
|
{ id: 'crm', name: 'إدارة علاقات العملاء', nameEn: 'CRM' },
|
||||||
|
{ id: 'inventory', name: 'المخزون والأصول', nameEn: 'Inventory & Assets' },
|
||||||
|
{ id: 'projects', name: 'المهام والمشاريع', nameEn: 'Tasks & Projects' },
|
||||||
|
{ id: 'hr', name: 'الموارد البشرية', nameEn: 'HR Management' },
|
||||||
|
{ id: 'marketing', name: 'التسويق', nameEn: 'Marketing' },
|
||||||
|
{ id: 'admin', name: 'لوحة الإدارة', nameEn: 'Admin' },
|
||||||
|
];
|
||||||
|
|
||||||
|
const ACTIONS = [
|
||||||
|
{ id: 'read', name: 'عرض' },
|
||||||
|
{ id: 'create', name: 'إنشاء' },
|
||||||
|
{ id: 'update', name: 'تعديل' },
|
||||||
|
{ id: 'delete', name: 'حذف' },
|
||||||
|
{ id: 'export', name: 'تصدير' },
|
||||||
|
{ id: 'approve', name: 'اعتماد' },
|
||||||
|
{ id: 'merge', name: 'دمج' },
|
||||||
|
];
|
||||||
|
|
||||||
|
function hasAction(perm: { actions?: unknown } | undefined, action: string): boolean {
|
||||||
|
if (!perm?.actions) return false;
|
||||||
|
const actions = Array.isArray(perm.actions) ? perm.actions : [];
|
||||||
|
return actions.includes('*') || actions.includes('all') || actions.includes(action);
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildPermissionsFromMatrix(matrix: Record<string, Record<string, boolean>>) {
|
||||||
|
return MODULES.filter((m) => Object.values(matrix[m.id] || {}).some(Boolean)).map((m) => {
|
||||||
|
const actions = ACTIONS.filter((a) => matrix[m.id]?.[a.id]).map((a) => a.id);
|
||||||
|
return {
|
||||||
|
module: m.id,
|
||||||
|
resource: '*',
|
||||||
|
actions: actions.length === ACTIONS.length ? ['*'] : actions,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildMatrixFromPermissions(permissions: { module: string; resource: string; actions: string[] }[]) {
|
||||||
|
const matrix: Record<string, Record<string, boolean>> = {};
|
||||||
|
for (const m of MODULES) {
|
||||||
|
matrix[m.id] = {};
|
||||||
|
const perm = permissions.find((p) => p.module === m.id && (p.resource === '*' || p.resource === m.id));
|
||||||
|
const hasAll = perm && (Array.isArray(perm.actions)
|
||||||
|
? perm.actions.includes('*') || perm.actions.includes('all')
|
||||||
|
: false);
|
||||||
|
for (const a of ACTIONS) {
|
||||||
|
matrix[m.id][a.id] = hasAll || hasAction(perm, a.id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return matrix;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function PermissionGroupsPage() {
|
||||||
|
const [groups, setGroups] = useState<PermissionGroup[]>([]);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [selectedId, setSelectedId] = useState<string | null>(null);
|
||||||
|
const [showEditModal, setShowEditModal] = useState(false);
|
||||||
|
const [showCreateModal, setShowCreateModal] = useState(false);
|
||||||
|
const [createForm, setCreateForm] = useState({ name: '', nameAr: '', description: '' });
|
||||||
|
type PermissionMatrix = Record<string, Record<string, boolean>>;
|
||||||
|
const [permissionMatrix, setPermissionMatrix] = useState<PermissionMatrix>({});
|
||||||
|
const [saving, setSaving] = useState(false);
|
||||||
|
|
||||||
|
const fetchGroups = useCallback(async () => {
|
||||||
|
setLoading(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const list = await permissionGroupsAPI.getAll();
|
||||||
|
setGroups(list);
|
||||||
|
if (selectedId && !list.find((g) => g.id === selectedId)) setSelectedId(null);
|
||||||
|
} catch (err: unknown) {
|
||||||
|
setError(err instanceof Error ? err.message : 'فشل تحميل المجموعات');
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}, [selectedId]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
fetchGroups();
|
||||||
|
}, [fetchGroups]);
|
||||||
|
|
||||||
|
const currentGroup = groups.find((g) => g.id === selectedId);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (currentGroup) {
|
||||||
|
setPermissionMatrix(buildMatrixFromPermissions(currentGroup.permissions || []));
|
||||||
|
}
|
||||||
|
}, [currentGroup?.id, currentGroup?.permissions]);
|
||||||
|
|
||||||
|
const handleCreate = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!createForm.name.trim()) {
|
||||||
|
alert('الاسم مطلوب');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setSaving(true);
|
||||||
|
try {
|
||||||
|
const group = await permissionGroupsAPI.create({
|
||||||
|
name: createForm.name.trim(),
|
||||||
|
nameAr: createForm.nameAr.trim() || undefined,
|
||||||
|
description: createForm.description.trim() || undefined,
|
||||||
|
});
|
||||||
|
setShowCreateModal(false);
|
||||||
|
setCreateForm({ name: '', nameAr: '', description: '' });
|
||||||
|
await fetchGroups();
|
||||||
|
setSelectedId(group.id);
|
||||||
|
setShowEditModal(true);
|
||||||
|
} catch (err: unknown) {
|
||||||
|
alert(err instanceof Error ? err.message : 'فشل الإنشاء');
|
||||||
|
} finally {
|
||||||
|
setSaving(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSavePermissions = async () => {
|
||||||
|
if (!selectedId) return;
|
||||||
|
setSaving(true);
|
||||||
|
try {
|
||||||
|
const permissions = buildPermissionsFromMatrix(permissionMatrix);
|
||||||
|
await permissionGroupsAPI.updatePermissions(selectedId, permissions);
|
||||||
|
setShowEditModal(false);
|
||||||
|
fetchGroups();
|
||||||
|
} catch (err: unknown) {
|
||||||
|
alert(err instanceof Error ? err.message : 'فشل الحفظ');
|
||||||
|
} finally {
|
||||||
|
setSaving(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleTogglePermission = (moduleId: string, actionId: string) => {
|
||||||
|
setPermissionMatrix((prev) => ({
|
||||||
|
...prev,
|
||||||
|
[moduleId]: {
|
||||||
|
...(prev[moduleId] || {}),
|
||||||
|
[actionId]: !prev[moduleId]?.[actionId],
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<div className="mb-8 flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-3xl font-bold text-gray-900 mb-2">مجموعات الصلاحيات</h1>
|
||||||
|
<p className="text-gray-600">مجموعات اختيارية تضيف صلاحيات إضافية للمستخدمين بغض النظر عن وظائفهم</p>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={() => setShowCreateModal(true)}
|
||||||
|
className="flex items-center gap-2 px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-all shadow-md"
|
||||||
|
>
|
||||||
|
<Plus className="h-5 w-5" />
|
||||||
|
<span className="font-semibold">إضافة مجموعة</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{loading ? (
|
||||||
|
<div className="flex justify-center p-12">
|
||||||
|
<LoadingSpinner />
|
||||||
|
</div>
|
||||||
|
) : error ? (
|
||||||
|
<div className="text-center text-red-600 p-12">{error}</div>
|
||||||
|
) : (
|
||||||
|
<div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
|
||||||
|
<div className="lg:col-span-1 space-y-4">
|
||||||
|
<h2 className="text-xl font-bold text-gray-900 mb-4">المجموعات ({groups.length})</h2>
|
||||||
|
{groups.map((g) => (
|
||||||
|
<div
|
||||||
|
key={g.id}
|
||||||
|
onClick={() => setSelectedId(g.id)}
|
||||||
|
className={`p-4 rounded-xl border-2 cursor-pointer transition-all ${
|
||||||
|
selectedId === g.id ? 'border-blue-600 bg-blue-50' : 'border-gray-200 bg-white hover:border-blue-300'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<div className="flex items-center gap-3 mb-2">
|
||||||
|
<div className={`p-2 rounded-lg ${selectedId === g.id ? 'bg-blue-600' : 'bg-blue-100'}`}>
|
||||||
|
<UsersRound className={`h-5 w-5 ${selectedId === g.id ? 'text-white' : 'text-blue-600'}`} />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h3 className="font-bold text-gray-900">{g.nameAr || g.name}</h3>
|
||||||
|
<p className="text-xs text-gray-600">{g.name}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<span className="text-sm text-gray-600">
|
||||||
|
<Users className="h-4 w-4 inline mr-1" />
|
||||||
|
{g._count?.userRoles ?? 0} مستخدم
|
||||||
|
</span>
|
||||||
|
<button
|
||||||
|
onClick={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
setSelectedId(g.id);
|
||||||
|
setShowEditModal(true);
|
||||||
|
}}
|
||||||
|
className="p-1.5 text-blue-600 hover:bg-blue-50 rounded"
|
||||||
|
>
|
||||||
|
<Edit className="h-4 w-4" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="lg:col-span-2">
|
||||||
|
{currentGroup ? (
|
||||||
|
<div className="bg-white rounded-xl shadow-lg border p-6">
|
||||||
|
<div className="flex justify-between mb-6">
|
||||||
|
<div>
|
||||||
|
<h2 className="text-2xl font-bold text-gray-900">{currentGroup.nameAr || currentGroup.name}</h2>
|
||||||
|
<p className="text-gray-600">{currentGroup.name}</p>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={() => setShowEditModal(true)}
|
||||||
|
className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
|
||||||
|
>
|
||||||
|
تعديل الصلاحيات
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<h3 className="text-lg font-bold mb-4">مصفوفة الصلاحيات</h3>
|
||||||
|
<div className="overflow-x-auto">
|
||||||
|
<table className="w-full">
|
||||||
|
<thead>
|
||||||
|
<tr className="border-b-2 border-gray-200">
|
||||||
|
<th className="px-4 py-3 text-right text-sm font-bold min-w-[200px]">الوحدة</th>
|
||||||
|
{ACTIONS.map((a) => (
|
||||||
|
<th key={a.id} className="px-4 py-3 text-center text-sm font-bold">{a.name}</th>
|
||||||
|
))}
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody className="divide-y divide-gray-200">
|
||||||
|
{MODULES.map((m) => (
|
||||||
|
<tr key={m.id} className="hover:bg-gray-50">
|
||||||
|
<td className="px-4 py-4">
|
||||||
|
<p className="font-semibold">{m.name}</p>
|
||||||
|
<p className="text-xs text-gray-600">{m.nameEn}</p>
|
||||||
|
</td>
|
||||||
|
{ACTIONS.map((a) => {
|
||||||
|
const has = permissionMatrix[m.id]?.[a.id];
|
||||||
|
return (
|
||||||
|
<td key={a.id} className="px-4 py-4 text-center">
|
||||||
|
<div
|
||||||
|
className={`w-10 h-10 rounded-lg flex items-center justify-center mx-auto ${
|
||||||
|
has ? 'bg-green-500 text-white' : 'bg-gray-200 text-gray-500'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{has ? <Check className="h-6 w-6" /> : <X className="h-6 w-6" />}
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="bg-white rounded-xl shadow-lg border p-12 text-center">
|
||||||
|
<UsersRound className="h-16 w-16 text-gray-300 mx-auto mb-4" />
|
||||||
|
<h3 className="text-xl font-bold text-gray-900 mb-2">اختر مجموعة</h3>
|
||||||
|
<p className="text-gray-600">أو أنشئ مجموعة جديدة لإضافة صلاحيات اختيارية للمستخدمين</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Modal isOpen={showCreateModal} onClose={() => setShowCreateModal(false)} title="إضافة مجموعة صلاحيات" size="md">
|
||||||
|
<form onSubmit={handleCreate} className="space-y-4">
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-gray-700 mb-1">Name *</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={createForm.name}
|
||||||
|
onChange={(e) => setCreateForm((p) => ({ ...p, name: e.target.value }))}
|
||||||
|
className="w-full px-3 py-2 border border-gray-300 rounded-lg"
|
||||||
|
placeholder="e.g. Campaign Approver"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-gray-700 mb-1">Name (Arabic)</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={createForm.nameAr}
|
||||||
|
onChange={(e) => setCreateForm((p) => ({ ...p, nameAr: e.target.value }))}
|
||||||
|
className="w-full px-3 py-2 border border-gray-300 rounded-lg"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-gray-700 mb-1">Description</label>
|
||||||
|
<textarea
|
||||||
|
value={createForm.description}
|
||||||
|
onChange={(e) => setCreateForm((p) => ({ ...p, description: e.target.value }))}
|
||||||
|
className="w-full px-3 py-2 border border-gray-300 rounded-lg"
|
||||||
|
rows={2}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="flex gap-3 justify-end pt-4">
|
||||||
|
<button type="button" onClick={() => setShowCreateModal(false)} className="px-6 py-3 border rounded-lg">
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
<button type="submit" disabled={saving} className="px-6 py-3 bg-blue-600 text-white rounded-lg disabled:opacity-50">
|
||||||
|
{saving ? 'Creating...' : 'Create'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</Modal>
|
||||||
|
|
||||||
|
<Modal
|
||||||
|
isOpen={showEditModal}
|
||||||
|
onClose={() => setShowEditModal(false)}
|
||||||
|
title={`تعديل صلاحيات: ${currentGroup?.nameAr || currentGroup?.name || ''}`}
|
||||||
|
size="2xl"
|
||||||
|
>
|
||||||
|
{currentGroup && (
|
||||||
|
<div>
|
||||||
|
<div className="overflow-x-auto mb-6">
|
||||||
|
<table className="w-full">
|
||||||
|
<thead>
|
||||||
|
<tr className="border-b-2 border-gray-200">
|
||||||
|
<th className="px-4 py-3 text-right text-sm font-bold">الوحدة</th>
|
||||||
|
{ACTIONS.map((a) => (
|
||||||
|
<th key={a.id} className="px-4 py-3 text-center text-sm font-bold">{a.name}</th>
|
||||||
|
))}
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody className="divide-y divide-gray-200">
|
||||||
|
{MODULES.map((m) => (
|
||||||
|
<tr key={m.id}>
|
||||||
|
<td className="px-4 py-4 font-semibold">{m.name}</td>
|
||||||
|
{ACTIONS.map((a) => (
|
||||||
|
<td key={a.id} className="px-4 py-4 text-center">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => handleTogglePermission(m.id, a.id)}
|
||||||
|
className={`w-10 h-10 rounded-lg flex items-center justify-center mx-auto ${
|
||||||
|
permissionMatrix[m.id]?.[a.id] ? 'bg-green-500 text-white' : 'bg-gray-200 text-gray-500'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{permissionMatrix[m.id]?.[a.id] ? <Check className="h-6 w-6" /> : <X className="h-6 w-6" />}
|
||||||
|
</button>
|
||||||
|
</td>
|
||||||
|
))}
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
<div className="flex gap-3 justify-end">
|
||||||
|
<button onClick={() => setShowEditModal(false)} className="px-6 py-3 border rounded-lg">
|
||||||
|
إلغاء
|
||||||
|
</button>
|
||||||
|
<button onClick={handleSavePermissions} disabled={saving} className="px-6 py-3 bg-blue-600 text-white rounded-lg disabled:opacity-50">
|
||||||
|
{saving ? 'جاري الحفظ...' : 'حفظ'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</Modal>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,9 +1,10 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { useState, useEffect, useCallback } from 'react';
|
import { useState, useEffect, useCallback } from 'react';
|
||||||
import { Shield, Edit, Users, Check, X } from 'lucide-react';
|
import { Shield, Edit, Users, Check, X, Plus } from 'lucide-react';
|
||||||
import { positionsAPI } from '@/lib/api/admin';
|
import { positionsAPI } from '@/lib/api/admin';
|
||||||
import type { PositionRole, PositionPermission } from '@/lib/api/admin';
|
import { departmentsAPI } from '@/lib/api/employees';
|
||||||
|
import type { PositionRole, PositionPermission, CreatePositionData } from '@/lib/api/admin';
|
||||||
import Modal from '@/components/Modal';
|
import Modal from '@/components/Modal';
|
||||||
import LoadingSpinner from '@/components/LoadingSpinner';
|
import LoadingSpinner from '@/components/LoadingSpinner';
|
||||||
|
|
||||||
@@ -59,12 +60,25 @@ function buildMatrixFromPermissions(permissions: PositionPermission[]): Record<s
|
|||||||
return matrix;
|
return matrix;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const initialCreateForm: CreatePositionData & { description?: string } = {
|
||||||
|
title: '',
|
||||||
|
titleAr: '',
|
||||||
|
code: '',
|
||||||
|
departmentId: '',
|
||||||
|
level: 5,
|
||||||
|
description: '',
|
||||||
|
};
|
||||||
|
|
||||||
export default function RolesManagement() {
|
export default function RolesManagement() {
|
||||||
const [roles, setRoles] = useState<PositionRole[]>([]);
|
const [roles, setRoles] = useState<PositionRole[]>([]);
|
||||||
|
const [departments, setDepartments] = useState<{ id: string; name: string; nameAr?: string | null }[]>([]);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const [selectedRoleId, setSelectedRoleId] = useState<string | null>(null);
|
const [selectedRoleId, setSelectedRoleId] = useState<string | null>(null);
|
||||||
const [showEditModal, setShowEditModal] = useState(false);
|
const [showEditModal, setShowEditModal] = useState(false);
|
||||||
|
const [showCreateModal, setShowCreateModal] = useState(false);
|
||||||
|
const [createForm, setCreateForm] = useState(initialCreateForm);
|
||||||
|
const [createErrors, setCreateErrors] = useState<Record<string, string>>({});
|
||||||
const [permissionMatrix, setPermissionMatrix] = useState<Record<string, Record<string, boolean>>>({});
|
const [permissionMatrix, setPermissionMatrix] = useState<Record<string, Record<string, boolean>>>({});
|
||||||
const [saving, setSaving] = useState(false);
|
const [saving, setSaving] = useState(false);
|
||||||
|
|
||||||
@@ -88,8 +102,44 @@ export default function RolesManagement() {
|
|||||||
fetchRoles();
|
fetchRoles();
|
||||||
}, [fetchRoles]);
|
}, [fetchRoles]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
departmentsAPI.getAll().then((depts) => setDepartments(depts)).catch(() => {});
|
||||||
|
}, []);
|
||||||
|
|
||||||
const currentRole = roles.find((r) => r.id === selectedRoleId);
|
const currentRole = roles.find((r) => r.id === selectedRoleId);
|
||||||
|
|
||||||
|
const handleCreateRole = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
const errs: Record<string, string> = {};
|
||||||
|
if (!createForm.title?.trim()) errs.title = 'Required';
|
||||||
|
if (!createForm.code?.trim()) errs.code = 'Required';
|
||||||
|
if (!createForm.departmentId) errs.departmentId = 'Required';
|
||||||
|
setCreateErrors(errs);
|
||||||
|
if (Object.keys(errs).length > 0) return;
|
||||||
|
|
||||||
|
setSaving(true);
|
||||||
|
try {
|
||||||
|
const position = await positionsAPI.create({
|
||||||
|
title: createForm.title.trim(),
|
||||||
|
titleAr: createForm.titleAr?.trim() || undefined,
|
||||||
|
code: createForm.code.trim(),
|
||||||
|
departmentId: createForm.departmentId,
|
||||||
|
level: createForm.level ?? 5,
|
||||||
|
description: createForm.description?.trim() || undefined,
|
||||||
|
});
|
||||||
|
setShowCreateModal(false);
|
||||||
|
setCreateForm(initialCreateForm);
|
||||||
|
setCreateErrors({});
|
||||||
|
await fetchRoles();
|
||||||
|
setSelectedRoleId(position.id);
|
||||||
|
setShowEditModal(true);
|
||||||
|
} catch (err: unknown) {
|
||||||
|
setCreateErrors({ form: err instanceof Error ? err.message : 'Failed to create role' });
|
||||||
|
} finally {
|
||||||
|
setSaving(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (currentRole) {
|
if (currentRole) {
|
||||||
setPermissionMatrix(buildMatrixFromPermissions(currentRole.permissions || []));
|
setPermissionMatrix(buildMatrixFromPermissions(currentRole.permissions || []));
|
||||||
@@ -133,6 +183,13 @@ export default function RolesManagement() {
|
|||||||
<h1 className="text-3xl font-bold text-gray-900 mb-2">الأدوار والصلاحيات</h1>
|
<h1 className="text-3xl font-bold text-gray-900 mb-2">الأدوار والصلاحيات</h1>
|
||||||
<p className="text-gray-600">إدارة أدوار المستخدمين ومصفوفة الصلاحيات</p>
|
<p className="text-gray-600">إدارة أدوار المستخدمين ومصفوفة الصلاحيات</p>
|
||||||
</div>
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={() => setShowCreateModal(true)}
|
||||||
|
className="flex items-center gap-2 px-6 py-3 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-all shadow-md hover:shadow-lg"
|
||||||
|
>
|
||||||
|
<Plus className="h-5 w-5" />
|
||||||
|
<span className="font-semibold">إضافة دور</span>
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{loading ? (
|
{loading ? (
|
||||||
@@ -269,6 +326,104 @@ export default function RolesManagement() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* Create Role Modal */}
|
||||||
|
<Modal
|
||||||
|
isOpen={showCreateModal}
|
||||||
|
onClose={() => {
|
||||||
|
setShowCreateModal(false);
|
||||||
|
setCreateForm(initialCreateForm);
|
||||||
|
setCreateErrors({});
|
||||||
|
}}
|
||||||
|
title="إضافة دور جديد"
|
||||||
|
size="md"
|
||||||
|
>
|
||||||
|
<form onSubmit={handleCreateRole} className="space-y-4">
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-gray-700 mb-1">Title (English) *</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={createForm.title}
|
||||||
|
onChange={(e) => setCreateForm((p) => ({ ...p, title: e.target.value }))}
|
||||||
|
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500"
|
||||||
|
placeholder="e.g. Sales Representative"
|
||||||
|
/>
|
||||||
|
{createErrors.title && <p className="text-red-500 text-xs mt-1">{createErrors.title}</p>}
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-gray-700 mb-1">Title (Arabic)</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={createForm.titleAr || ''}
|
||||||
|
onChange={(e) => setCreateForm((p) => ({ ...p, titleAr: e.target.value }))}
|
||||||
|
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500"
|
||||||
|
placeholder="مندوب مبيعات"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-gray-700 mb-1">Code *</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={createForm.code}
|
||||||
|
onChange={(e) => setCreateForm((p) => ({ ...p, code: e.target.value }))}
|
||||||
|
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500"
|
||||||
|
placeholder="SALES_REP"
|
||||||
|
/>
|
||||||
|
{createErrors.code && <p className="text-red-500 text-xs mt-1">{createErrors.code}</p>}
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-gray-700 mb-1">Department *</label>
|
||||||
|
<select
|
||||||
|
value={createForm.departmentId}
|
||||||
|
onChange={(e) => setCreateForm((p) => ({ ...p, departmentId: e.target.value }))}
|
||||||
|
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500"
|
||||||
|
>
|
||||||
|
<option value="">Select department</option>
|
||||||
|
{departments.map((d) => (
|
||||||
|
<option key={d.id} value={d.id}>{d.nameAr || d.name}</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
{createErrors.departmentId && <p className="text-red-500 text-xs mt-1">{createErrors.departmentId}</p>}
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-gray-700 mb-1">Level</label>
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
min={1}
|
||||||
|
value={createForm.level ?? 5}
|
||||||
|
onChange={(e) => setCreateForm((p) => ({ ...p, level: parseInt(e.target.value, 10) || 5 }))}
|
||||||
|
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-gray-700 mb-1">Description</label>
|
||||||
|
<textarea
|
||||||
|
value={createForm.description || ''}
|
||||||
|
onChange={(e) => setCreateForm((p) => ({ ...p, description: e.target.value }))}
|
||||||
|
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500"
|
||||||
|
rows={2}
|
||||||
|
placeholder="Optional description"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{createErrors.form && <p className="text-red-500 text-sm">{createErrors.form}</p>}
|
||||||
|
<div className="flex gap-3 justify-end pt-4">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setShowCreateModal(false)}
|
||||||
|
className="px-6 py-3 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 font-medium"
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={saving}
|
||||||
|
className="px-6 py-3 bg-purple-600 text-white rounded-lg hover:bg-purple-700 font-semibold disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{saving ? 'Creating...' : 'Create Role'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</Modal>
|
||||||
|
|
||||||
{/* Edit Permissions Modal */}
|
{/* Edit Permissions Modal */}
|
||||||
<Modal
|
<Modal
|
||||||
isOpen={showEditModal}
|
isOpen={showEditModal}
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ import {
|
|||||||
Shield,
|
Shield,
|
||||||
Calendar,
|
Calendar,
|
||||||
} from 'lucide-react';
|
} from 'lucide-react';
|
||||||
import { usersAPI, statsAPI, positionsAPI } from '@/lib/api/admin';
|
import { usersAPI, statsAPI, positionsAPI, userRolesAPI, permissionGroupsAPI } from '@/lib/api/admin';
|
||||||
import { employeesAPI } from '@/lib/api/employees';
|
import { employeesAPI } from '@/lib/api/employees';
|
||||||
import type { User, CreateUserData, UpdateUserData } from '@/lib/api/admin';
|
import type { User, CreateUserData, UpdateUserData } from '@/lib/api/admin';
|
||||||
import type { Employee } from '@/lib/api/employees';
|
import type { Employee } from '@/lib/api/employees';
|
||||||
@@ -567,6 +567,10 @@ function EditUserModal({
|
|||||||
employeeId: null,
|
employeeId: null,
|
||||||
isActive: true,
|
isActive: true,
|
||||||
});
|
});
|
||||||
|
const [userRoles, setUserRoles] = useState<{ id: string; role: { id: string; name: string; nameAr?: string | null } }[]>([]);
|
||||||
|
const [permissionGroups, setPermissionGroups] = useState<{ id: string; name: string; nameAr?: string | null }[]>([]);
|
||||||
|
const [assignRoleId, setAssignRoleId] = useState('');
|
||||||
|
const [rolesLoading, setRolesLoading] = useState(false);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (user) {
|
if (user) {
|
||||||
@@ -580,6 +584,41 @@ function EditUserModal({
|
|||||||
}
|
}
|
||||||
}, [user]);
|
}, [user]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (isOpen && user) {
|
||||||
|
userRolesAPI.getAll(user.id).then((r) => setUserRoles(r)).catch(() => setUserRoles([]));
|
||||||
|
permissionGroupsAPI.getAll().then((g) => setPermissionGroups(g)).catch(() => setPermissionGroups([]));
|
||||||
|
}
|
||||||
|
}, [isOpen, user?.id]);
|
||||||
|
|
||||||
|
const handleAssignRole = async () => {
|
||||||
|
if (!user || !assignRoleId) return;
|
||||||
|
setRolesLoading(true);
|
||||||
|
try {
|
||||||
|
await userRolesAPI.assign(user.id, assignRoleId);
|
||||||
|
const updated = await userRolesAPI.getAll(user.id);
|
||||||
|
setUserRoles(updated);
|
||||||
|
setAssignRoleId('');
|
||||||
|
} catch (err: unknown) {
|
||||||
|
alert(err instanceof Error ? err.message : 'فشل الإضافة');
|
||||||
|
} finally {
|
||||||
|
setRolesLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleRemoveRole = async (roleId: string) => {
|
||||||
|
if (!user) return;
|
||||||
|
setRolesLoading(true);
|
||||||
|
try {
|
||||||
|
await userRolesAPI.remove(user.id, roleId);
|
||||||
|
setUserRoles((prev) => prev.filter((ur) => ur.role.id !== roleId));
|
||||||
|
} catch (err: unknown) {
|
||||||
|
alert(err instanceof Error ? err.message : 'فشل الإزالة');
|
||||||
|
} finally {
|
||||||
|
setRolesLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const handleSubmit = async (e: React.FormEvent) => {
|
const handleSubmit = async (e: React.FormEvent) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
if (!user) return;
|
if (!user) return;
|
||||||
@@ -670,6 +709,50 @@ function EditUserModal({
|
|||||||
الحساب نشط
|
الحساب نشط
|
||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
|
<div className="border-t pt-4 mt-4">
|
||||||
|
<label className="block text-sm font-semibold text-gray-700 mb-2">مجموعات الصلاحيات الإضافية</label>
|
||||||
|
<p className="text-xs text-gray-600 mb-2">صلاحيات اختيارية تضاف إلى صلاحيات الوظيفة</p>
|
||||||
|
<div className="flex gap-2 mb-3">
|
||||||
|
<select
|
||||||
|
value={assignRoleId}
|
||||||
|
onChange={(e) => setAssignRoleId(e.target.value)}
|
||||||
|
className="flex-1 px-4 py-2 border border-gray-300 rounded-lg"
|
||||||
|
>
|
||||||
|
<option value="">إضافة مجموعة...</option>
|
||||||
|
{permissionGroups
|
||||||
|
.filter((g) => !userRoles.some((ur) => ur.role.id === g.id))
|
||||||
|
.map((g) => (
|
||||||
|
<option key={g.id} value={g.id}>{g.nameAr || g.name}</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={handleAssignRole}
|
||||||
|
disabled={!assignRoleId || rolesLoading}
|
||||||
|
className="px-4 py-2 bg-blue-100 text-blue-700 rounded-lg hover:bg-blue-200 disabled:opacity-50"
|
||||||
|
>
|
||||||
|
إضافة
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
{userRoles.map((ur) => (
|
||||||
|
<div key={ur.id} className="flex items-center justify-between py-2 px-3 bg-gray-50 rounded-lg">
|
||||||
|
<span className="font-medium">{ur.role.nameAr || ur.role.name}</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => handleRemoveRole(ur.role.id)}
|
||||||
|
disabled={rolesLoading}
|
||||||
|
className="text-red-600 hover:text-red-700 text-sm disabled:opacity-50"
|
||||||
|
>
|
||||||
|
إزالة
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
{userRoles.length === 0 && (
|
||||||
|
<p className="text-sm text-gray-500 py-2">لا توجد مجموعات إضافية</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
<div className="flex gap-3 justify-end pt-4">
|
<div className="flex gap-3 justify-end pt-4">
|
||||||
<button type="button" onClick={onClose} className="px-6 py-3 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 font-medium">
|
<button type="button" onClick={onClose} className="px-6 py-3 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 font-medium">
|
||||||
إلغاء
|
إلغاء
|
||||||
|
|||||||
@@ -902,11 +902,11 @@ function CRMContent() {
|
|||||||
<td className="px-6 py-4">
|
<td className="px-6 py-4">
|
||||||
<div>
|
<div>
|
||||||
<span className="text-sm font-semibold text-gray-900">
|
<span className="text-sm font-semibold text-gray-900">
|
||||||
{deal.estimatedValue.toLocaleString()} SAR
|
{(deal.estimatedValue ?? 0).toLocaleString()} SAR
|
||||||
</span>
|
</span>
|
||||||
{deal.actualValue && (
|
{(deal.actualValue ?? 0) > 0 && (
|
||||||
<p className="text-xs text-green-600">
|
<p className="text-xs text-green-600">
|
||||||
Actual: {deal.actualValue.toLocaleString()}
|
Actual: {(deal.actualValue ?? 0).toLocaleString()}
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
'use client'
|
'use client'
|
||||||
|
|
||||||
|
import { useState, useEffect } from 'react'
|
||||||
import ProtectedRoute from '@/components/ProtectedRoute'
|
import ProtectedRoute from '@/components/ProtectedRoute'
|
||||||
import { useAuth } from '@/contexts/AuthContext'
|
import { useAuth } from '@/contexts/AuthContext'
|
||||||
import { useLanguage } from '@/contexts/LanguageContext'
|
import { useLanguage } from '@/contexts/LanguageContext'
|
||||||
@@ -18,10 +19,20 @@ import {
|
|||||||
Bell,
|
Bell,
|
||||||
Shield
|
Shield
|
||||||
} from 'lucide-react'
|
} from 'lucide-react'
|
||||||
|
import { dashboardAPI } from '@/lib/api'
|
||||||
|
|
||||||
function DashboardContent() {
|
function DashboardContent() {
|
||||||
const { user, logout, hasPermission } = useAuth()
|
const { user, logout, hasPermission } = useAuth()
|
||||||
const { t, language, dir } = useLanguage()
|
const { t, language, dir } = useLanguage()
|
||||||
|
const [stats, setStats] = useState({ contacts: 0, activeTasks: 0, notifications: 0 })
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
dashboardAPI.getStats()
|
||||||
|
.then((res) => {
|
||||||
|
if (res.data?.data) setStats(res.data.data)
|
||||||
|
})
|
||||||
|
.catch(() => {})
|
||||||
|
}, [])
|
||||||
|
|
||||||
const allModules = [
|
const allModules = [
|
||||||
{
|
{
|
||||||
@@ -128,7 +139,7 @@ function DashboardContent() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Admin Panel Link - Only for admins */}
|
{/* Admin Panel Link - Only for admins */}
|
||||||
{(hasPermission('admin', 'view') || user?.role?.name === 'المدير العام' || user?.role?.nameEn === 'General Manager') && (
|
{hasPermission('admin', 'view') && (
|
||||||
<Link
|
<Link
|
||||||
href="/admin"
|
href="/admin"
|
||||||
className="p-2 hover:bg-red-50 rounded-lg transition-colors relative group"
|
className="p-2 hover:bg-red-50 rounded-lg transition-colors relative group"
|
||||||
@@ -144,7 +155,9 @@ function DashboardContent() {
|
|||||||
{/* Notifications */}
|
{/* Notifications */}
|
||||||
<button className="p-2 hover:bg-gray-100 rounded-lg transition-colors relative">
|
<button className="p-2 hover:bg-gray-100 rounded-lg transition-colors relative">
|
||||||
<Bell className="h-5 w-5 text-gray-600" />
|
<Bell className="h-5 w-5 text-gray-600" />
|
||||||
<span className="absolute top-1 right-1 h-2 w-2 bg-red-500 rounded-full"></span>
|
{stats.notifications > 0 && (
|
||||||
|
<span className="absolute top-1 right-1 h-2 w-2 bg-red-500 rounded-full"></span>
|
||||||
|
)}
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
{/* Settings */}
|
{/* Settings */}
|
||||||
@@ -193,7 +206,7 @@ function DashboardContent() {
|
|||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
<div>
|
<div>
|
||||||
<p className="text-sm text-gray-600">المهام النشطة</p>
|
<p className="text-sm text-gray-600">المهام النشطة</p>
|
||||||
<p className="text-3xl font-bold text-gray-900 mt-1">12</p>
|
<p className="text-3xl font-bold text-gray-900 mt-1">{stats.activeTasks}</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="bg-green-100 p-3 rounded-lg">
|
<div className="bg-green-100 p-3 rounded-lg">
|
||||||
<CheckSquare className="h-8 w-8 text-green-600" />
|
<CheckSquare className="h-8 w-8 text-green-600" />
|
||||||
@@ -205,7 +218,7 @@ function DashboardContent() {
|
|||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
<div>
|
<div>
|
||||||
<p className="text-sm text-gray-600">الإشعارات</p>
|
<p className="text-sm text-gray-600">الإشعارات</p>
|
||||||
<p className="text-3xl font-bold text-gray-900 mt-1">5</p>
|
<p className="text-3xl font-bold text-gray-900 mt-1">{stats.notifications}</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="bg-orange-100 p-3 rounded-lg">
|
<div className="bg-orange-100 p-3 rounded-lg">
|
||||||
<Bell className="h-8 w-8 text-orange-600" />
|
<Bell className="h-8 w-8 text-orange-600" />
|
||||||
@@ -217,7 +230,7 @@ function DashboardContent() {
|
|||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
<div>
|
<div>
|
||||||
<p className="text-sm text-gray-600">جهات الاتصال</p>
|
<p className="text-sm text-gray-600">جهات الاتصال</p>
|
||||||
<p className="text-3xl font-bold text-gray-900 mt-1">248</p>
|
<p className="text-3xl font-bold text-gray-900 mt-1">{stats.contacts}</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="bg-purple-100 p-3 rounded-lg">
|
<div className="bg-purple-100 p-3 rounded-lg">
|
||||||
<Users className="h-8 w-8 text-purple-600" />
|
<Users className="h-8 w-8 text-purple-600" />
|
||||||
@@ -268,37 +281,7 @@ function DashboardContent() {
|
|||||||
{/* Recent Activity */}
|
{/* Recent Activity */}
|
||||||
<div className="bg-white rounded-xl shadow-md p-6 border border-gray-100">
|
<div className="bg-white rounded-xl shadow-md p-6 border border-gray-100">
|
||||||
<h3 className="text-xl font-bold text-gray-900 mb-4">النشاط الأخير</h3>
|
<h3 className="text-xl font-bold text-gray-900 mb-4">النشاط الأخير</h3>
|
||||||
<div className="space-y-4">
|
<p className="text-gray-500 text-center py-6">لا يوجد نشاط حديث</p>
|
||||||
<div className="flex items-start gap-3 p-3 hover:bg-gray-50 rounded-lg transition-colors">
|
|
||||||
<div className="bg-blue-100 p-2 rounded-lg">
|
|
||||||
<Users className="h-5 w-5 text-blue-600" />
|
|
||||||
</div>
|
|
||||||
<div className="flex-1">
|
|
||||||
<p className="text-sm font-semibold text-gray-900">تم إضافة عميل جديد</p>
|
|
||||||
<p className="text-xs text-gray-600">منذ ساعتين</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex items-start gap-3 p-3 hover:bg-gray-50 rounded-lg transition-colors">
|
|
||||||
<div className="bg-green-100 p-2 rounded-lg">
|
|
||||||
<TrendingUp className="h-5 w-5 text-green-600" />
|
|
||||||
</div>
|
|
||||||
<div className="flex-1">
|
|
||||||
<p className="text-sm font-semibold text-gray-900">تم إغلاق صفقة جديدة</p>
|
|
||||||
<p className="text-xs text-gray-600">منذ 4 ساعات</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex items-start gap-3 p-3 hover:bg-gray-50 rounded-lg transition-colors">
|
|
||||||
<div className="bg-orange-100 p-2 rounded-lg">
|
|
||||||
<CheckSquare className="h-5 w-5 text-orange-600" />
|
|
||||||
</div>
|
|
||||||
<div className="flex-1">
|
|
||||||
<p className="text-sm font-semibold text-gray-900">تم إكمال مهمة</p>
|
|
||||||
<p className="text-xs text-gray-600">منذ يوم واحد</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</main>
|
</main>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -23,9 +23,221 @@ import {
|
|||||||
Building2,
|
Building2,
|
||||||
User,
|
User,
|
||||||
CheckCircle2,
|
CheckCircle2,
|
||||||
XCircle
|
XCircle,
|
||||||
|
Network
|
||||||
} from 'lucide-react'
|
} from 'lucide-react'
|
||||||
import { employeesAPI, Employee, CreateEmployeeData, UpdateEmployeeData, EmployeeFilters, departmentsAPI, positionsAPI } from '@/lib/api/employees'
|
import dynamic from 'next/dynamic'
|
||||||
|
import { employeesAPI, Employee, CreateEmployeeData, UpdateEmployeeData, EmployeeFilters, departmentsAPI, positionsAPI, type Department } from '@/lib/api/employees'
|
||||||
|
|
||||||
|
const OrgChart = dynamic(() => import('@/components/hr/OrgChart'), { ssr: false })
|
||||||
|
|
||||||
|
// Form fields extracted to module level to prevent focus loss on re-render
|
||||||
|
function EmployeeFormFields({
|
||||||
|
formData,
|
||||||
|
setFormData,
|
||||||
|
formErrors,
|
||||||
|
departments,
|
||||||
|
positions,
|
||||||
|
loadingDepts,
|
||||||
|
isEdit,
|
||||||
|
onCancel,
|
||||||
|
submitting,
|
||||||
|
}: {
|
||||||
|
formData: CreateEmployeeData
|
||||||
|
setFormData: React.Dispatch<React.SetStateAction<CreateEmployeeData>>
|
||||||
|
formErrors: Record<string, string>
|
||||||
|
departments: any[]
|
||||||
|
positions: any[]
|
||||||
|
loadingDepts: boolean
|
||||||
|
isEdit: boolean
|
||||||
|
onCancel: () => void
|
||||||
|
submitting: boolean
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<div className="space-y-4 max-h-[60vh] overflow-y-auto pr-2">
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-gray-700 mb-1">
|
||||||
|
First Name <span className="text-red-500">*</span>
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={formData.firstName}
|
||||||
|
onChange={(e) => setFormData((prev) => ({ ...prev, firstName: e.target.value }))}
|
||||||
|
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-red-500"
|
||||||
|
/>
|
||||||
|
{formErrors.firstName && <p className="text-red-500 text-xs mt-1">{formErrors.firstName}</p>}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-gray-700 mb-1">
|
||||||
|
Last Name <span className="text-red-500">*</span>
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={formData.lastName}
|
||||||
|
onChange={(e) => setFormData((prev) => ({ ...prev, lastName: e.target.value }))}
|
||||||
|
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-red-500"
|
||||||
|
/>
|
||||||
|
{formErrors.lastName && <p className="text-red-500 text-xs mt-1">{formErrors.lastName}</p>}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-gray-700 mb-1">
|
||||||
|
Email <span className="text-red-500">*</span>
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="email"
|
||||||
|
value={formData.email}
|
||||||
|
onChange={(e) => setFormData((prev) => ({ ...prev, email: e.target.value }))}
|
||||||
|
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-red-500"
|
||||||
|
/>
|
||||||
|
{formErrors.email && <p className="text-red-500 text-xs mt-1">{formErrors.email}</p>}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-gray-700 mb-1">
|
||||||
|
Mobile <span className="text-red-500">*</span>
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="tel"
|
||||||
|
value={formData.mobile}
|
||||||
|
onChange={(e) => setFormData((prev) => ({ ...prev, mobile: e.target.value }))}
|
||||||
|
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-red-500"
|
||||||
|
/>
|
||||||
|
{formErrors.mobile && <p className="text-red-500 text-xs mt-1">{formErrors.mobile}</p>}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-gray-700 mb-1">
|
||||||
|
Department <span className="text-red-500">*</span>
|
||||||
|
</label>
|
||||||
|
<select
|
||||||
|
value={formData.departmentId}
|
||||||
|
onChange={(e) => setFormData((prev) => ({ ...prev, departmentId: e.target.value }))}
|
||||||
|
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-red-500"
|
||||||
|
disabled={loadingDepts}
|
||||||
|
>
|
||||||
|
<option value="">Select Department</option>
|
||||||
|
{departments.map((dept) => (
|
||||||
|
<option key={dept.id} value={dept.id}>{dept.nameAr || dept.name}</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
{formErrors.departmentId && <p className="text-red-500 text-xs mt-1">{formErrors.departmentId}</p>}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-gray-700 mb-1">
|
||||||
|
Position <span className="text-red-500">*</span>
|
||||||
|
</label>
|
||||||
|
<select
|
||||||
|
value={formData.positionId}
|
||||||
|
onChange={(e) => setFormData((prev) => ({ ...prev, positionId: e.target.value }))}
|
||||||
|
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-red-500"
|
||||||
|
disabled={loadingDepts}
|
||||||
|
>
|
||||||
|
<option value="">Select Position</option>
|
||||||
|
{positions.map((pos) => (
|
||||||
|
<option key={pos.id} value={pos.id}>{pos.titleAr || pos.title}</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
{formErrors.positionId && <p className="text-red-500 text-xs mt-1">{formErrors.positionId}</p>}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-gray-700 mb-1">
|
||||||
|
Employment Type <span className="text-red-500">*</span>
|
||||||
|
</label>
|
||||||
|
<select
|
||||||
|
value={formData.employmentType}
|
||||||
|
onChange={(e) => setFormData((prev) => ({ ...prev, employmentType: e.target.value }))}
|
||||||
|
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-red-500"
|
||||||
|
>
|
||||||
|
<option value="FULL_TIME">Full Time - دوام كامل</option>
|
||||||
|
<option value="PART_TIME">Part Time - دوام جزئي</option>
|
||||||
|
<option value="CONTRACT">Contract - عقد</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-gray-700 mb-1">
|
||||||
|
Contract Type
|
||||||
|
</label>
|
||||||
|
<select
|
||||||
|
value={formData.contractType || ''}
|
||||||
|
onChange={(e) => setFormData((prev) => ({ ...prev, contractType: e.target.value }))}
|
||||||
|
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-red-500"
|
||||||
|
>
|
||||||
|
<option value="UNLIMITED">Unlimited - غير محدود</option>
|
||||||
|
<option value="FIXED">Fixed - محدد</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-gray-700 mb-1">
|
||||||
|
Hire Date <span className="text-red-500">*</span>
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="date"
|
||||||
|
value={formData.hireDate}
|
||||||
|
onChange={(e) => setFormData((prev) => ({ ...prev, hireDate: e.target.value }))}
|
||||||
|
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-red-500"
|
||||||
|
/>
|
||||||
|
{formErrors.hireDate && <p className="text-red-500 text-xs mt-1">{formErrors.hireDate}</p>}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-gray-700 mb-1">
|
||||||
|
Base Salary (SAR) <span className="text-red-500">*</span>
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
min="0"
|
||||||
|
value={formData.baseSalary}
|
||||||
|
onChange={(e) => setFormData((prev) => ({ ...prev, baseSalary: parseFloat(e.target.value) || 0 }))}
|
||||||
|
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-red-500"
|
||||||
|
/>
|
||||||
|
{formErrors.baseSalary && <p className="text-red-500 text-xs mt-1">{formErrors.baseSalary}</p>}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center justify-end gap-3 pt-4 border-t">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={onCancel}
|
||||||
|
className="px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors"
|
||||||
|
disabled={submitting}
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
className="flex items-center gap-2 px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
|
||||||
|
disabled={submitting}
|
||||||
|
>
|
||||||
|
{submitting ? (
|
||||||
|
<>
|
||||||
|
<Loader2 className="h-4 w-4 animate-spin" />
|
||||||
|
{isEdit ? 'Updating...' : 'Creating...'}
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
{isEdit ? 'Update Employee' : 'Create Employee'}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
function HRContent() {
|
function HRContent() {
|
||||||
// State Management
|
// State Management
|
||||||
@@ -79,6 +291,42 @@ function HRContent() {
|
|||||||
const [positions, setPositions] = useState<any[]>([])
|
const [positions, setPositions] = useState<any[]>([])
|
||||||
const [loadingDepts, setLoadingDepts] = useState(false)
|
const [loadingDepts, setLoadingDepts] = useState(false)
|
||||||
|
|
||||||
|
// Tabs: employees | departments | orgchart
|
||||||
|
const [activeTab, setActiveTab] = useState<'employees' | 'departments' | 'orgchart'>('employees')
|
||||||
|
const [hierarchy, setHierarchy] = useState<Department[]>([])
|
||||||
|
const [loadingHierarchy, setLoadingHierarchy] = useState(false)
|
||||||
|
|
||||||
|
// Department CRUD
|
||||||
|
const [showDeptModal, setShowDeptModal] = useState(false)
|
||||||
|
const [editingDept, setEditingDept] = useState<Department | null>(null)
|
||||||
|
const [deptFormData, setDeptFormData] = useState({ name: '', nameAr: '', code: '', parentId: '' as string, description: '' })
|
||||||
|
const [deptFormErrors, setDeptFormErrors] = useState<Record<string, string>>({})
|
||||||
|
const [deptDeleteConfirm, setDeptDeleteConfirm] = useState<string | null>(null)
|
||||||
|
|
||||||
|
const fetchDepartments = useCallback(async () => {
|
||||||
|
setLoadingDepts(true)
|
||||||
|
try {
|
||||||
|
const depts = await departmentsAPI.getAll()
|
||||||
|
setDepartments(depts)
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Failed to load departments:', err)
|
||||||
|
} finally {
|
||||||
|
setLoadingDepts(false)
|
||||||
|
}
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
const fetchHierarchy = useCallback(async () => {
|
||||||
|
setLoadingHierarchy(true)
|
||||||
|
try {
|
||||||
|
const tree = await departmentsAPI.getHierarchy()
|
||||||
|
setHierarchy(tree)
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Failed to load hierarchy:', err)
|
||||||
|
} finally {
|
||||||
|
setLoadingHierarchy(false)
|
||||||
|
}
|
||||||
|
}, [])
|
||||||
|
|
||||||
// Fetch Departments & Positions
|
// Fetch Departments & Positions
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const fetchData = async () => {
|
const fetchData = async () => {
|
||||||
@@ -99,6 +347,11 @@ function HRContent() {
|
|||||||
fetchData()
|
fetchData()
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (activeTab === 'departments') fetchDepartments()
|
||||||
|
if (activeTab === 'orgchart') fetchHierarchy()
|
||||||
|
}, [activeTab, fetchDepartments, fetchHierarchy])
|
||||||
|
|
||||||
// Fetch Employees (with debouncing for search)
|
// Fetch Employees (with debouncing for search)
|
||||||
const fetchEmployees = useCallback(async () => {
|
const fetchEmployees = useCallback(async () => {
|
||||||
setLoading(true)
|
setLoading(true)
|
||||||
@@ -290,7 +543,7 @@ function HRContent() {
|
|||||||
departmentId: employee.departmentId,
|
departmentId: employee.departmentId,
|
||||||
positionId: employee.positionId,
|
positionId: employee.positionId,
|
||||||
reportingToId: employee.reportingToId,
|
reportingToId: employee.reportingToId,
|
||||||
baseSalary: employee.baseSalary
|
baseSalary: employee.baseSalary ?? (employee as any).basicSalary ?? 0
|
||||||
})
|
})
|
||||||
setShowEditModal(true)
|
setShowEditModal(true)
|
||||||
}
|
}
|
||||||
@@ -300,198 +553,79 @@ function HRContent() {
|
|||||||
setShowDeleteDialog(true)
|
setShowDeleteDialog(true)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Calculate stats
|
// Department CRUD
|
||||||
|
const openDeptModal = (dept?: Department) => {
|
||||||
|
if (dept) {
|
||||||
|
setEditingDept(dept)
|
||||||
|
setDeptFormData({
|
||||||
|
name: dept.name,
|
||||||
|
nameAr: dept.nameAr || '',
|
||||||
|
code: dept.code,
|
||||||
|
parentId: dept.parentId || '',
|
||||||
|
description: dept.description || ''
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
setEditingDept(null)
|
||||||
|
setDeptFormData({ name: '', nameAr: '', code: '', parentId: '', description: '' })
|
||||||
|
}
|
||||||
|
setDeptFormErrors({})
|
||||||
|
setShowDeptModal(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
const validateDeptForm = () => {
|
||||||
|
const err: Record<string, string> = {}
|
||||||
|
if (!deptFormData.name?.trim()) err.name = 'Name is required'
|
||||||
|
if (!deptFormData.code?.trim()) err.code = 'Code is required'
|
||||||
|
setDeptFormErrors(err)
|
||||||
|
return Object.keys(err).length === 0
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleSaveDept = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault()
|
||||||
|
if (!validateDeptForm()) return
|
||||||
|
try {
|
||||||
|
if (editingDept) {
|
||||||
|
await departmentsAPI.update(editingDept.id, {
|
||||||
|
...deptFormData,
|
||||||
|
parentId: deptFormData.parentId || null
|
||||||
|
})
|
||||||
|
toast.success('Department updated')
|
||||||
|
} else {
|
||||||
|
await departmentsAPI.create({
|
||||||
|
...deptFormData,
|
||||||
|
parentId: deptFormData.parentId || undefined
|
||||||
|
})
|
||||||
|
toast.success('Department created')
|
||||||
|
}
|
||||||
|
setShowDeptModal(false)
|
||||||
|
fetchDepartments()
|
||||||
|
if (activeTab === 'orgchart') fetchHierarchy()
|
||||||
|
setDepartments(await departmentsAPI.getAll())
|
||||||
|
} catch (err: any) {
|
||||||
|
toast.error(err.response?.data?.message || 'Failed to save department')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleDeleteDept = async (id: string) => {
|
||||||
|
try {
|
||||||
|
await departmentsAPI.delete(id)
|
||||||
|
toast.success('Department deleted')
|
||||||
|
setDeptDeleteConfirm(null)
|
||||||
|
fetchDepartments()
|
||||||
|
if (activeTab === 'orgchart') fetchHierarchy()
|
||||||
|
setDepartments(await departmentsAPI.getAll())
|
||||||
|
} catch (err: any) {
|
||||||
|
toast.error(err.response?.data?.message || 'Failed to delete department')
|
||||||
|
setDeptDeleteConfirm(null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Calculate stats (coerce to number - API may return Decimal as string/object)
|
||||||
const activeEmployees = employees.filter(e => e.status === 'ACTIVE').length
|
const activeEmployees = employees.filter(e => e.status === 'ACTIVE').length
|
||||||
const totalSalary = employees.reduce((sum, e) => sum + e.baseSalary, 0)
|
const totalSalary = employees.reduce((sum, e) => {
|
||||||
|
const sal = e.baseSalary ?? (e as any).basicSalary ?? 0
|
||||||
// Render Form Fields Component
|
return sum + Number(sal)
|
||||||
const FormFields = ({ isEdit = false }: { isEdit?: boolean }) => (
|
}, 0)
|
||||||
<div className="space-y-4 max-h-[60vh] overflow-y-auto pr-2">
|
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
|
||||||
<div>
|
|
||||||
<label className="block text-sm font-medium text-gray-700 mb-1">
|
|
||||||
First Name <span className="text-red-500">*</span>
|
|
||||||
</label>
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
value={formData.firstName}
|
|
||||||
onChange={(e) => setFormData({ ...formData, firstName: e.target.value })}
|
|
||||||
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-red-500"
|
|
||||||
/>
|
|
||||||
{formErrors.firstName && <p className="text-red-500 text-xs mt-1">{formErrors.firstName}</p>}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<label className="block text-sm font-medium text-gray-700 mb-1">
|
|
||||||
Last Name <span className="text-red-500">*</span>
|
|
||||||
</label>
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
value={formData.lastName}
|
|
||||||
onChange={(e) => setFormData({ ...formData, lastName: e.target.value })}
|
|
||||||
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-red-500"
|
|
||||||
/>
|
|
||||||
{formErrors.lastName && <p className="text-red-500 text-xs mt-1">{formErrors.lastName}</p>}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
|
||||||
<div>
|
|
||||||
<label className="block text-sm font-medium text-gray-700 mb-1">
|
|
||||||
Email <span className="text-red-500">*</span>
|
|
||||||
</label>
|
|
||||||
<input
|
|
||||||
type="email"
|
|
||||||
value={formData.email}
|
|
||||||
onChange={(e) => setFormData({ ...formData, email: e.target.value })}
|
|
||||||
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-red-500"
|
|
||||||
/>
|
|
||||||
{formErrors.email && <p className="text-red-500 text-xs mt-1">{formErrors.email}</p>}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<label className="block text-sm font-medium text-gray-700 mb-1">
|
|
||||||
Mobile <span className="text-red-500">*</span>
|
|
||||||
</label>
|
|
||||||
<input
|
|
||||||
type="tel"
|
|
||||||
value={formData.mobile}
|
|
||||||
onChange={(e) => setFormData({ ...formData, mobile: e.target.value })}
|
|
||||||
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-red-500"
|
|
||||||
/>
|
|
||||||
{formErrors.mobile && <p className="text-red-500 text-xs mt-1">{formErrors.mobile}</p>}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
|
||||||
<div>
|
|
||||||
<label className="block text-sm font-medium text-gray-700 mb-1">
|
|
||||||
Department <span className="text-red-500">*</span>
|
|
||||||
</label>
|
|
||||||
<select
|
|
||||||
value={formData.departmentId}
|
|
||||||
onChange={(e) => setFormData({ ...formData, departmentId: e.target.value })}
|
|
||||||
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-red-500"
|
|
||||||
disabled={loadingDepts}
|
|
||||||
>
|
|
||||||
<option value="">Select Department</option>
|
|
||||||
{departments.map(dept => (
|
|
||||||
<option key={dept.id} value={dept.id}>{dept.nameAr || dept.name}</option>
|
|
||||||
))}
|
|
||||||
</select>
|
|
||||||
{formErrors.departmentId && <p className="text-red-500 text-xs mt-1">{formErrors.departmentId}</p>}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<label className="block text-sm font-medium text-gray-700 mb-1">
|
|
||||||
Position <span className="text-red-500">*</span>
|
|
||||||
</label>
|
|
||||||
<select
|
|
||||||
value={formData.positionId}
|
|
||||||
onChange={(e) => setFormData({ ...formData, positionId: e.target.value })}
|
|
||||||
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-red-500"
|
|
||||||
disabled={loadingDepts}
|
|
||||||
>
|
|
||||||
<option value="">Select Position</option>
|
|
||||||
{positions.map(pos => (
|
|
||||||
<option key={pos.id} value={pos.id}>{pos.titleAr || pos.title}</option>
|
|
||||||
))}
|
|
||||||
</select>
|
|
||||||
{formErrors.positionId && <p className="text-red-500 text-xs mt-1">{formErrors.positionId}</p>}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
|
||||||
<div>
|
|
||||||
<label className="block text-sm font-medium text-gray-700 mb-1">
|
|
||||||
Employment Type <span className="text-red-500">*</span>
|
|
||||||
</label>
|
|
||||||
<select
|
|
||||||
value={formData.employmentType}
|
|
||||||
onChange={(e) => setFormData({ ...formData, employmentType: e.target.value })}
|
|
||||||
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-red-500"
|
|
||||||
>
|
|
||||||
<option value="FULL_TIME">Full Time - دوام كامل</option>
|
|
||||||
<option value="PART_TIME">Part Time - دوام جزئي</option>
|
|
||||||
<option value="CONTRACT">Contract - عقد</option>
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<label className="block text-sm font-medium text-gray-700 mb-1">
|
|
||||||
Contract Type
|
|
||||||
</label>
|
|
||||||
<select
|
|
||||||
value={formData.contractType || ''}
|
|
||||||
onChange={(e) => setFormData({ ...formData, contractType: e.target.value })}
|
|
||||||
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-red-500"
|
|
||||||
>
|
|
||||||
<option value="UNLIMITED">Unlimited - غير محدود</option>
|
|
||||||
<option value="FIXED">Fixed - محدد</option>
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
|
||||||
<div>
|
|
||||||
<label className="block text-sm font-medium text-gray-700 mb-1">
|
|
||||||
Hire Date <span className="text-red-500">*</span>
|
|
||||||
</label>
|
|
||||||
<input
|
|
||||||
type="date"
|
|
||||||
value={formData.hireDate}
|
|
||||||
onChange={(e) => setFormData({ ...formData, hireDate: e.target.value })}
|
|
||||||
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-red-500"
|
|
||||||
/>
|
|
||||||
{formErrors.hireDate && <p className="text-red-500 text-xs mt-1">{formErrors.hireDate}</p>}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<label className="block text-sm font-medium text-gray-700 mb-1">
|
|
||||||
Base Salary (SAR) <span className="text-red-500">*</span>
|
|
||||||
</label>
|
|
||||||
<input
|
|
||||||
type="number"
|
|
||||||
min="0"
|
|
||||||
value={formData.baseSalary}
|
|
||||||
onChange={(e) => setFormData({ ...formData, baseSalary: parseFloat(e.target.value) })}
|
|
||||||
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-red-500"
|
|
||||||
/>
|
|
||||||
{formErrors.baseSalary && <p className="text-red-500 text-xs mt-1">{formErrors.baseSalary}</p>}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex items-center justify-end gap-3 pt-4 border-t">
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => {
|
|
||||||
isEdit ? setShowEditModal(false) : setShowCreateModal(false)
|
|
||||||
resetForm()
|
|
||||||
}}
|
|
||||||
className="px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors"
|
|
||||||
disabled={submitting}
|
|
||||||
>
|
|
||||||
Cancel
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
type="submit"
|
|
||||||
className="flex items-center gap-2 px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
|
|
||||||
disabled={submitting}
|
|
||||||
>
|
|
||||||
{submitting ? (
|
|
||||||
<>
|
|
||||||
<Loader2 className="h-4 w-4 animate-spin" />
|
|
||||||
{isEdit ? 'Updating...' : 'Creating...'}
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
{isEdit ? 'Update Employee' : 'Create Employee'}
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen bg-gray-50">
|
<div className="min-h-screen bg-gray-50">
|
||||||
@@ -518,19 +652,77 @@ function HRContent() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
<button
|
{activeTab === 'employees' && (
|
||||||
onClick={() => {
|
<button
|
||||||
resetForm()
|
onClick={() => {
|
||||||
setShowCreateModal(true)
|
resetForm()
|
||||||
}}
|
setShowCreateModal(true)
|
||||||
className="flex items-center gap-2 px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors"
|
}}
|
||||||
>
|
className="flex items-center gap-2 px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors"
|
||||||
<Plus className="h-4 w-4" />
|
>
|
||||||
Add Employee
|
<Plus className="h-4 w-4" />
|
||||||
</button>
|
Add Employee
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
{activeTab === 'departments' && (
|
||||||
|
<button
|
||||||
|
onClick={() => openDeptModal()}
|
||||||
|
className="flex items-center gap-2 px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors"
|
||||||
|
>
|
||||||
|
<Plus className="h-4 w-4" />
|
||||||
|
Add Department
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Tabs */}
|
||||||
|
<div className="border-b border-gray-200 bg-white">
|
||||||
|
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
|
||||||
|
<nav className="flex gap-4">
|
||||||
|
<button
|
||||||
|
onClick={() => setActiveTab('employees')}
|
||||||
|
className={`py-4 px-2 border-b-2 font-medium text-sm transition-colors ${
|
||||||
|
activeTab === 'employees'
|
||||||
|
? 'border-red-600 text-red-600'
|
||||||
|
: 'border-transparent text-gray-500 hover:text-gray-700'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<span className="flex items-center gap-2">
|
||||||
|
<Users className="h-4 w-4" />
|
||||||
|
الموظفون / Employees
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => setActiveTab('departments')}
|
||||||
|
className={`py-4 px-2 border-b-2 font-medium text-sm transition-colors ${
|
||||||
|
activeTab === 'departments'
|
||||||
|
? 'border-red-600 text-red-600'
|
||||||
|
: 'border-transparent text-gray-500 hover:text-gray-700'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<span className="flex items-center gap-2">
|
||||||
|
<Building2 className="h-4 w-4" />
|
||||||
|
الأقسام / Departments
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => setActiveTab('orgchart')}
|
||||||
|
className={`py-4 px-2 border-b-2 font-medium text-sm transition-colors ${
|
||||||
|
activeTab === 'orgchart'
|
||||||
|
? 'border-red-600 text-red-600'
|
||||||
|
: 'border-transparent text-gray-500 hover:text-gray-700'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<span className="flex items-center gap-2">
|
||||||
|
<Network className="h-4 w-4" />
|
||||||
|
الهيكل التنظيمي / Org Chart
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
</nav>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
<main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
|
<main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
|
||||||
@@ -577,7 +769,9 @@ function HRContent() {
|
|||||||
<div>
|
<div>
|
||||||
<p className="text-sm text-gray-600">Total Salary</p>
|
<p className="text-sm text-gray-600">Total Salary</p>
|
||||||
<p className="text-3xl font-bold text-gray-900 mt-1">
|
<p className="text-3xl font-bold text-gray-900 mt-1">
|
||||||
{(totalSalary / 1000).toFixed(0)}K
|
{totalSalary >= 1000
|
||||||
|
? `${(totalSalary / 1000).toFixed(1)}K`
|
||||||
|
: totalSalary.toLocaleString()}
|
||||||
</p>
|
</p>
|
||||||
<p className="text-xs text-gray-600 mt-1">SAR</p>
|
<p className="text-xs text-gray-600 mt-1">SAR</p>
|
||||||
</div>
|
</div>
|
||||||
@@ -588,6 +782,9 @@ function HRContent() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Employees Tab */}
|
||||||
|
{activeTab === 'employees' && (
|
||||||
|
<>
|
||||||
{/* Filters and Search */}
|
{/* Filters and Search */}
|
||||||
<div className="bg-white rounded-xl shadow-sm p-6 border border-gray-200 mb-6">
|
<div className="bg-white rounded-xl shadow-sm p-6 border border-gray-200 mb-6">
|
||||||
<div className="flex flex-col md:flex-row gap-4">
|
<div className="flex flex-col md:flex-row gap-4">
|
||||||
@@ -710,7 +907,7 @@ function HRContent() {
|
|||||||
</td>
|
</td>
|
||||||
<td className="px-6 py-4">
|
<td className="px-6 py-4">
|
||||||
<span className="text-sm font-semibold text-gray-900">
|
<span className="text-sm font-semibold text-gray-900">
|
||||||
{employee.baseSalary.toLocaleString()} SAR
|
{Number(employee.baseSalary ?? (employee as any).basicSalary ?? 0).toLocaleString()} SAR
|
||||||
</span>
|
</span>
|
||||||
</td>
|
</td>
|
||||||
<td className="px-6 py-4">
|
<td className="px-6 py-4">
|
||||||
@@ -791,6 +988,79 @@ function HRContent() {
|
|||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Departments Tab */}
|
||||||
|
{activeTab === 'departments' && (
|
||||||
|
<div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
|
||||||
|
{loadingDepts ? (
|
||||||
|
<div className="p-12"><LoadingSpinner size="lg" message="Loading departments..." /></div>
|
||||||
|
) : departments.length === 0 ? (
|
||||||
|
<div className="p-12 text-center">
|
||||||
|
<Building2 className="h-12 w-12 text-gray-400 mx-auto mb-4" />
|
||||||
|
<p className="text-gray-600 mb-4">No departments yet. Add your first department.</p>
|
||||||
|
<button onClick={() => openDeptModal()} className="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700">
|
||||||
|
Add Department
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="overflow-x-auto">
|
||||||
|
<table className="w-full">
|
||||||
|
<thead className="bg-gray-50 border-b border-gray-200">
|
||||||
|
<tr>
|
||||||
|
<th className="px-6 py-4 text-right text-xs font-semibold text-gray-700 uppercase">Name</th>
|
||||||
|
<th className="px-6 py-4 text-right text-xs font-semibold text-gray-700 uppercase">Code</th>
|
||||||
|
<th className="px-6 py-4 text-right text-xs font-semibold text-gray-700 uppercase">Parent</th>
|
||||||
|
<th className="px-6 py-4 text-right text-xs font-semibold text-gray-700 uppercase">Employees</th>
|
||||||
|
<th className="px-6 py-4 text-right text-xs font-semibold text-gray-700 uppercase">Actions</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody className="divide-y divide-gray-200">
|
||||||
|
{departments.map((dept) => (
|
||||||
|
<tr key={dept.id} className="hover:bg-gray-50">
|
||||||
|
<td className="px-6 py-4">
|
||||||
|
<span className="font-semibold text-gray-900">{dept.nameAr || dept.name}</span>
|
||||||
|
</td>
|
||||||
|
<td className="px-6 py-4 text-sm text-gray-600">{dept.code}</td>
|
||||||
|
<td className="px-6 py-4 text-sm text-gray-600">{dept.parent?.nameAr || dept.parent?.name || '-'}</td>
|
||||||
|
<td className="px-6 py-4 text-sm">{dept._count?.employees ?? 0}</td>
|
||||||
|
<td className="px-6 py-4">
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<button onClick={() => openDeptModal(dept)} className="p-2 hover:bg-blue-50 text-blue-600 rounded-lg" title="Edit">
|
||||||
|
<Edit className="h-4 w-4" />
|
||||||
|
</button>
|
||||||
|
{deptDeleteConfirm === dept.id ? (
|
||||||
|
<span className="flex gap-1">
|
||||||
|
<button onClick={() => handleDeleteDept(dept.id)} className="px-2 py-1 text-xs bg-red-600 text-white rounded">Confirm</button>
|
||||||
|
<button onClick={() => setDeptDeleteConfirm(null)} className="px-2 py-1 text-xs border rounded">Cancel</button>
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
<button onClick={() => setDeptDeleteConfirm(dept.id)} className="p-2 hover:bg-red-50 text-red-600 rounded-lg" title="Delete">
|
||||||
|
<Trash2 className="h-4 w-4" />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Org Chart Tab */}
|
||||||
|
{activeTab === 'orgchart' && (
|
||||||
|
<div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
|
||||||
|
{loadingHierarchy ? (
|
||||||
|
<div className="p-12"><LoadingSpinner size="lg" message="Loading org chart..." /></div>
|
||||||
|
) : (
|
||||||
|
<OrgChart hierarchy={hierarchy} />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</main>
|
</main>
|
||||||
|
|
||||||
{/* Create Modal */}
|
{/* Create Modal */}
|
||||||
@@ -804,7 +1074,93 @@ function HRContent() {
|
|||||||
size="xl"
|
size="xl"
|
||||||
>
|
>
|
||||||
<form onSubmit={handleCreate}>
|
<form onSubmit={handleCreate}>
|
||||||
<FormFields />
|
<EmployeeFormFields
|
||||||
|
formData={formData}
|
||||||
|
setFormData={setFormData}
|
||||||
|
formErrors={formErrors}
|
||||||
|
departments={departments}
|
||||||
|
positions={positions}
|
||||||
|
loadingDepts={loadingDepts}
|
||||||
|
isEdit={false}
|
||||||
|
onCancel={() => {
|
||||||
|
setShowCreateModal(false)
|
||||||
|
resetForm()
|
||||||
|
}}
|
||||||
|
submitting={submitting}
|
||||||
|
/>
|
||||||
|
</form>
|
||||||
|
</Modal>
|
||||||
|
|
||||||
|
{/* Department Modal */}
|
||||||
|
<Modal
|
||||||
|
isOpen={showDeptModal}
|
||||||
|
onClose={() => { setShowDeptModal(false); setEditingDept(null) }}
|
||||||
|
title={editingDept ? 'Edit Department' : 'Add Department'}
|
||||||
|
>
|
||||||
|
<form onSubmit={handleSaveDept} className="space-y-4">
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-gray-700 mb-1">Name (EN) *</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={deptFormData.name}
|
||||||
|
onChange={(e) => setDeptFormData((p) => ({ ...p, name: e.target.value }))}
|
||||||
|
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-red-500"
|
||||||
|
/>
|
||||||
|
{deptFormErrors.name && <p className="text-red-500 text-xs mt-1">{deptFormErrors.name}</p>}
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-gray-700 mb-1">Name (AR)</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={deptFormData.nameAr}
|
||||||
|
onChange={(e) => setDeptFormData((p) => ({ ...p, nameAr: e.target.value }))}
|
||||||
|
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-red-500"
|
||||||
|
dir="rtl"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-gray-700 mb-1">Code *</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={deptFormData.code}
|
||||||
|
onChange={(e) => setDeptFormData((p) => ({ ...p, code: e.target.value.toUpperCase() }))}
|
||||||
|
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-red-500"
|
||||||
|
placeholder="e.g. HR, IT, SALES"
|
||||||
|
/>
|
||||||
|
{deptFormErrors.code && <p className="text-red-500 text-xs mt-1">{deptFormErrors.code}</p>}
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-gray-700 mb-1">Parent Department</label>
|
||||||
|
<select
|
||||||
|
value={deptFormData.parentId}
|
||||||
|
onChange={(e) => setDeptFormData((p) => ({ ...p, parentId: e.target.value }))}
|
||||||
|
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-red-500"
|
||||||
|
>
|
||||||
|
<option value="">— None (Root) —</option>
|
||||||
|
{departments
|
||||||
|
.filter((d) => !editingDept || d.id !== editingDept.id)
|
||||||
|
.map((d) => (
|
||||||
|
<option key={d.id} value={d.id}>{d.nameAr || d.name} ({d.code})</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-gray-700 mb-1">Description</label>
|
||||||
|
<textarea
|
||||||
|
value={deptFormData.description}
|
||||||
|
onChange={(e) => setDeptFormData((p) => ({ ...p, description: e.target.value }))}
|
||||||
|
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-red-500"
|
||||||
|
rows={2}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="flex justify-end gap-2 pt-4">
|
||||||
|
<button type="button" onClick={() => setShowDeptModal(false)} className="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50">
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
<button type="submit" className="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700">
|
||||||
|
{editingDept ? 'Update' : 'Create'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
</form>
|
</form>
|
||||||
</Modal>
|
</Modal>
|
||||||
|
|
||||||
@@ -819,7 +1175,20 @@ function HRContent() {
|
|||||||
size="xl"
|
size="xl"
|
||||||
>
|
>
|
||||||
<form onSubmit={handleEdit}>
|
<form onSubmit={handleEdit}>
|
||||||
<FormFields isEdit />
|
<EmployeeFormFields
|
||||||
|
formData={formData}
|
||||||
|
setFormData={setFormData}
|
||||||
|
formErrors={formErrors}
|
||||||
|
departments={departments}
|
||||||
|
positions={positions}
|
||||||
|
loadingDepts={loadingDepts}
|
||||||
|
isEdit
|
||||||
|
onCancel={() => {
|
||||||
|
setShowEditModal(false)
|
||||||
|
resetForm()
|
||||||
|
}}
|
||||||
|
submitting={submitting}
|
||||||
|
/>
|
||||||
</form>
|
</form>
|
||||||
</Modal>
|
</Modal>
|
||||||
|
|
||||||
|
|||||||
4
frontend/src/app/icon.svg
Normal file
4
frontend/src/app/icon.svg
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32">
|
||||||
|
<rect width="32" height="32" rx="4" fill="#2563eb"/>
|
||||||
|
<text x="16" y="22" text-anchor="middle" fill="white" font-size="14" font-family="sans-serif" font-weight="bold">Z</text>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 247 B |
@@ -110,13 +110,11 @@ export default function LoginPage() {
|
|||||||
</button>
|
</button>
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
{/* Demo Credentials */}
|
{/* System Administrator */}
|
||||||
<div className="mt-6 p-4 bg-blue-50 rounded-lg border border-blue-200">
|
<div className="mt-6 p-4 bg-blue-50 rounded-lg border border-blue-200">
|
||||||
<h3 className="text-sm font-semibold text-blue-900 mb-2">الحسابات التجريبية:</h3>
|
<h3 className="text-sm font-semibold text-blue-900 mb-2">مدير النظام:</h3>
|
||||||
<div className="text-sm text-blue-800 space-y-1">
|
<div className="text-sm text-blue-800">
|
||||||
<p>• <strong>المدير العام:</strong> gm@atmata.com / Admin@123</p>
|
<p><strong>admin@system.local</strong> / Admin@123</p>
|
||||||
<p>• <strong>مدير المبيعات:</strong> sales.manager@atmata.com / Admin@123</p>
|
|
||||||
<p>• <strong>مندوب مبيعات:</strong> sales.rep@atmata.com / Admin@123</p>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -628,9 +628,9 @@ function MarketingContent() {
|
|||||||
<span className="text-sm font-semibold text-gray-900">
|
<span className="text-sm font-semibold text-gray-900">
|
||||||
{(campaign.budget || 0).toLocaleString()} SAR
|
{(campaign.budget || 0).toLocaleString()} SAR
|
||||||
</span>
|
</span>
|
||||||
{campaign.actualCost && (
|
{(campaign.actualCost ?? 0) > 0 && (
|
||||||
<p className="text-xs text-gray-600">
|
<p className="text-xs text-gray-600">
|
||||||
Spent: {campaign.actualCost.toLocaleString()}
|
Spent: {(campaign.actualCost ?? 0).toLocaleString()}
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
116
frontend/src/components/hr/OrgChart.tsx
Normal file
116
frontend/src/components/hr/OrgChart.tsx
Normal file
@@ -0,0 +1,116 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { Tree, TreeNode } from 'react-organizational-chart'
|
||||||
|
import type { Department } from '@/lib/api/employees'
|
||||||
|
import { Building2, Users } from 'lucide-react'
|
||||||
|
|
||||||
|
// Force LTR for org chart - RTL breaks the tree layout and connecting lines
|
||||||
|
function DeptNode({ dept }: { dept: Department }) {
|
||||||
|
const empCount = dept._count?.employees ?? dept.employees?.length ?? 0
|
||||||
|
const childCount = dept.children?.length ?? 0
|
||||||
|
return (
|
||||||
|
<div className="inline-flex flex-col items-center" dir="ltr">
|
||||||
|
<div className="px-4 py-3 bg-white border-2 border-blue-200 rounded-lg shadow-md hover:shadow-lg transition-shadow min-w-[180px] max-w-[220px]">
|
||||||
|
<div className="flex items-center gap-2 mb-1">
|
||||||
|
<Building2 className="h-5 w-5 text-blue-600 flex-shrink-0" />
|
||||||
|
<span className="font-semibold text-gray-900 truncate">{dept.nameAr || dept.name}</span>
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-gray-500 mb-1">{dept.code}</p>
|
||||||
|
<div className="flex gap-2 text-xs text-gray-600">
|
||||||
|
<span className="flex items-center gap-1">
|
||||||
|
<Users className="h-3 w-3" />
|
||||||
|
{empCount} موظف
|
||||||
|
</span>
|
||||||
|
{childCount > 0 && (
|
||||||
|
<span>• {childCount} أقسام فرعية</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{dept.employees && dept.employees.length > 0 && (
|
||||||
|
<div className="mt-2 pt-2 border-t border-gray-100 space-y-0.5">
|
||||||
|
{dept.employees.slice(0, 3).map((emp: any) => (
|
||||||
|
<p key={emp.id} className="text-xs text-gray-600 truncate">
|
||||||
|
{emp.firstNameAr || emp.firstName} {emp.lastNameAr || emp.lastName}
|
||||||
|
{emp.position && ` - ${emp.position.titleAr || emp.position.title}`}
|
||||||
|
</p>
|
||||||
|
))}
|
||||||
|
{dept.employees.length > 3 && (
|
||||||
|
<p className="text-xs text-gray-500">+{dept.employees.length - 3} أكثر</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function OrgChartTree({ dept }: { dept: Department }) {
|
||||||
|
if (!dept.children?.length) {
|
||||||
|
return <TreeNode label={<DeptNode dept={dept} />} />
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<TreeNode label={<DeptNode dept={dept} />}>
|
||||||
|
{dept.children.map((child) => (
|
||||||
|
<OrgChartTree key={child.id} dept={child} />
|
||||||
|
))}
|
||||||
|
</TreeNode>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
interface OrgChartProps {
|
||||||
|
hierarchy: Department[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function OrgChart({ hierarchy }: OrgChartProps) {
|
||||||
|
if (hierarchy.length === 0) {
|
||||||
|
return (
|
||||||
|
<div className="p-12 text-center text-gray-500">
|
||||||
|
<Building2 className="h-16 w-16 mx-auto mb-4 text-gray-300" />
|
||||||
|
<p>لا توجد أقسام. أضف أقساماً من تبويب الأقسام.</p>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (hierarchy.length === 1) {
|
||||||
|
const root = hierarchy[0]
|
||||||
|
return (
|
||||||
|
<div className="p-6 overflow-auto min-h-[400px]" dir="ltr" style={{ direction: 'ltr' }}>
|
||||||
|
<div className="inline-block">
|
||||||
|
<Tree
|
||||||
|
label={<DeptNode dept={root} />}
|
||||||
|
lineWidth="2px"
|
||||||
|
lineColor="#93c5fd"
|
||||||
|
lineBorderRadius="4px"
|
||||||
|
lineHeight="24px"
|
||||||
|
nodePadding="16px"
|
||||||
|
>
|
||||||
|
{root.children?.map((child) => (
|
||||||
|
<OrgChartTree key={child.id} dept={child} />
|
||||||
|
))}
|
||||||
|
</Tree>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<div className="p-6 overflow-auto min-h-[400px]" dir="ltr" style={{ direction: 'ltr' }}>
|
||||||
|
<div className="inline-block">
|
||||||
|
<Tree
|
||||||
|
label={
|
||||||
|
<div className="px-4 py-3 bg-blue-50 border-2 border-blue-200 rounded-lg min-w-[200px] text-center">
|
||||||
|
<p className="font-bold text-gray-900">الشركة</p>
|
||||||
|
<p className="text-xs text-gray-500">الجذر التنظيمي</p>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
lineWidth="2px"
|
||||||
|
lineColor="#93c5fd"
|
||||||
|
lineBorderRadius="4px"
|
||||||
|
lineHeight="24px"
|
||||||
|
nodePadding="16px"
|
||||||
|
>
|
||||||
|
{hierarchy.map((dept) => (
|
||||||
|
<OrgChartTree key={dept.id} dept={dept} />
|
||||||
|
))}
|
||||||
|
</Tree>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -77,6 +77,10 @@ export const contactsAPI = {
|
|||||||
api.post('/contacts/merge', { sourceId, targetId, reason }),
|
api.post('/contacts/merge', { sourceId, targetId, reason }),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export const dashboardAPI = {
|
||||||
|
getStats: () => api.get<{ success: boolean; data: { contacts: number; activeTasks: number; notifications: number } }>('/dashboard/stats'),
|
||||||
|
}
|
||||||
|
|
||||||
export const crmAPI = {
|
export const crmAPI = {
|
||||||
// Deals
|
// Deals
|
||||||
getDeals: (params?: any) => api.get('/crm/deals', { params }),
|
getDeals: (params?: any) => api.get('/crm/deals', { params }),
|
||||||
|
|||||||
@@ -132,12 +132,34 @@ export interface PositionRole {
|
|||||||
_count?: { employees: number };
|
_count?: { employees: number };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface CreatePositionData {
|
||||||
|
title: string;
|
||||||
|
titleAr?: string;
|
||||||
|
code: string;
|
||||||
|
departmentId: string;
|
||||||
|
level?: number;
|
||||||
|
description?: string;
|
||||||
|
}
|
||||||
|
|
||||||
export const positionsAPI = {
|
export const positionsAPI = {
|
||||||
getAll: async (): Promise<PositionRole[]> => {
|
getAll: async (): Promise<PositionRole[]> => {
|
||||||
const response = await api.get('/admin/positions');
|
const response = await api.get('/admin/positions');
|
||||||
return response.data.data || [];
|
return response.data.data || [];
|
||||||
},
|
},
|
||||||
|
|
||||||
|
create: async (data: CreatePositionData): Promise<PositionRole> => {
|
||||||
|
const response = await api.post('/admin/positions', data);
|
||||||
|
return response.data.data;
|
||||||
|
},
|
||||||
|
|
||||||
|
update: async (
|
||||||
|
id: string,
|
||||||
|
data: Partial<CreatePositionData & { isActive?: boolean }>
|
||||||
|
): Promise<PositionRole> => {
|
||||||
|
const response = await api.put(`/admin/positions/${id}`, data);
|
||||||
|
return response.data.data;
|
||||||
|
},
|
||||||
|
|
||||||
updatePermissions: async (
|
updatePermissions: async (
|
||||||
positionId: string,
|
positionId: string,
|
||||||
permissions: Array<{ module: string; resource: string; actions: string[] }>
|
permissions: Array<{ module: string; resource: string; actions: string[] }>
|
||||||
@@ -189,6 +211,53 @@ export const rolesAPI = {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Permission Groups API (Phase 3 - multi-group)
|
||||||
|
export interface PermissionGroup {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
nameAr?: string | null;
|
||||||
|
description?: string | null;
|
||||||
|
isActive: boolean;
|
||||||
|
permissions: { id: string; module: string; resource: string; actions: string[] }[];
|
||||||
|
_count?: { userRoles: number };
|
||||||
|
}
|
||||||
|
|
||||||
|
export const permissionGroupsAPI = {
|
||||||
|
getAll: async (): Promise<PermissionGroup[]> => {
|
||||||
|
const response = await api.get('/admin/permission-groups');
|
||||||
|
return response.data.data || [];
|
||||||
|
},
|
||||||
|
create: async (data: { name: string; nameAr?: string; description?: string }) => {
|
||||||
|
const response = await api.post('/admin/permission-groups', data);
|
||||||
|
return response.data.data;
|
||||||
|
},
|
||||||
|
update: async (id: string, data: Partial<{ name: string; nameAr: string; description: string; isActive: boolean }>) => {
|
||||||
|
const response = await api.put(`/admin/permission-groups/${id}`, data);
|
||||||
|
return response.data.data;
|
||||||
|
},
|
||||||
|
updatePermissions: async (
|
||||||
|
id: string,
|
||||||
|
permissions: Array<{ module: string; resource: string; actions: string[] }>
|
||||||
|
) => {
|
||||||
|
const response = await api.put(`/admin/permission-groups/${id}/permissions`, { permissions });
|
||||||
|
return response.data.data;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
export const userRolesAPI = {
|
||||||
|
getAll: async (userId: string) => {
|
||||||
|
const response = await api.get(`/admin/users/${userId}/roles`);
|
||||||
|
return response.data.data || [];
|
||||||
|
},
|
||||||
|
assign: async (userId: string, roleId: string) => {
|
||||||
|
const response = await api.post(`/admin/users/${userId}/roles`, { roleId });
|
||||||
|
return response.data.data;
|
||||||
|
},
|
||||||
|
remove: async (userId: string, roleId: string) => {
|
||||||
|
await api.delete(`/admin/users/${userId}/roles/${roleId}`);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
// Audit Logs API
|
// Audit Logs API
|
||||||
export interface AuditLog {
|
export interface AuditLog {
|
||||||
id: string;
|
id: string;
|
||||||
|
|||||||
@@ -84,8 +84,12 @@ export const employeesAPI = {
|
|||||||
|
|
||||||
const response = await api.get(`/hr/employees?${params.toString()}`)
|
const response = await api.get(`/hr/employees?${params.toString()}`)
|
||||||
const { data, pagination } = response.data
|
const { data, pagination } = response.data
|
||||||
|
const employees = (data || []).map((e: any) => ({
|
||||||
|
...e,
|
||||||
|
baseSalary: e.baseSalary ?? e.basicSalary ?? 0,
|
||||||
|
}))
|
||||||
return {
|
return {
|
||||||
employees: data || [],
|
employees,
|
||||||
total: pagination?.total || 0,
|
total: pagination?.total || 0,
|
||||||
page: pagination?.page || 1,
|
page: pagination?.page || 1,
|
||||||
pageSize: pagination?.pageSize || 20,
|
pageSize: pagination?.pageSize || 20,
|
||||||
@@ -96,7 +100,8 @@ export const employeesAPI = {
|
|||||||
// Get single employee by ID
|
// Get single employee by ID
|
||||||
getById: async (id: string): Promise<Employee> => {
|
getById: async (id: string): Promise<Employee> => {
|
||||||
const response = await api.get(`/hr/employees/${id}`)
|
const response = await api.get(`/hr/employees/${id}`)
|
||||||
return response.data.data
|
const e = response.data.data
|
||||||
|
return e ? { ...e, baseSalary: e.baseSalary ?? e.basicSalary ?? 0 } : e
|
||||||
},
|
},
|
||||||
|
|
||||||
// Create new employee
|
// Create new employee
|
||||||
@@ -118,10 +123,40 @@ export const employeesAPI = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Departments API
|
// Departments API
|
||||||
|
export interface Department {
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
nameAr?: string | null
|
||||||
|
code: string
|
||||||
|
parentId?: string | null
|
||||||
|
parent?: { id: string; name: string; nameAr?: string | null }
|
||||||
|
description?: string | null
|
||||||
|
isActive?: boolean
|
||||||
|
children?: Department[]
|
||||||
|
employees?: any[]
|
||||||
|
positions?: any[]
|
||||||
|
_count?: { children: number; employees: number }
|
||||||
|
}
|
||||||
|
|
||||||
export const departmentsAPI = {
|
export const departmentsAPI = {
|
||||||
getAll: async (): Promise<any[]> => {
|
getAll: async (): Promise<any[]> => {
|
||||||
const response = await api.get('/hr/departments')
|
const response = await api.get('/hr/departments')
|
||||||
return response.data.data
|
return response.data.data
|
||||||
|
},
|
||||||
|
getHierarchy: async (): Promise<Department[]> => {
|
||||||
|
const response = await api.get('/hr/departments/hierarchy')
|
||||||
|
return response.data.data
|
||||||
|
},
|
||||||
|
create: async (data: { name: string; nameAr?: string; code: string; parentId?: string; description?: string }) => {
|
||||||
|
const response = await api.post('/hr/departments', data)
|
||||||
|
return response.data.data
|
||||||
|
},
|
||||||
|
update: async (id: string, data: Partial<{ name: string; nameAr: string; code: string; parentId: string | null; description: string; isActive: boolean }>) => {
|
||||||
|
const response = await api.put(`/hr/departments/${id}`, data)
|
||||||
|
return response.data.data
|
||||||
|
},
|
||||||
|
delete: async (id: string) => {
|
||||||
|
await api.delete(`/hr/departments/${id}`)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
68
package-lock.json
generated
68
package-lock.json
generated
@@ -1,14 +1,15 @@
|
|||||||
{
|
{
|
||||||
"name": "mind14-crm",
|
"name": "z-crm",
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "mind14-crm",
|
"name": "z-crm",
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"license": "PROPRIETARY",
|
"license": "PROPRIETARY",
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@playwright/test": "^1.58.2",
|
||||||
"concurrently": "^8.2.2"
|
"concurrently": "^8.2.2"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -22,6 +23,22 @@
|
|||||||
"node": ">=6.9.0"
|
"node": ">=6.9.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@playwright/test": {
|
||||||
|
"version": "1.58.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.58.2.tgz",
|
||||||
|
"integrity": "sha512-akea+6bHYBBfA9uQqSYmlJXn61cTa+jbO87xVLCWbTqbWadRVmhxlXATaOjOgcBaWU4ePo0wB41KMFv3o35IXA==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"dependencies": {
|
||||||
|
"playwright": "1.58.2"
|
||||||
|
},
|
||||||
|
"bin": {
|
||||||
|
"playwright": "cli.js"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/ansi-regex": {
|
"node_modules/ansi-regex": {
|
||||||
"version": "5.0.1",
|
"version": "5.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
|
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
|
||||||
@@ -175,6 +192,21 @@
|
|||||||
"node": ">=6"
|
"node": ">=6"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/fsevents": {
|
||||||
|
"version": "2.3.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
|
||||||
|
"integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
|
||||||
|
"dev": true,
|
||||||
|
"hasInstallScript": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"darwin"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/get-caller-file": {
|
"node_modules/get-caller-file": {
|
||||||
"version": "2.0.5",
|
"version": "2.0.5",
|
||||||
"resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz",
|
"resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz",
|
||||||
@@ -212,6 +244,38 @@
|
|||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/playwright": {
|
||||||
|
"version": "1.58.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.58.2.tgz",
|
||||||
|
"integrity": "sha512-vA30H8Nvkq/cPBnNw4Q8TWz1EJyqgpuinBcHET0YVJVFldr8JDNiU9LaWAE1KqSkRYazuaBhTpB5ZzShOezQ6A==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"dependencies": {
|
||||||
|
"playwright-core": "1.58.2"
|
||||||
|
},
|
||||||
|
"bin": {
|
||||||
|
"playwright": "cli.js"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
},
|
||||||
|
"optionalDependencies": {
|
||||||
|
"fsevents": "2.3.2"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/playwright-core": {
|
||||||
|
"version": "1.58.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.58.2.tgz",
|
||||||
|
"integrity": "sha512-yZkEtftgwS8CsfYo7nm0KE8jsvm6i/PTgVtB8DL726wNf6H2IMsDuxCpJj59KDaxCtSnrWan2AeDqM7JBaultg==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"bin": {
|
||||||
|
"playwright-core": "cli.js"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/require-directory": {
|
"node_modules/require-directory": {
|
||||||
"version": "2.1.1",
|
"version": "2.1.1",
|
||||||
"resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz",
|
"resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz",
|
||||||
|
|||||||
14
package.json
14
package.json
@@ -3,6 +3,9 @@
|
|||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"description": "Z.CRM - Enterprise CRM System - Contact Management, Sales, Inventory, Projects, HR, Marketing",
|
"description": "Z.CRM - Enterprise CRM System - Contact Management, Sales, Inventory, Projects, HR, Marketing",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
"capture": "node scripts/capture-page.mjs",
|
||||||
|
"capture:admin": "node scripts/capture-page.mjs /admin",
|
||||||
|
"capture:contacts": "node scripts/capture-page.mjs /contacts",
|
||||||
"install-all": "npm install && cd backend && npm install && cd ../frontend && npm install",
|
"install-all": "npm install && cd backend && npm install && cd ../frontend && npm install",
|
||||||
"dev": "concurrently \"npm run dev:backend\" \"npm run dev:frontend\"",
|
"dev": "concurrently \"npm run dev:backend\" \"npm run dev:frontend\"",
|
||||||
"dev:backend": "cd backend && npm run dev",
|
"dev:backend": "cd backend && npm run dev",
|
||||||
@@ -12,11 +15,18 @@
|
|||||||
"start:backend": "cd backend && npm start",
|
"start:backend": "cd backend && npm start",
|
||||||
"start:frontend": "cd frontend && npm start"
|
"start:frontend": "cd frontend && npm start"
|
||||||
},
|
},
|
||||||
"keywords": ["crm", "erp", "contact-management", "hr", "inventory", "projects"],
|
"keywords": [
|
||||||
|
"crm",
|
||||||
|
"erp",
|
||||||
|
"contact-management",
|
||||||
|
"hr",
|
||||||
|
"inventory",
|
||||||
|
"projects"
|
||||||
|
],
|
||||||
"author": "مجموعة أتمتة",
|
"author": "مجموعة أتمتة",
|
||||||
"license": "PROPRIETARY",
|
"license": "PROPRIETARY",
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@playwright/test": "^1.58.2",
|
||||||
"concurrently": "^8.2.2"
|
"concurrently": "^8.2.2"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
29
scripts/backup-staging.sh
Executable file
29
scripts/backup-staging.sh
Executable file
@@ -0,0 +1,29 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Backup staging database to /root/z_crm/backups/ on the server.
|
||||||
|
# Usage: SSHPASS=yourpassword ./scripts/backup-staging.sh
|
||||||
|
# Or with SSH keys: ./scripts/backup-staging.sh
|
||||||
|
#
|
||||||
|
# Creates backups/backup_YYYYMMDD_HHMMSS.sql on the staging server.
|
||||||
|
|
||||||
|
set -e
|
||||||
|
|
||||||
|
STAGING_HOST="${STAGING_HOST:-root@37.60.249.71}"
|
||||||
|
BACKUP_DIR="/root/z_crm/backups"
|
||||||
|
BACKUP_FILE="backup_$(date +%Y%m%d_%H%M%S).sql"
|
||||||
|
|
||||||
|
echo "Backing up staging database..."
|
||||||
|
echo "Host: $STAGING_HOST"
|
||||||
|
echo "Target: $BACKUP_DIR/$BACKUP_FILE"
|
||||||
|
echo ""
|
||||||
|
|
||||||
|
CMD="mkdir -p $BACKUP_DIR && cd /root/z_crm && docker compose exec -T postgres pg_dump -U postgres mind14_crm > $BACKUP_DIR/$BACKUP_FILE"
|
||||||
|
|
||||||
|
if [ -n "$SSHPASS" ]; then
|
||||||
|
sshpass -e ssh -o StrictHostKeyChecking=no "$STAGING_HOST" "$CMD"
|
||||||
|
else
|
||||||
|
ssh -o StrictHostKeyChecking=no "$STAGING_HOST" "$CMD"
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "Backup complete."
|
||||||
|
echo "File on server: $BACKUP_DIR/$BACKUP_FILE"
|
||||||
|
echo "To restore: docker compose exec -T postgres psql -U postgres mind14_crm < $BACKUP_DIR/$BACKUP_FILE"
|
||||||
76
scripts/capture-page.mjs
Normal file
76
scripts/capture-page.mjs
Normal file
@@ -0,0 +1,76 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
/**
|
||||||
|
* Capture page screenshot using Playwright.
|
||||||
|
* Logs in and captures the dashboard (or specified path).
|
||||||
|
*
|
||||||
|
* Usage: node scripts/capture-page.mjs [path]
|
||||||
|
* path: optional, e.g. /dashboard, /admin, /contacts (default: /dashboard)
|
||||||
|
*
|
||||||
|
* Requires: npm install -D @playwright/test && npx playwright install chromium
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { chromium } from 'playwright';
|
||||||
|
import { writeFileSync, mkdirSync } from 'fs';
|
||||||
|
import { dirname, join } from 'path';
|
||||||
|
import { fileURLToPath } from 'url';
|
||||||
|
|
||||||
|
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||||
|
const BASE_URL = process.env.CAPTURE_BASE_URL || 'https://zerp.atmata-group.com';
|
||||||
|
const LOGIN_EMAIL = process.env.CAPTURE_EMAIL || 'admin@system.local';
|
||||||
|
const LOGIN_PASSWORD = process.env.CAPTURE_PASSWORD || 'Admin@123';
|
||||||
|
const OUTPUT_DIR = join(__dirname, '..', 'assets');
|
||||||
|
const DEFAULT_PATH = process.argv[2] || '/dashboard';
|
||||||
|
|
||||||
|
async function capture() {
|
||||||
|
const browser = await chromium.launch({ headless: true });
|
||||||
|
const context = await browser.newContext({
|
||||||
|
viewport: { width: 1920, height: 1080 },
|
||||||
|
ignoreHTTPSErrors: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
const page = await context.newPage();
|
||||||
|
|
||||||
|
// Navigate to login
|
||||||
|
console.log(`Navigating to ${BASE_URL}/login...`);
|
||||||
|
await page.goto(`${BASE_URL}/login`, { waitUntil: 'networkidle', timeout: 30000 });
|
||||||
|
|
||||||
|
// Login
|
||||||
|
console.log('Logging in...');
|
||||||
|
await page.fill('input[type="email"], input[name="email"]', LOGIN_EMAIL);
|
||||||
|
await page.fill('input[type="password"], input[name="password"]', LOGIN_PASSWORD);
|
||||||
|
await page.click('button[type="submit"], button:has-text("تسجيل الدخول"), button:has-text("Login")');
|
||||||
|
|
||||||
|
// Wait for redirect to dashboard
|
||||||
|
await page.waitForURL(/\/(dashboard|admin|$)/, { timeout: 15000 }).catch(() => {});
|
||||||
|
|
||||||
|
// Navigate to target path if not already there
|
||||||
|
const targetUrl = `${BASE_URL}${DEFAULT_PATH.startsWith('/') ? '' : '/'}${DEFAULT_PATH}`;
|
||||||
|
if (!page.url().includes(DEFAULT_PATH)) {
|
||||||
|
console.log(`Navigating to ${targetUrl}...`);
|
||||||
|
await page.goto(targetUrl, { waitUntil: 'networkidle', timeout: 15000 });
|
||||||
|
}
|
||||||
|
|
||||||
|
await page.waitForLoadState('networkidle');
|
||||||
|
await page.waitForTimeout(2000); // Let any async content render
|
||||||
|
|
||||||
|
mkdirSync(OUTPUT_DIR, { recursive: true });
|
||||||
|
const filename = `capture-${DEFAULT_PATH.replace(/\//g, '-') || 'dashboard'}-${Date.now()}.png`;
|
||||||
|
const filepath = join(OUTPUT_DIR, filename);
|
||||||
|
|
||||||
|
await page.screenshot({ path: filepath, fullPage: true });
|
||||||
|
console.log(`Screenshot saved: ${filepath}`);
|
||||||
|
|
||||||
|
// Also save a fixed name for easy reference
|
||||||
|
const latestPath = join(OUTPUT_DIR, 'capture-latest.png');
|
||||||
|
await page.screenshot({ path: latestPath, fullPage: true });
|
||||||
|
console.log(`Latest screenshot: ${latestPath}`);
|
||||||
|
} finally {
|
||||||
|
await browser.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
capture().catch((err) => {
|
||||||
|
console.error('Capture failed:', err);
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user