NNS Telecom Management System
Expert AI assistant for the NNS telecom management platform - a Next.js-based system for managing fiber optic line installations, inventory, and operational workflows.
Project Overview
NNS is a comprehensive telecom management platform built with Next.js that handles the complete lifecycle of fiber optic installations, from planning and task assignment through completion, with AI-powered validation and suggestions.
Technology Stack & Architecture
Core Technologies
**Framework**: Next.js 15 (App Router), React 19, TypeScript**Styling**: Tailwind CSS, Radix UI, shadcn/ui**Database**: PostgreSQL via Prisma ORM**Authentication**: NextAuth with Google OAuth support**State Management**: React Context API**Forms**: React Hook Form + Zod validation**Icons**: Lucide ReactFile Structure
`app/`: Next.js App Router pages (auth, inventory, invoices, tasks, reports, profile, welcome)`components/`: Reusable UI components (layout, modals, tables, shadcn/ui)`contexts/`: React Context providers (auth, theme, notifications)`lib/`: Utilities (Prisma client, AI suggestions, report services, inventory usage service)`hooks/`: Custom React hooks`styles/`: Tailwind CSS configuration and global stylesDomain Rules & Validation
Distribution Points (DPs)
Format: `XX-XXXX-XXXX-XXX-0X`Regex-enforced, must be unique per lineValidated via AI serviceCable Measurements
**F1**: Start to middle distance**G1**: Middle to end distance**Total**: F1 + G1**Wastage**: Must be ≤ 20% of total cable lengthAI validation enforces these rulesPower Readings
Measured at DP/inboxReading ≥ 20 triggers warningsValidated during line installationInventory Items
Track drums, rosettes, hardware, cable lengthsReorder thresholds enforcedStock deductions tied to installationsKey Database Tables
`line_details`: Fiber optic line installations and measurements`tasks`: Work assignments and status tracking`inventory_items`: Current stock levels and reorder points`monthly_inventory_usage`: Usage tracking per item per month (unique on item+month+year)`drum_tracking`: Cable drum management`inventory_invoice_items`: Stock additions from invoices`waste_tracking`: Manual waste entry records`invoices`: Financial records`profiles`: User profiles and rolesInstructions
1. Database Integration
Always use the singleton Prisma client:
```typescript
import { prisma } from "@/lib/prisma"
```
Enforce database rules:
DP regex validationWastage ≤ 20% of total cableDrum quantity checksPower reading warningsSerial number validation2. Authentication & Authorization
Use NextAuth for authentication:
Import `AuthProvider` for session managementConfigure providers in `app/api/auth/[...nextauth]`Google OAuth redirect URLs: - Production: `https://<domain>/auth/callback`
- Local: `http://localhost:3000/auth/callback`
Enforce server-side role checks (admin/moderator) via NextAuth sessionThe `/auth/callback` page finalizes OAuth and redirects to dashboard3. Google Sheets Import (Admin/Moderator Only)
**API Endpoint**: `POST /api/import-lines`
**Request Body**:
```json
{
"sheetUrl": "string",
"sheetName": "string",
"month": "number",
"year": "number",
"dryRun": "boolean (optional)"
}
```
**Validations**:
Sheet name must contain "nns" (case-insensitive)First row must match required headers (case-insensitive)Overwrites existing `line_details` for the month where phone numbers matchDeletes matching rows, then inserts new ones**Column Mappings**:
`Pole-5.6` → `pole``Pole-6.7` → `pole_67``Total` → `total_cable`(Follow existing mapping patterns)**Default Values**:
Status defaults to `completed` on import**Environment Variables Required**:
`GOOGLE_SERVICE_ACCOUNT_EMAIL``GOOGLE_SERVICE_ACCOUNT_KEY` (PEM format, escape newlines as `\n`)**Access Requirements**:
Sheet must grant Viewer access to service account emailPublic sheets still require explicit sharing**Dry Run**:
Use `dryRun: true` to preview deletions and insertionsReturns: totals, existingByPhone, sampleInserts4. Inventory Management
**Stock Flow**:
Add stock via inventory invoices (primary method) or manual editing (admin)Reduce stock automatically during Google Sheets sync based on hardware usageTrack monthly usage to prevent duplicate deductions**Monthly Usage Tracking** (`monthly_inventory_usage` table):
Tracks total usage per item per month/yearUnique constraint on item+month+yearOnly **difference** between new and previous usage is deducted from inventory**API Endpoints**:
`GET /api/inventory/usage?month=X&year=Y` - Get monthly usage summary`DELETE /api/inventory/usage` - Reset monthly usage (admin only, restores inventory)`POST /api/inventory/usage` with `{action: "recalculate"}` - Recalculate all inventory from usage records**Service Location**:
Core logic in `lib/inventory-usage-service.ts`5. Component & Layout Patterns
**Layouts**:
Use `PublicLayout` for landing/marketing pagesUse `DashboardLayout` for authenticated app pages**Component Organization**:
Modals: `components/modals/`Tables: `components/tables/`Forms: Use React Hook Form + Zod validation**AI Integration**:
```typescript
import { AIService } from "@/lib/ai-suggestions"
```
Use for DP validation, wastage checks, power readings, error detection6. Forms & Validation
For all forms:
Use React Hook Form for form stateUse Zod for schema validationImplement loading states during submissionImplement error states with user-friendly messagesValidate on both client and server sideSanitize all user inputs7. Development Best Practices
**Installation**:
```bash
npm install --legacy-peer-deps
```
(Required for React 19 compatibility)
**Development Server**:
```bash
npm run dev
```
**Code Quality**:
Use TypeScript strict modeFollow Next.js App Router conventionsUse semantic HTML with ARIA labelsImplement error boundariesApply database constraints via Prisma migrations**Security**:
Validate all inputs client and server-sideEnforce server-side authorization checks via NextAuthSanitize user data before database operationsApply proper role-based access control**Performance**:
Optimize database queriesUse loading states for async operationsImplement proper error handling8. Adding New Features
When adding features:
1. Follow existing modal/form/table patterns
2. Ensure inventory and drum updates align with line installations
3. Use AI validation for domain-specific rules
4. Add both client and server-side validation
5. Implement proper loading and error states
6. Update this documentation with new domain rules
7. Write Prisma migrations for schema changes
8. Test calculations and AI logic thoroughly
Example Usage
**Creating a new line installation with validation**:
1. Validate DP format using AI service
2. Calculate total cable (F1 + G1)
3. Verify wastage ≤ 20%
4. Check power readings
5. Update inventory for used materials
6. Record in monthly usage tracking
7. Create line_details record via Prisma
**Importing lines from Google Sheets**:
1. Verify user has admin/moderator role
2. Validate sheet name contains "nns"
3. Check headers match required format
4. Optional: Use dry-run to preview changes
5. Delete existing records for month/phone matches
6. Insert new records with mapped columns
7. Update inventory based on usage delta
8. Record usage in monthly_inventory_usage
Important Notes
All inventory updates must be consistent with line installationsMonthly usage prevents duplicate deductions on re-syncServer-side role checks are mandatory for admin operationsGoogle Sheets require explicit access grant to service accountForms require comprehensive validation and error handlingDocument new domain rules in project instructions