### Service Method Definition Source: https://github.com/aifgrouplaos/aif-gold/blob/main/AGENTS.md Shows how to define services as plain objects with asynchronous methods. This example demonstrates a `getData` method that interacts with a database using Prisma to fetch multiple records. ```typescript export const myFeatureService = { async getData(): Promise { return prisma.myModel.findMany(); }, }; ``` -------------------------------- ### Development and Build Commands Source: https://github.com/aifgrouplaos/aif-gold/blob/main/AGENTS.md Standard pnpm commands for managing the development lifecycle, including server execution and production builds. ```bash pnpm dev # Dev server on port 8888 (Turbopack) pnpm build # Production build pnpm start # Production server ``` -------------------------------- ### Get Dashboard Statistics with TypeScript Source: https://context7.com/aifgrouplaos/aif-gold/llms.txt This snippet retrieves key statistics for the dashboard, such as total customers, open positions, pending settlements, and gold inventory. It utilizes a service layer to fetch the data. ```typescript import { dashboardService } from "@/features/dashboard/services"; const stats = await dashboardService.getStats(); // { // totalCustomers: 150, // openPositions: 45, // pendingSettlements: 12, // goldInventoryKg: 250.5 // } ``` -------------------------------- ### Server Action Implementation Source: https://github.com/aifgrouplaos/aif-gold/blob/main/AGENTS.md Illustrates the structure of a server action, which acts as a thin wrapper for service methods. It includes the 'use server' directive and demonstrates how to import types and services, returning a Promise of a specific type. ```typescript "use server"; import { myFeatureService } from "../services"; import type { MyType } from "@/types/my-feature"; export async function getMyDataAction(): Promise { return myFeatureService.getData(); } ``` -------------------------------- ### Testing and Verification Commands Source: https://github.com/aifgrouplaos/aif-gold/blob/main/AGENTS.md Commands for running unit tests with Vitest and end-to-end tests with Playwright. ```bash pnpm test # Run all unit tests once (Vitest) pnpm test:watch # Vitest interactive watch mode pnpm vitest run src/lib/calculations/gold.test.ts pnpm vitest run --reporter=verbose -t "spotPerKg" pnpm test:e2e # Run all e2e tests pnpm test:e2e:ui # Playwright UI mode pnpm playwright test e2e/login.spec.ts # Single e2e file ``` -------------------------------- ### Database Management Commands Source: https://github.com/aifgrouplaos/aif-gold/blob/main/AGENTS.md Prisma commands for schema generation, migration, seeding, and database inspection. ```bash pnpm db:generate # prisma generate (after schema changes) pnpm db:migrate # prisma migrate dev (dev only) pnpm db:push # prisma db push (prototype/quick sync) pnpm db:seed # tsx prisma/seed.ts pnpm db:studio # Prisma Studio GUI ``` -------------------------------- ### Adding Shadcn UI Component via CLI Source: https://github.com/aifgrouplaos/aif-gold/blob/main/AGENTS.md Provides the command-line instruction to add new Shadcn UI components to the project using the `shadcn-ui` CLI. This command automates the process of integrating components managed by the CLI. ```bash pnpm dlx shadcn@latest add ``` -------------------------------- ### Manage Customers via Services and Server Actions Source: https://context7.com/aifgrouplaos/aif-gold/llms.txt Handles customer retrieval, creation, and statement generation. Includes server-side actions for form submission and service methods for fetching filtered lists and transaction summaries. ```typescript import { customerService } from "@/features/customers/services"; import { createCustomerAction } from "@/features/customers/actions"; // Retrieval const customers = await customerService.getCustomers({ status: "ACTIVE", search: "John Doe" }); // Creation const customerData = { firstName: "John", lastName: "Doe", phone: "+1234567890" }; const formData = new FormData(); formData.append("payload", JSON.stringify(customerData)); const result = await createCustomerAction(formData); // Statements const statements = await customerService.getCustomerStatement("customer-id"); const summary = await customerService.getCustomerStatementSummary("customer-id"); ``` -------------------------------- ### Manage User Accounts in TypeScript Source: https://context7.com/aifgrouplaos/aif-gold/llms.txt Facilitates user creation by linking existing employees to system roles and handles password management. Requires fetching available employees and role options prior to user creation. ```typescript import { userService } from "@/features/users/services"; const availableEmployees = await userService.getAvailableEmployees(); const roles = await userService.getRoleOptions(); const user = await userService.createUser({ username: "jane.smith", password: "SecureP@ss123", status: "ACTIVE", employeeId: "employee-id", roleId: "role-id" }); await userService.resetPassword("user-id", "NewSecureP@ss456"); ``` -------------------------------- ### Manage Roles and Permissions in TypeScript Source: https://context7.com/aifgrouplaos/aif-gold/llms.txt Allows retrieval of system permissions and creation of custom roles with specific access levels. Supports role duplication to streamline administrative configuration. ```typescript import { roleService } from "@/features/roles/services"; const permissionGroups = await roleService.getAllPermissions(); const role = await roleService.createRole({ name: "Trader", description: "Can manage trading operations", permissionIds: ["perm-id-1", "perm-id-2", "perm-id-3"] }); const duplicatedRole = await roleService.duplicateRole("role-id"); ``` -------------------------------- ### Check Permissions with TypeScript Source: https://context7.com/aifgrouplaos/aif-gold/llms.txt This snippet demonstrates how to check user permissions using a set of predefined functions. It includes checks for specific permissions and module-level access (read, create, update, delete, export). Dependencies include the 'permissions' library. ```typescript import { hasPermission, canReadModule, canCreateModule, canUpdateModule, canDeleteModule, canExportModule, canApproveModule } from "@/lib/permissions"; const userPermissions = ["customers.read", "customers.create", "positions.read"]; // Check specific permission hasPermission(userPermissions, "customers.read"); // true hasPermission(userPermissions, "customers.delete"); // false // Check module-level permissions canReadModule(userPermissions, "customers"); // true canCreateModule(userPermissions, "customers"); // true canDeleteModule(userPermissions, "customers"); // false canExportModule(userPermissions, "customers"); // false ``` -------------------------------- ### Calculate Inventory and Rental Fees in TypeScript Source: https://context7.com/aifgrouplaos/aif-gold/llms.txt Provides utility functions for calculating gold inventory balances, rental fees based on weight and duration, and date differences. These functions are essential for financial reporting and tracking asset movements. ```typescript import { inventoryBalance, rentalFee, daysBetween } from "@/lib/calculations/gold"; const balance = inventoryBalance(100, 50, 20, 10, 30, 15, 5); const weightKg = 10; const pricePerKgPerDay = 5.50; const days = 30; const fee = rentalFee(weightKg, pricePerKgPerDay, days); const startDate = new Date("2025-01-01"); const endDate = new Date("2025-01-31"); const numDays = daysBetween(startDate, endDate); ``` -------------------------------- ### Manage Supplier Operations in TypeScript Source: https://context7.com/aifgrouplaos/aif-gold/llms.txt Provides methods to create supplier put orders, record transaction statements, and perform portfolio moves between statements. These services interact with the supplier database to maintain accurate gold trading records. ```typescript import { supplierService } from "@/features/suppliers/services"; // Create Put Order const putOrder = await supplierService.createPutOrder({ orderDate: "2025-01-15", customerInfo: "VIP Customer - Gold Holdings Ltd", orderType: "BUY", goldType: "XAU", supplierAccountId: "supplier-id", status: "ACTIVE", sourceType: "MANUAL", spotPerOz: "2650.50", qtyKg: "10.000000", pricePerKgUsd: "85200.00", totalAmountUsd: "852000.00", remark: "Monthly allocation order" }); // Create Supplier Statement const statement = await supplierService.createSupplierStatement({ supplierAccountId: "supplier-id", tradeDate: "2025-01-15", valueDate: "2025-01-17", narration: "Gold purchase settlement", spotPerOz: "2650.50", spotPerKgUsd: "85200.87", xauDebitKg: "10.000000", xauCreditKg: "0.000000", xauBalanceKg: "50.000000", amountDebitUsd: "0.00", amountCreditUsd: "852000.00", amountBalanceUsd: "1500000.00", sourceType: "MANUAL" }); // Create Supplier Move Port const movePort = await supplierService.createSupplierMovePort({ supplierAccountId: "supplier-id", fromSupplierStatementId: "from-statement-id", toSupplierStatementId: "to-statement-id", tradeDate: "2025-01-15", sellerInfo: "Internal transfer", xauDebitKg: "5.000000", xauCreditKg: "5.000000", xauBalanceKg: "0.000000", amountDebitUsd: "0.00", amountCreditUsd: "0.00", amountBalanceUsd: "0.00", sourceType: "MANUAL", remark: "Portfolio rebalancing" }); ``` -------------------------------- ### Generate Sequential IDs with TypeScript Source: https://context7.com/aifgrouplaos/aif-gold/llms.txt This snippet shows how to generate human-readable sequential IDs for various entities like customers, employees, and users. It also includes a utility function to create entities with automatic ID generation and retry logic for ID collisions. ```typescript import { generateCustomerId, generateEmployeeId, generateUserId, generateSupplierAccountId, generateSupplierStatementId, generatePutOrderId, generateSupplierMovePortId, createWithGeneratedId } from "@/lib/id-generator"; // Generate IDs manually const customerId = await generateCustomerId(); // "C-001", "C-002", ... const employeeId = await generateEmployeeId(); // "EMP-001", "EMP-002", ... const userId = await generateUserId(); // "USER-001", "USER-002", ... const supplierId = await generateSupplierAccountId(); // "SUP-001", "SUP-002", ... const statementId = await generateSupplierStatementId(); // "SST-001", ... const putOrderId = await generatePutOrderId(); // "PO-001", "PO-002", ... const movePortId = await generateSupplierMovePortId(); // "MP-001", "MP-002", ... // Create entity with automatic retry on ID collision const result = await createWithGeneratedId( generateCustomerId, async (customerId) => { return prisma.customer.create({ data: { customerId, firstName: "John", lastName: "Doe" } }); } ); ``` -------------------------------- ### Code Quality and Linting Commands Source: https://github.com/aifgrouplaos/aif-gold/blob/main/AGENTS.md Commands to ensure code quality through ESLint, Prettier, and TypeScript type checking. ```bash pnpm lint # ESLint check pnpm lint:fix # ESLint auto-fix pnpm format # Prettier write (src/**/*.{ts,tsx,css,json}) pnpm format:check # Prettier check pnpm type-check # tsc --noEmit ``` -------------------------------- ### NextAuth Credentials Provider Authentication Source: https://context7.com/aifgrouplaos/aif-gold/llms.txt Handles user authentication using NextAuth v5 with a credentials provider. It validates user credentials against the database using bcrypt hashing and includes role permissions in the session. Supports login, session retrieval, and logout functionalities. ```typescript import { signIn, signOut, auth } from "@/lib/auth"; // Login with credentials const result = await signIn("credentials", { username: "admin", password: "securePassword123", redirect: false, }); // Get current session with user info const session = await auth(); // session.user contains: { id, name, email, role, permissions, locale, userId } // Logout await signOut({ redirectTo: "/login" }); ```