NEXUS JFD AUTOCARE JSON 


{
  "project": {
    "name": "JFD Auto Care Portal",
    "version": "1.0.0",
    "description": "Sistema web de gestión operativa y financiera para JFD Auto Care, optimizado para cPanel, que permite registrar inspecciones vehiculares, gestionar reparaciones con firma digital, generar prefacturas automáticas y consolidar cortes financieros.",
    "repository": null,
    "license": "Proprietary",
    "author": "JFD Auto Care Dev Team"
  },
  "infrastructure": {
    "hosting": "cPanel (HappyWebServer)",
    "subdomain": "portal.jfdautocare.com",
    "root_path": "/home2/jfdautoc/portal.jfdautocare.com",
    "php_version": "8.3",
    "database": {
      "engine": "MySQL 8.0 / MariaDB 10.6+",
      "name": "jfdautoc_jfdautoc_portal",
      "user": "jfdautoc_jfdautoc_portal_user",
      "password": "AutoCare2026$",
      "host": "localhost",
      "charset": "utf8mb4",
      "connection_options": {
        "PDO::ATTR_ERRMODE": "PDO::ERRMODE_EXCEPTION",
        "PDO::ATTR_DEFAULT_FETCH_MODE": "PDO::FETCH_ASSOC",
        "PDO::ATTR_EMULATE_PREPARES": false
      }
    },
    "ssl": {
      "type": "Wildcard or SAN",
      "coverage": ["www.jfdautocare.com", "portal.jfdautocare.com"],
      "force_https": true
    },
    "email": {
      "smtp_host": "localhost",
      "smtp_port": 587,
      "from_address": "info@jfdautocare.com",
      "from_name": "JFD Auto Care Portal",
      "encryption": "tls"
    }
  },
  "roles": {
    "admin": {
      "name": "Admin",
      "permissions": [
        "users:crud",
        "dealers:crud",
        "services:crud",
        "prices:crud",
        "reports:view",
        "reports:export",
        "settings:manage",
        "cuts:generate",
        "cuts:confirm",
        "invoices:view",
        "audit:full"
      ],
      "scope": "global",
      "can_impersonate": false,
      "requires_2fa": true
    },
    "employee": {
      "name": "Empleado",
      "permissions": [
        "inspections:create",
        "inspections:read:assigned",
        "repairs:execute",
        "repairs:mark_complete",
        "invoices:draft",
        "signatures:request",
        "batch:process",
        "prefactura:send"
      ],
      "scope": "assigned_dealers_only",
      "can_view_financial": false,
      "can_modify_prices": false
    },
    "accounting": {
      "name": "Contabilidad",
      "permissions": [
        "invoices:view",
        "invoices:export",
        "cuts:view",
        "cuts:mark_paid",
        "reports:financial",
        "prefacturas:receive"
      ],
      "scope": "financial_module_readonly",
      "can_edit_operational": false,
      "can_generate_cuts": false
    }
  },
  "entities": {
    "dealer": {
      "table": "dealers",
      "fields": {
        "id": {"type": "INT", "primary": true, "auto_increment": true},
        "nombre_comercial": {"type": "VARCHAR(255)", "required": true},
        "contacto_nombre": {"type": "VARCHAR(255)", "required": true},
        "contacto_email": {"type": "VARCHAR(255)", "required": true},
        "contacto_telefono": {"type": "VARCHAR(20)", "required": false},
        "direccion_fisica": {"type": "TEXT", "required": false},
        "correo_contabilidad": {"type": "VARCHAR(255)", "required": true, "description": "Para envío automático de prefacturas/consolidados"},
        "tipo_facturacion": {"type": "ENUM", "values": ["reparaciones", "limpieza", "ambos"], "default": "ambos"},
        "regla_facturacion": {"type": "ENUM", "values": ["1_factura_por_carro", "multiples_reparaciones_1_factura"], "default": "1_factura_por_carro"},
        "activo": {"type": "BOOLEAN", "default": true},
        "created_at": {"type": "TIMESTAMP", "default": "CURRENT_TIMESTAMP"},
        "updated_at": {"type": "TIMESTAMP", "on_update": "CURRENT_TIMESTAMP"}
      },
      "indexes": ["nombre_comercial", "contacto_email", "activo"],
      "relations": {
        "has_many": ["employees", "vehicles", "invoices", "cuts"]
      }
    },
    "employee": {
      "table": "employees",
      "fields": {
        "id": {"type": "INT", "primary": true, "auto_increment": true},
        "user_id": {"type": "INT", "foreign_key": "users.id", "required": true},
        "nombre_completo": {"type": "VARCHAR(255)", "required": true},
        "email": {"type": "VARCHAR(255)", "unique": true, "required": true},
        "telefono": {"type": "VARCHAR(20)", "required": false},
        "activo": {"type": "BOOLEAN", "default": true},
        "created_at": {"type": "TIMESTAMP", "default": "CURRENT_TIMESTAMP"},
        "updated_at": {"type": "TIMESTAMP", "on_update": "CURRENT_TIMESTAMP"}
      },
      "indexes": ["email", "activo", "user_id"],
      "relations": {
        "belongs_to": ["user"],
        "belongs_to_many": ["dealers", "via: employee_dealers"]
      }
    },
    "employee_dealer": {
      "table": "employee_dealers",
      "fields": {
        "employee_id": {"type": "INT", "foreign_key": "employees.id", "composite_pk": true},
        "dealer_id": {"type": "INT", "foreign_key": "dealers.id", "composite_pk": true},
        "assigned_at": {"type": "TIMESTAMP", "default": "CURRENT_TIMESTAMP"}
      },
      "indexes": ["employee_id", "dealer_id"]
    },
    "vehicle": {
      "table": "vehicles",
      "fields": {
        "id": {"type": "INT", "primary": true, "auto_increment": true},
        "vin": {"type": "VARCHAR(17)", "unique": true, "required": true},
        "marca": {"type": "VARCHAR(100)", "required": true},
        "modelo": {"type": "VARCHAR(100)", "required": true},
        "anio": {"type": "YEAR", "required": true},
        "color": {"type": "VARCHAR(50)", "required": false},
        "dealer_id": {"type": "INT", "foreign_key": "dealers.id", "required": true},
        "placa_tag": {"type": "VARCHAR(20)", "required": false},
        "pre_aprobado": {"type": "BOOLEAN", "default": false, "description": "Salta firma inicial para listas de limpieza"},
        "created_at": {"type": "TIMESTAMP", "default": "CURRENT_TIMESTAMP"},
        "updated_at": {"type": "TIMESTAMP", "on_update": "CURRENT_TIMESTAMP"}
      },
      "indexes": ["vin", "dealer_id", "placa_tag", "pre_aprobado"],
      "relations": {
        "belongs_to": ["dealer"],
        "has_many": ["inspections"]
      }
    },
    "inspection": {
      "table": "inspections",
      "fields": {
        "id": {"type": "INT", "primary": true, "auto_increment": true},
        "vehicle_id": {"type": "INT", "foreign_key": "vehicles.id", "required": true},
        "employee_id": {"type": "INT", "foreign_key": "employees.id", "required": true},
        "fecha_hora": {"type": "DATETIME", "default": "CURRENT_TIMESTAMP"},
        "estado": {"type": "ENUM", "values": ["draft", "pending_approval", "approved", "in_progress", "completed", "validated", "sent", "invoiced", "paid"], "default": "draft"},
        "notas_generales": {"type": "TEXT", "required": false},
        "firma_inicial_png": {"type": "VARCHAR(255)", "required": false, "description": "Ruta o base64 de firma canvas inicial"},
        "firma_final_png": {"type": "VARCHAR(255)", "required": false, "description": "Ruta o base64 de firma canvas final"},
        "firma_inicial_timestamp": {"type": "TIMESTAMP", "required": false},
        "firma_final_timestamp": {"type": "TIMESTAMP", "required": false},
        "prefactura_enviada_at": {"type": "TIMESTAMP", "required": false},
        "created_at": {"type": "TIMESTAMP", "default": "CURRENT_TIMESTAMP"},
        "updated_at": {"type": "TIMESTAMP", "on_update": "CURRENT_TIMESTAMP"}
      },
      "indexes": ["vehicle_id", "employee_id", "estado", "fecha_hora"],
      "relations": {
        "belongs_to": ["vehicle", "employee"],
        "has_many": ["inspection_items", "repairs"]
      }
    },
    "inspection_item": {
      "table": "inspection_items",
      "fields": {
        "id": {"type": "INT", "primary": true, "auto_increment": true},
        "inspection_id": {"type": "INT", "foreign_key": "inspections.id", "required": true},
        "service_id": {"type": "INT", "foreign_key": "services.id", "required": true},
        "ubicacion_vehiculo": {"type": "VARCHAR(100)", "required": true, "description": "Ej: 'Puerta delantera izquierda', 'Capó'"},
        "nivel_complejidad": {"type": "ENUM", "values": [1, 2, 3], "required": false, "description": "Para Scratch Repair: 1=superficial, 2=medio, 3=profundo"},
        "notas": {"type": "TEXT", "required": false},
        "estado": {"type": "ENUM", "values": ["pendiente", "aprobado", "rechazado"], "default": "pendiente"},
        "precio_estimado": {"type": "DECIMAL(10,2)", "required": false},
        "created_at": {"type": "TIMESTAMP", "default": "CURRENT_TIMESTAMP"}
      },
      "indexes": ["inspection_id", "service_id", "estado"],
      "relations": {
        "belongs_to": ["inspection", "service"]
      }
    },
    "repair": {
      "table": "repairs",
      "fields": {
        "id": {"type": "INT", "primary": true, "auto_increment": true},
        "inspection_id": {"type": "INT", "foreign_key": "inspections.id", "required": true},
        "inspection_item_id": {"type": "INT", "foreign_key": "inspection_items.id", "required": true},
        "service_executed": {"type": "VARCHAR(100)", "required": true},
        "tiempo_estimado_min": {"type": "INT", "required": false},
        "tiempo_real_min": {"type": "INT", "required": false},
        "materiales_usados": {"type": "TEXT", "required": false},
        "precio_final": {"type": "DECIMAL(10,2)", "required": true},
        "ajuste_manual": {"type": "DECIMAL(10,2)", "default": 0, "description": "Ajuste por material especial u otros"},
        "estado": {"type": "ENUM", "values": ["pending", "in_progress", "completed"], "default": "pending"},
        "completed_at": {"type": "TIMESTAMP", "required": false},
        "created_at": {"type": "TIMESTAMP", "default": "CURRENT_TIMESTAMP"},
        "updated_at": {"type": "TIMESTAMP", "on_update": "CURRENT_TIMESTAMP"}
      },
      "indexes": ["inspection_id", "estado", "completed_at"],
      "relations": {
        "belongs_to": ["inspection", "inspection_item"]
      }
    },
    "invoice": {
      "table": "invoices",
      "fields": {
        "id": {"type": "INT", "primary": true, "auto_increment": true},
        "dealer_id": {"type": "INT", "foreign_key": "dealers.id", "required": true},
        "inspection_id": {"type": "INT", "foreign_key": "inspections.id", "required": true},
        "folio": {"type": "VARCHAR(50)", "unique": true, "required": false},
        "monto_bruto": {"type": "DECIMAL(10,2)", "required": true},
        "impuestos": {"type": "DECIMAL(10,2)", "default": 0},
        "descuentos": {"type": "DECIMAL(10,2)", "default": 0},
        "monto_neto": {"type": "DECIMAL(10,2)", "required": true},
        "fecha_emision": {"type": "DATE", "required": false},
        "estado": {"type": "ENUM", "values": ["draft", "sent", "invoiced", "paid"], "default": "draft"},
        "tipo_corte": {"type": "ENUM", "values": ["semanal", "mensual"], "required": false},
        "cut_id": {"type": "INT", "foreign_key": "cuts.id", "required": false},
        "pdf_path": {"type": "VARCHAR(255)", "required": false},
        "envio_email_at": {"type": "TIMESTAMP", "required": false},
        "created_at": {"type": "TIMESTAMP", "default": "CURRENT_TIMESTAMP"},
        "updated_at": {"type": "TIMESTAMP", "on_update": "CURRENT_TIMESTAMP"}
      },
      "indexes": ["dealer_id", "inspection_id", "estado", "fecha_emision", "cut_id"],
      "relations": {
        "belongs_to": ["dealer", "inspection", "cut"]
      }
    },
    "cut": {
      "table": "cuts",
      "fields": {
        "id": {"type": "INT", "primary": true, "auto_increment": true},
        "dealer_id": {"type": "INT", "foreign_key": "dealers.id", "required": true},
        "periodo_inicio": {"type": "DATE", "required": true},
        "periodo_fin": {"type": "DATE", "required": true},
        "monto_total": {"type": "DECIMAL(12,2)", "required": true},
        "estado": {"type": "ENUM", "values": ["generated", "sent", "paid"], "default": "generated"},
        "pdf_path": {"type": "VARCHAR(255)", "required": false},
        "confirmado_por": {"type": "INT", "foreign_key": "users.id", "required": false},
        "pagado_por": {"type": "INT", "foreign_key": "users.id", "required": false},
        "pagado_at": {"type": "TIMESTAMP", "required": false},
        "created_at": {"type": "TIMESTAMP", "default": "CURRENT_TIMESTAMP"},
        "updated_at": {"type": "TIMESTAMP", "on_update": "CURRENT_TIMESTAMP"}
      },
      "indexes": ["dealer_id", "periodo_inicio", "periodo_fin", "estado"],
      "relations": {
        "belongs_to": ["dealer"],
        "has_many": ["invoices"]
      }
    },
    "service": {
      "table": "services",
      "fields": {
        "id": {"type": "INT", "primary": true, "auto_increment": true},
        "nombre": {"type": "VARCHAR(100)", "required": true},
        "descripcion": {"type": "TEXT", "required": false},
        "unidad_cobro": {"type": "ENUM", "values": ["panel", "vehiculo", "punto", "nivel", "hora"], "required": true},
        "precio_base": {"type": "DECIMAL(10,2)", "required": true},
        "niveles_complejidad": {"type": "JSON", "required": false, "description": "Para servicios con niveles: {'1': precio, '2': precio, '3': precio}"},
        "variantes_tamano": {"type": "JSON", "required": false, "description": "Para Ceramic Coating: {'sedan': precio, 'suv': precio, 'truck': precio}"},
        "activo": {"type": "BOOLEAN", "default": true},
        "created_at": {"type": "TIMESTAMP", "default": "CURRENT_TIMESTAMP"},
        "updated_at": {"type": "TIMESTAMP", "on_update": "CURRENT_TIMESTAMP"}
      },
      "indexes": ["nombre", "activo"],
      "relations": {
        "has_many": ["inspection_items", "repairs"]
      }
    },
    "dealer_service_price": {
      "table": "dealer_service_prices",
      "fields": {
        "id": {"type": "INT", "primary": true, "auto_increment": true},
        "dealer_id": {"type": "INT", "foreign_key": "dealers.id", "required": true},
        "service_id": {"type": "INT", "foreign_key": "services.id", "required": true},
        "precio_personalizado": {"type": "DECIMAL(10,2)", "required": false},
        "porcentaje_ajuste": {"type": "DECIMAL(5,2)", "required": false, "description": "Ajuste % sobre precio base"},
        "activo": {"type": "BOOLEAN", "default": true},
        "created_at": {"type": "TIMESTAMP", "default": "CURRENT_TIMESTAMP"}
      },
      "indexes": ["dealer_id", "service_id"],
      "unique": [["dealer_id", "service_id"]],
      "relations": {
        "belongs_to": ["dealer", "service"]
      }
    },
    "user": {
      "table": "users",
      "fields": {
        "id": {"type": "INT", "primary": true, "auto_increment": true},
        "nombre_completo": {"type": "VARCHAR(255)", "required": true},
        "username": {"type": "VARCHAR(50)", "unique": true, "required": true},
        "email": {"type": "VARCHAR(255)", "unique": true, "required": true},
        "password_hash": {"type": "VARCHAR(255)", "required": true, "description": "bcrypt con coste 12"},
        "rol": {"type": "ENUM", "values": ["admin", "empleado", "contabilidad"], "required": true},
        "activo": {"type": "BOOLEAN", "default": true},
        "require_password_change": {"type": "BOOLEAN", "default": true},
        "last_login": {"type": "TIMESTAMP", "required": false},
        "created_at": {"type": "TIMESTAMP", "default": "CURRENT_TIMESTAMP"},
        "updated_at": {"type": "TIMESTAMP", "on_update": "CURRENT_TIMESTAMP"}
      },
      "indexes": ["username", "email", "rol", "activo"],
      "relations": {
        "has_one": ["employee"]
      }
    },
    "audit_log": {
      "table": "audit_log",
      "fields": {
        "id": {"type": "BIGINT", "primary": true, "auto_increment": true},
        "timestamp": {"type": "TIMESTAMP", "default": "CURRENT_TIMESTAMP"},
        "user_id": {"type": "INT", "foreign_key": "users.id", "required": false},
        "role": {"type": "VARCHAR(50)", "required": false},
        "action": {"type": "VARCHAR(50)", "required": true, "description": "CREATE, UPDATE, DELETE, SIGN, SEND, LOGIN, etc."},
        "entity": {"type": "VARCHAR(50)", "required": true, "description": "Vehicle, Invoice, Cut, etc."},
        "entity_id": {"type": "INT", "required": true},
        "changes": {"type": "JSON", "required": false, "description": "Diferencial antes/después"},
        "ip_address": {"type": "VARCHAR(45)", "required": false},
        "metadata": {"type": "JSON", "required": false, "description": "Contexto adicional"}
      },
      "indexes": ["timestamp", "user_id", "action", "entity"],
      "immutable_after_insert": true
    },
    "email_log": {
      "table": "email_log",
      "fields": {
        "id": {"type": "BIGINT", "primary": true, "auto_increment": true},
        "inspection_id": {"type": "INT", "foreign_key": "inspections.id", "required": false},
        "cut_id": {"type": "INT", "foreign_key": "cuts.id", "required": false},
        "recipient": {"type": "VARCHAR(255)", "required": true},
        "cc": {"type": "VARCHAR(255)", "required": false},
        "subject": {"type": "VARCHAR(255)", "required": true},
        "attachments": {"type": "JSON", "required": false, "description": "Array de paths de PDFs adjuntos"},
        "sent_at": {"type": "TIMESTAMP", "default": "CURRENT_TIMESTAMP"},
        "status": {"type": "ENUM", "values": ["sent", "failed", "retrying"], "default": "sent"},
        "error_message": {"type": "TEXT", "required": false},
        "retry_count": {"type": "INT", "default": 0}
      },
      "indexes": ["sent_at", "status", "recipient"]
    }
  },
  "workflow": {
    "states": {
      "draft": {
        "label": {"es": "Borrador", "en": "Draft"},
        "color": "#ffc107",
        "description": "Inspección registrada, sin aprobación",
        "trigger": "employee_save_inspection",
        "visible_to_employee": true,
        "actions_available": ["edit", "delete", "request_approval", "generate_inspection_format"]
      },
      "pending_approval": {
        "label": {"es": "Por Firmar (Inicial)", "en": "Pending Signature (Initial)"},
        "color": "#fd7e14",
        "description": "Esperando firma de aprobación en Canvas",
        "trigger": "employee_request_approval",
        "visible_to_employee": false,
        "actions_available": []
      },
      "approved": {
        "label": {"es": "Aprobado", "en": "Approved"},
        "color": "#198754",
        "description": "Firma inicial capturada, trabajo autorizado",
        "trigger": "manager_signs_initial_canvas",
        "visible_to_employee": false,
        "actions_available": ["start_repair"],
        "auto_transition": true
      },
      "in_progress": {
        "label": {"es": "En Proceso", "en": "In Progress"},
        "color": "#0dcaf0",
        "description": "Reparación en ejecución",
        "trigger": "system_after_approved",
        "visible_to_employee": false,
        "actions_available": ["mark_completed"]
      },
      "completed": {
        "label": {"es": "Completado", "en": "Completed"},
        "color": "#6f42c1",
        "description": "Trabajo finalizado, pendiente de validación final",
        "trigger": "employee_mark_ready",
        "visible_to_employee": true,
        "actions_available": ["request_final_signature", "generate_completion_format"]
      },
      "validated": {
        "label": {"es": "Validado", "en": "Validated"},
        "color": "#20c997",
        "description": "Firma final capturada, listo para enviar",
        "trigger": "manager_signs_final_canvas",
        "visible_to_employee": false,
        "actions_available": ["enable_send_button"],
        "auto_transition": true,
        "enables_send": true
      },
      "sent": {
        "label": {"es": "Enviado", "en": "Sent"},
        "color": "#0d6efd",
        "description": "Prefacturas enviadas por correo",
        "trigger": "employee_clicks_send_batch",
        "visible_to_employee": false,
        "actions_available": [],
        "immutable": true
      },
      "invoiced": {
        "label": {"es": "Facturado", "en": "Invoiced"},
        "color": "#6610f2",
        "description": "Incluido en corte y factura oficial generada",
        "trigger": "admin_includes_in_cut",
        "visible_to_employee": false,
        "actions_available": []
      },
      "paid": {
        "label": {"es": "Pagado", "en": "Paid"},
        "color": "#198754",
        "description": "Pago recibido y conciliado",
        "trigger": "accounting_marks_paid",
        "visible_to_employee": false,
        "actions_available": [],
        "immutable": true
      }
    },
    "transitions": [
      {"from": "draft", "to": "pending_approval", "action": "request_approval", "actor": "employee"},
      {"from": "pending_approval", "to": "approved", "action": "sign_initial_canvas", "actor": "manager", "auto": true},
      {"from": "approved", "to": "in_progress", "action": "system_auto", "actor": "system", "auto": true},
      {"from": "in_progress", "to": "completed", "action": "mark_completed", "actor": "employee"},
      {"from": "completed", "to": "validated", "action": "sign_final_canvas", "actor": "manager", "auto": true},
      {"from": "validated", "to": "sent", "action": "send_prefactura_batch", "actor": "employee"},
      {"from": "sent", "to": "invoiced", "action": "include_in_cut", "actor": "admin"},
      {"from": "invoiced", "to": "paid", "action": "mark_paid", "actor": "accounting"}
    ],
    "exceptions": {
      "pre_approved_vehicles": {
        "description": "Vehículos con pre_aprobado=true saltan firma inicial",
        "skip_states": ["pending_approval"],
        "direct_transition": {"from": "draft", "to": "approved"}
      }
    }
  },
  "digital_signatures": {
    "canvas": {
      "library": "signature_pad.js",
      "output_format": "PNG",
      "storage": "base64_in_db_or_file_path",
      "max_size_kb": 500,
      "background_color": "#ffffff",
      "pen_color": "#000000",
      "pen_width": 2,
      "clear_button": true,
      "undo_support": false
    },
    "initial_canvas": {
      "trigger_state": "pending_approval",
      "display_data": ["vehicle_info", "inspection_items_summary", "estimated_cost", "estimated_time"],
      "on_sign_callback": "update_inspection_state_to_approved",
      "save_fields": ["firma_inicial_png", "firma_inicial_timestamp"]
    },
    "final_canvas": {
      "trigger_state": "completed",
      "display_data": ["vehicle_info", "executed_services", "real_time", "final_cost", "materials_used"],
      "on_sign_callback": "update_inspection_state_to_validated_and_enable_send",
      "save_fields": ["firma_final_png", "firma_final_timestamp"]
    },
    "pdf_generation": {
      "library": "TCPDF or FPDI",
      "template": "official_jfd_format",
      "embed_signatures": true,
      "signature_position": {"initial": "bottom_left", "final": "bottom_right"},
      "file_naming": "JFD_{dealer}_{vin}_{date}.pdf",
      "include_metadata": ["generated_at", "generated_by", "inspection_id"]
    }
  },
  "batch_processing": {
    "enabled": true,
    "max_batch_size": 20,
    "ui": {
      "selection_method": "checkboxes_in_list_view",
      "modal_type": "sequential_canvas",
      "auto_advance": true,
      "progress_indicator": true,
      "skip_option": false
    },
    "initial_approval_batch": {
      "endpoint": "/api/batch/request-approval",
      "payload": {"inspection_ids": "array_of_ints"},
      "response": {"signed_count": "int", "failed_count": "int", "details": "array"}
    },
    "final_signature_batch": {
      "endpoint": "/api/batch/request-final-signature",
      "payload": {"inspection_ids": "array_of_ints"},
      "response": {"validated_count": "int", "enabled_send": "boolean"}
    },
    "send_consolidated": {
      "endpoint": "/api/batch/send-prefacturas",
      "payload": {"inspection_ids": "array_of_ints", "force_individual_emails": "boolean"},
      "email_logic": {
        "single_email": true,
        "max_attachments": 20,
        "split_if_exceeds": true,
        "recipient": "dealer.correo_contabilidad",
        "cc": "global_admin_email",
        "subject_template": "Prefacturas JFD Auto Care - {dealer} - {date}",
        "body_template": "summary_with_totals_and_period",
        "attachment_per_vehicle": true,
        "attachment_naming": "JFD_{dealer}_{vin}_{date}.pdf"
      }
    }
  },
  "billing": {
    "cut_types": {
      "reparaciones": {"frequency": "monthly", "trigger_day": 1, "trigger_time": "00:00"},
      "limpieza": {"frequency": "weekly", "trigger_day": "monday", "trigger_time": "00:00"},
      "ambos": {"frequency": "both", "rules": "per_dealer_configuration"}
    },
    "calculation_rules": {
      "vehicle_total": "sum_of_executed_services_x_configured_price + manual_adjustments",
      "taxes": {"configurable": true, "default_percent": 0, "apply_to": "subtotal"},
      "discounts": {"admin_only": true, "require_reason": true, "max_percent": 50},
      "rounding": {"decimals": 2, "method": "half_up"}
    },
    "cut_generation_flow": [
      "system_groups_sent_invoices_by_dealer_and_period",
      "admin_reviews_draft_cut",
      "admin_confirms_cut",
      "system_generates_consolidated_pdf",
      "accounting_marks_as_paid",
      "system_closes_cycle"
    ],
    "pdf_structure": {
      "header": ["logo_jfd", "dealer_data", "period", "folio"],
      "summary": ["total_vehicles", "total_services", "gross_amount", "adjustments", "net_amount"],
      "detail_table": ["vin", "date", "services", "amount_per_vehicle"],
      "signatures_section": ["admin_signature_space", "accounting_signature_space"],
      "footer": ["banking_data", "payment_terms", "contact_info"]
    }
  },
  "dashboard": {
    "admin": {
      "widgets": [
        {"id": "vehicles_today", "title": {"es": "Vehículos hoy", "en": "Vehicles today"}, "metrics": ["inspections_count", "in_progress_count", "completed_count"], "refresh": "realtime"},
        {"id": "monthly_revenue", "title": {"es": "Ingresos del mes", "en": "Monthly revenue"}, "metrics": ["invoiced_amount", "pending_amount"], "refresh": "daily"},
        {"id": "employee_productivity", "title": {"es": "Productividad empleados", "en": "Employee productivity"}, "metrics": ["repairs_per_employee_weekly", "avg_time_per_service"], "refresh": "weekly"},
        {"id": "active_dealers", "title": {"es": "Dealers activos", "en": "Active dealers"}, "metrics": ["top_dealers_by_volume"], "refresh": "monthly"},
        {"id": "alerts", "title": {"es": "Alertas", "en": "Alerts"}, "metrics": ["approvals_pending_24h", "cuts_expiring_soon"], "refresh": "realtime"}
      ]
    },
    "employee": {
      "widgets": [
        {"id": "my_tasks_today", "title": {"es": "Mis tareas hoy", "en": "My tasks today"}, "metrics": ["assigned_vehicles_by_state"], "refresh": "realtime"},
        {"id": "avg_time", "title": {"es": "Tiempo promedio", "en": "Average time"}, "metrics": ["estimated_vs_real_per_service"], "refresh": "weekly"},
        {"id": "personal_history", "title": {"es": "Historial personal", "en": "Personal history"}, "metrics": ["completed_repairs_last_30_days"], "refresh": "daily"}
      ]
    },
    "accounting": {
      "widgets": [
        {"id": "pending_receivables", "title": {"es": "Por cobrar", "en": "Pending receivables"}, "metrics": ["pending_amount_by_dealer", "due_dates"], "refresh": "daily"},
        {"id": "pending_cuts", "title": {"es": "Cortes pendientes", "en": "Pending cuts"}, "metrics": ["generated_not_paid_count"], "refresh": "realtime"},
        {"id": "received_prefacturas", "title": {"es": "Prefacturas recibidas", "en": "Received prefacturas"}, "metrics": ["new_today_count", "links_to_detail"], "refresh": "realtime"}
      ]
    }
  },
  "reports": {
    "exportable": [
      {
        "id": "repair_detail",
        "name": {"es": "Detalle de Reparaciones", "en": "Repair Detail"},
        "filters": ["dealer_id", "employee_id", "date_range", "service_id", "state"],
        "columns": ["vin", "dealer", "employee", "service", "amount", "state", "date"],
        "formats": ["pdf", "excel", "csv"],
        "typical_frequency": "daily/weekly"
      },
      {
        "id": "cut_by_dealer",
        "name": {"es": "Corte por Dealer", "en": "Cut by Dealer"},
        "filters": ["period", "service_type"],
        "columns": ["dealer", "period", "total_vehicles", "total_amount", "state"],
        "formats": ["pdf", "excel"],
        "typical_frequency": "monthly/weekly"
      },
      {
        "id": "employee_productivity",
        "name": {"es": "Productividad por Empleado", "en": "Employee Productivity"},
        "filters": ["date_range", "dealer_id", "service_type"],
        "columns": ["employee", "repairs_count", "avg_time", "total_amount"],
        "formats": ["excel", "pdf"],
        "typical_frequency": "weekly/monthly"
      },
      {
        "id": "consolidated_revenue",
        "name": {"es": "Ingresos Consolidados", "en": "Consolidated Revenue"},
        "filters": ["period", "dealer_id", "service_id"],
        "columns": ["period", "dealer", "service", "gross", "taxes", "net"],
        "formats": ["excel", "pdf"],
        "typical_frequency": "monthly"
      },
      {
        "id": "email_log",
        "name": {"es": "Bitácora de Envíos", "en": "Email Log"},
        "filters": ["date_range", "dealer_id", "status"],
        "columns": ["sent_at", "recipient", "subject", "status", "retry_count"],
        "formats": ["csv", "pdf"],
        "typical_frequency": "on_demand"
      },
      {
        "id": "signature_audit",
        "name": {"es": "Auditoría de Firmas", "en": "Signature Audit"},
        "filters": ["vehicle_id", "date_range", "signature_type"],
        "columns": ["inspection_id", "vin", "signature_type", "signed_at", "signer_ip"],
        "formats": ["pdf", "csv"],
        "typical_frequency": "on_demand"
      }
    ],
    "global_filters": ["dealer_id", "employee_id", "date_range", "service_type", "vehicle_state", "invoice_state"],
    "export_options": {
      "pdf": {"use_case": "client_delivery, formal_printing, archiving"},
      "excel_csv": {"use_case": "spreadsheet_analysis, external_integration"},
      "json_api": {"use_case": "future_accounting_system_integration"}
    }
  },
  "notifications": {
    "channels": {
      "in_app": {
        "enabled": true,
        "persistent": true,
        "dismissible": true,
        "icon": "bell",
        "badge_count": true
      },
      "email": {
        "enabled": true,
        "configurable_by_role": true,
        "transactional_mandatory": ["approval_requests", "prefactura_sends", "cut_confirmations"]
      },
      "push_sms": {"enabled": false, "reason": "keep_simplicity"}
    },
    "events": {
      "inspection_saved": {
        "recipient": "employee",
        "channel": "in_app",
        "template": {"es": "✅ Inspección guardada. Listo para solicitar aprobación.", "en": "✅ Inspection saved. Ready to request approval."}
      },
      "approval_requested": {
        "recipient": "dealer_manager_external",
        "channel": "email",
        "template": {
          "subject": {"es": "Aprobación requerida - Vehículo {vin}", "en": "Approval required - Vehicle {vin}"},
          "body": "inspection_summary_with_secure_canvas_link",
          "canvas_embedded": true,
          "link_expiration_hours": 72,
          "token_unique": true
        }
      },
      "approval_captured": {
        "recipient": "employee",
        "channel": "in_app",
        "template": {"es": "✅ Vehículo {vin} aprobado. Puedes iniciar el trabajo.", "en": "✅ Vehicle {vin} approved. You can start work."}
      },
      "work_completed": {
        "recipient": "employee",
        "channel": "in_app",
        "template": {"es": "📋 Listo para solicitar firma final.", "en": "📋 Ready to request final signature."}
      },
      "final_signature_captured": {
        "recipient": "employee",
        "channel": "in_app",
        "template": {"es": "✅ Firma recibida. Botón 'Enviar' habilitado.", "en": "✅ Signature received. 'Send' button enabled."}
      },
      "prefacturas_sent": {
        "recipient": ["employee", "admin", "accounting"],
        "channel": ["email", "in_app"],
        "template": {
          "subject": {"es": "Prefacturas enviadas - {dealer} - {date}", "en": "Prefacturas sent - {dealer} - {date}"},
          "body": "confirmation_with_summary_and_pdf_links"
        }
      },
      "cut_generated": {
        "recipient": "admin",
        "channel": ["in_app", "email"],
        "template": {"es": "📄 Borrador de corte {dealer} listo para revisión.", "en": "📄 Cut draft {dealer} ready for review."}
      },
      "cut_confirmed": {
        "recipient": ["accounting", "admin"],
        "channel": "email",
        "template": {"subject": "Corte confirmado - {folio}", "body": "consolidated_pdf_with_portal_link"}
      },
      "cut_paid": {
        "recipient": ["admin", "accounting"],
        "channel": "in_app",
        "template": {"es": "💰 Corte {folio} conciliado y cerrado.", "en": "💰 Cut {folio} reconciled and closed."}
      }
    },
    "alerts": {
      "approval_pending_24h": {
        "recipient": "admin",
        "channels": ["in_app", "email"],
        "action_required": "Follow up with dealer"
      },
      "completed_no_final_signature_48h": {
        "recipient": "admin",
        "channels": ["in_app"],
        "action_required": "Reminder to employee"
      },
      "email_send_failed": {
        "recipient": ["admin", "responsible_employee"],
        "channels": ["in_app", "email"],
        "action_required": "Retry send"
      },
      "cut_expiring_3days": {
        "recipient": "admin",
        "channels": ["email"],
        "action_required": "Prepare documentation"
      }
    },
    "configuration": {
      "by_role": {
        "admin": {"can_disable_email": false, "can_silence_in_app": true, "summary_frequency": "optional_daily"},
        "employee": {"can_disable_email": true, "can_silence_in_app": true, "summary_frequency": "optional_weekly"},
        "accounting": {"can_disable_email": false, "can_silence_in_app": true, "summary_frequency": "optional_weekly"}
      },
      "by_dealer": {
        "manager_receives_only_transactional": true,
        "no_portal_access": true,
        "interactions_via_email_and_secure_link": true
      }
    }
  },
  "security": {
    "authentication": {
      "method": "username_password",
      "password_hash": {
        "algorithm": "PASSWORD_BCRYPT",
        "cost": 12,
        "reason": "100% compatible with cPanel shared hosting, no libargon2 required",
        "field_type": "VARCHAR(255)"
      },
      "session": {
        "type": "PHP_native_session",
        "cookie_lifetime": 28800,
        "cookie_secure": true,
        "cookie_httponly": true,
        "cookie_samesite": "Lax",
        "regenerate_on_login": true,
        "idle_timeout_minutes": 480
      },
      "failed_attempts": {
        "max": 5,
        "lockout_duration_minutes": 15,
        "notify_admin": true
      },
      "two_factor": {
        "required_for": ["admin"],
        "method": "TOTP",
        "optional_for": []
      }
    },
    "authorization": {
      "model": "RBAC",
      "enforcement": "middleware_per_route",
      "data_scope": {
        "employee": "assigned_dealers_only",
        "accounting": "financial_module_readonly",
        "admin": "global"
      }
    },
    "data_protection": {
      "in_transit": {
        "tls_version": "1.3",
        "force_https": true,
        "hsts_enabled": true
      },
      "at_rest": {
        "sensitive_fields_encrypted": ["signatures", "amounts", "contacts"],
        "encryption_algorithm": "AES-256",
        "key_management": "cPanel_encryption_or_env_variable"
      },
      "signatures_storage": {
        "method": "base64_in_db_or_encrypted_file",
        "immutable_after_sign": true,
        "linked_to_record": true
      },
      "backups": {
        "frequency": "daily",
        "retention_days": 90,
        "encrypted": true,
        "offsite": true,
        "rto_hours": 4,
        "rpo_hours": 1
      }
    },
    "audit": {
      "logged_events": [
        "LOGIN_SUCCESS", "LOGIN_FAILURE", "LOGOUT",
        "CREATE", "UPDATE", "DELETE",
        "SIGN_INITIAL", "SIGN_FINAL",
        "SEND_PREFACTURA", "GENERATE_CUT", "MARK_PAID",
        "EXPORT_REPORT", "CHANGE_PASSWORD", "IMPERSONATE"
      ],
      "log_structure": {
        "id": "BIGINT",
        "timestamp": "TIMESTAMP_UTC",
        "user_id": "INT_nullable",
        "role": "VARCHAR",
        "action": "ENUM",
        "entity": "VARCHAR",
        "entity_id": "INT",
        "changes": "JSON_nullable",
        "ip_address": "VARCHAR_45",
        "metadata": "JSON_nullable"
      },
      "access": {
        "full_log": ["admin"],
        "financial_events_only": ["accounting"],
        "export_formats": ["pdf", "csv"],
        "filters": ["date_range", "user_id", "action"]
      },
      "immutability_rules": {
        "post_signature": "inspection_data_readonly",
        "post_send": "invoice_data_readonly_credit_note_for_changes",
        "post_paid": "cut_readonly_adjustment_cut_for_corrections",
        "deletion": "logical_only_deleted_at_timestamp"
      }
    },
    "incident_response": {
      "unauthorized_access": {
        "auto_actions": ["block_session", "invalidate_tokens"],
        "notifications": ["admin_email", "admin_in_app"]
      },
      "email_send_failures": {
        "auto_actions": ["exponential_retry", "alert"],
        "notifications": ["admin", "responsible_employee"]
      },
      "post_signature_edit_attempt": {
        "auto_actions": ["reject_operation", "log_attempt"],
        "notifications": ["admin"]
      },
      "server_downtime": {
        "auto_actions": ["failover_to_backup"],
        "notifications": ["admin_sms", "admin_external_email"]
      }
    }
  },
  "technical_stack": {
    "backend": {
      "language": "PHP",
      "version_min": "8.2",
      "version_recommended": "8.3",
      "pattern": "MVC_lightweight",
      "routing": "static_routes_based",
      "autoloading": "PSR-4_simplified",
      "sessions": "native_PHP_files_or_DB",
      "no_microservices": true,
      "reason": "cPanel_process_limits"
    },
    "frontend": {
      "html": "HTML5",
      "css": "CSS3_with_variables_and_backdrop_filter",
      "javascript": "Vanilla_ES6+",
      "framework": "Bootstrap_5.3",
      "build_step": "none_cPanel_friendly",
      "canvas_library": "signature_pad.js_lightweight"
    },
    "database": {
      "engine": "MySQL_8_or_MariaDB_10.6",
      "connection": "PDO_with_persistent_false",
      "charset": "utf8mb4",
      "indexes": "optimized_for_VIN_date_state_queries",
      "migrations": "manual_SQL_scripts_or_simple_php_runner"
    },
    "pdf_generation": {
      "library": "TCPDF_or_FPDI",
      "method": "in_memory_generation",
      "no_external_services": true,
      "embed_fonts": true,
      "embed_images": true
    },
    "email": {
      "library": "PHPMailer",
      "transport": "SMTP_cPanel_or_mail_function",
      "authentication": "host_credentials",
      "attachments": "multiple_PDFs_consolidated",
      "retry_logic": "exponential_backoff_max_3"
    },
    "scheduled_tasks": {
      "mechanism": "cPanel_cron_jobs",
      "frequency_examples": {
        "weekly_cut": "0 0 * * 1",
        "monthly_cut": "0 0 1 * *",
        "backup": "0 2 * * *",
        "cleanup_temp": "0 3 * * *"
      },
      "lock_file": true,
      "log_output": true
    },
    "file_structure": {
      "root": "/home2/jfdautoc/portal.jfdautocare.com",
      "directories": {
        "app/Config": ["App.php", "Database.php", "Language.php"],
        "app/Controllers": ["BaseController.php", "AuthController.php", "DashboardController.php", "DealersController.php", "EmployeesController.php", "VehiclesController.php", "InspectionsController.php", "RepairsController.php", "InvoicesController.php", "CutsController.php", "ReportsController.php"],
        "app/Models": ["User.php", "Dealer.php", "Employee.php", "Vehicle.php", "Inspection.php", "InspectionItem.php", "Repair.php", "Invoice.php", "Cut.php", "Service.php", "AuditLog.php", "EmailLog.php"],
        "app/Views/layouts": ["header.php", "footer.php", "sidebar.php"],
        "app/Views/auth": ["login.php", "cambiar_password.php"],
        "app/Views/dashboard": ["admin.php", "employee.php", "accounting.php"],
        "app/Views/dealers": ["index.php", "create.php", "edit.php"],
        "app/Views/employees": ["index.php", "create.php", "edit.php", "assign_dealers.php"],
        "app/Views/vehicles": ["index.php", "create.php", "edit.php"],
        "app/Views/inspections": ["create.php", "show.php", "request_approval.php", "signature_canvas.php"],
        "app/Views/repairs": ["execute.php", "mark_complete.php"],
        "app/Views/invoices": ["draft.php", "preview.php"],
        "app/Views/cuts": ["generate.php", "show.php"],
        "app/Views/reports": ["index.php", "export.php"],
        "app/Helpers": ["functions.php", "PDFGenerator.php", "EmailSender.php", "CanvasHandler.php"],
        "app/Middleware": ["Auth.php", "RoleCheck.php", "Audit.php", "CSRF.php"],
        "public": [".htaccess", "index.php"],
        "public/assets/css": ["app.css", "glassmorphism.css", "canvas.css"],
        "public/assets/js": ["app.js", "canvas-handler.js", "batch-processor.js", "lang-switcher.js"],
        "public/assets/img/logos": ["jfd-logo.png"],
        "storage/logs": [".gitkeep"],
        "storage/pdfs": [".gitkeep"],
        "storage/firmas": [".gitkeep"],
        "storage/temp": [".gitkeep"],
        "storage/cache": [".gitkeep"]
      }
    },
    "htaccess_rules": {
      "root": [
        "RewriteEngine On",
        "RewriteRule ^app/ - [F,L]",
        "RewriteRule ^storage/ - [F,L]",
        "RewriteCond %{REQUEST_URI} !^/public/",
        "RewriteCond %{REQUEST_FILENAME} !-f",
        "RewriteCond %{REQUEST_FILENAME} !-d",
        "RewriteRule ^(.*)$ public/$1 [L,QSA]",
        "Options -Indexes",
        "Header set X-Frame-Options SAMEORIGIN",
        "Header set X-Content-Type-Options nosniff"
      ],
      "public": [
        "RewriteEngine On",
        "RewriteCond %{REQUEST_FILENAME} -f [OR]",
        "RewriteCond %{REQUEST_FILENAME} -d",
        "RewriteRule ^ - [L]",
        "RewriteRule ^ index.php [QSA,L]"
      ]
    }
  },
  "deployment": {
    "strategy": "subdomain_isolation",
    "main_domain": "www.jfdautocare.com",
    "subdomain": "portal.jfdautocare.com",
    "document_root": "/home2/jfdautoc/portal.jfdautocare.com",
    "wordpress_integration": {
      "method": "external_link_button",
      "button_text": {"es": "Portal JFD", "en": "JFD Portal"},
      "button_style": "match_brand_colors",
      "placement_options": ["main_menu_widget", "shortcode_jfd_portal_button", "theme_header_hook"],
      "no_shared_code": true,
      "no_shared_database": true
    },
    "isolation_benefits": [
      "WordPress updates do not affect portal",
      "Portal deployment does not touch WordPress",
      "Security breach in one does not compromise the other",
      "Independent performance and scaling",
      "Separate backups and maintenance windows"
    ],
    "cpanel_setup_steps": [
      "Create subdomain portal.jfdautocare.com → point to /home2/jfdautoc/portal.jfdautocare.com",
      "Force HTTPS via .htaccess redirect 301",
      "Create database jfdautoc_jfdautoc_portal with limited-privilege user",
      "Upload project files via FTP/SFTP or File Manager",
      "Configure .env with production credentials",
      "Set folder permissions: 755 for directories, 644 for files",
      "Create cron jobs for weekly/monthly cuts and backups",
      "Configure email to use info@jfdautocare.com as sender via SMTP",
      "Test login and digital signature flow",
      "Delete installation/debug scripts"
    ]
  },
  "initial_users": [
    {
      "username": "francis",
      "nombre_completo": "Francis",
      "email": "francis@jfdautocare.com",
      "password_plain": "Admin123",
      "password_hash_bcrypt_cost12": "$2y$12$GENERATED_HASH_HERE",
      "rol": "admin",
      "activo": true,
      "require_password_change": true,
      "seed_order": 1
    },
    {
      "username": "juan",
      "nombre_completo": "Juan",
      "email": "juan@jfdautocare.com",
      "password_plain": "Admin123",
      "password_hash_bcrypt_cost12": "$2y$12$GENERATED_HASH_HERE",
      "rol": "admin",
      "activo": true,
      "require_password_change": true,
      "seed_order": 2
    }
  ],
  "design": {
    "visual_style": "glassmorphism",
    "css_variables": {
      "--glass-bg": "rgba(255, 255, 255, 0.1)",
      "--glass-border": "rgba(255, 255, 255, 0.2)",
      "--glass-shadow": "0 8px 32px 0 rgba(31, 38, 135, 0.37)",
      "--primary-glow": "rgba(13, 110, 253, 0.5)",
      "--bg-gradient": "linear-gradient(135deg, #0f0f23 0%, #1a1a3a 50%, #0f0f23 100%)"
    },
    "typography": {
      "font_family": "system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif",
      "base_size": "16px",
      "scale": {"h1": "2rem", "h2": "1.5rem", "h3": "1.25rem", "body": "1rem", "small": "0.875rem"}
    },
    "colors": {
      "primary": "#0d6efd",
      "success": "#198754",
      "warning": "#ffc107",
      "danger": "#dc3545",
      "info": "#0dcaf0",
      "text_primary": "#ffffff",
      "text_secondary": "rgba(255,255,255,0.75)",
      "background": "#0f0f23"
    },
    "bilingual": {
      "supported_locales": ["es", "en"],
      "default_locale": "es",
      "persistence": "localStorage",
      "translation_method": "centralized_Language_class_with_dot_notation",
      "fallback_chain": ["selected_locale", "en", "key_as_fallback"]
    },
    "branding": {
      "logo_url": "https://jfdautocare.com/wp-content/uploads/2025/02/cropped-lOGO-JDF-AUTO-CARE-sin-fonodo-letras-azules-512-X-512.png",
      "logo_max_height": "70px",
      "logo_filter": "drop-shadow(0 4px 8px rgba(0,0,0,0.3))",
      "brand_colors_match_wordpress": true
    },
    "responsive": {
      "breakpoints": {"mobile": "320px", "tablet": "768px", "desktop": "1024px"},
      "canvas_touch_optimized": true,
      "mobile_first_css": true
    }
  },
  "api_endpoints": {
    "auth": {
      "POST /api/auth/login": {"description": "Authenticate user", "request": {"username": "string", "password": "string"}, "response": {"token": "string", "user": "object", "require_password_change": "boolean"}},
      "POST /api/auth/logout": {"description": "End session", "auth_required": true},
      "POST /api/auth/change-password": {"description": "Update password", "auth_required": true, "request": {"current": "string", "new": "string", "confirm": "string"}}
    },
    "inspections": {
      "GET /api/inspections": {"description": "List inspections (filtered by role)", "auth_required": true, "params": {"dealer_id", "employee_id", "state", "date_range"}},
      "POST /api/inspections": {"description": "Create new inspection", "auth_required": true, "role": ["employee"], "request": {"vehicle_id", "items": "array"}},
      "GET /api/inspections/{id}": {"description": "Get inspection detail", "auth_required": true},
      "PUT /api/inspections/{id}": {"description": "Update inspection (draft only)", "auth_required": true, "role": ["employee"]},
      "POST /api/inspections/{id}/request-approval": {"description": "Request initial signature", "auth_required": true, "role": ["employee"]},
      "POST /api/inspections/{id}/sign-initial": {"description": "Capture initial canvas signature", "auth_required": false, "token_required": true, "request": {"signature_png_base64": "string"}},
      "POST /api/inspections/{id}/request-final-signature": {"description": "Request final signature", "auth_required": true, "role": ["employee"]},
      "POST /api/inspections/{id}/sign-final": {"description": "Capture final canvas signature", "auth_required": false, "token_required": true, "request": {"signature_png_base64": "string"}},
      "GET /api/inspections/{id}/pdf": {"description": "Generate/download PDF with signatures", "auth_required": true}
    },
    "batch": {
      "POST /api/batch/request-approval": {"description": "Request approval for multiple inspections", "auth_required": true, "role": ["employee"], "request": {"inspection_ids": "array"}},
      "POST /api/batch/request-final-signature": {"description": "Request final signature for multiple inspections", "auth_required": true, "role": ["employee"], "request": {"inspection_ids": "array"}},
      "POST /api/batch/send-prefacturas": {"description": "Send consolidated prefacturas email", "auth_required": true, "role": ["employee"], "request": {"inspection_ids": "array"}}
    },
    "dealers": {
      "GET /api/dealers": {"description": "List dealers", "auth_required": true},
      "POST /api/dealers": {"description": "Create dealer", "auth_required": true, "role": ["admin"]},
      "GET /api/dealers/{id}": {"description": "Get dealer detail", "auth_required": true},
      "PUT /api/dealers/{id}": {"description": "Update dealer", "auth_required": true, "role": ["admin"]},
      "GET /api/dealers/{id}/employees": {"description": "List assigned employees", "auth_required": true}
    },
    "employees": {
      "GET /api/employees": {"description": "List employees", "auth_required": true, "role": ["admin"]},
      "POST /api/employees": {"description": "Create employee", "auth_required": true, "role": ["admin"]},
      "PUT /api/employees/{id}": {"description": "Update employee", "auth_required": true, "role": ["admin"]},
      "POST /api/employees/{id}/assign-dealers": {"description": "Assign dealers to employee", "auth_required": true, "role": ["admin"], "request": {"dealer_ids": "array"}}
    },
    "vehicles": {
      "GET /api/vehicles": {"description": "List vehicles", "auth_required": true, "params": {"dealer_id", "vin", "placa"}},
      "POST /api/vehicles": {"description": "Register vehicle", "auth_required": true, "role": ["admin", "employee"]},
      "PUT /api/vehicles/{id}": {"description": "Update vehicle", "auth_required": true}
    },
    "invoices": {
      "GET /api/invoices": {"description": "List invoices", "auth_required": true, "role": ["admin", "accounting"]},
      "GET /api/invoices/{id}": {"description": "Get invoice detail", "auth_required": true},
      "POST /api/invoices/{id}/send": {"description": "Send invoice email", "auth_required": true, "role": ["admin"]},
      "GET /api/invoices/{id}/pdf": {"description": "Download invoice PDF", "auth_required": true}
    },
    "cuts": {
      "GET /api/cuts": {"description": "List cuts", "auth_required": true, "role": ["admin", "accounting"]},
      "POST /api/cuts/generate": {"description": "Generate draft cut", "auth_required": true, "role": ["admin"], "request": {"dealer_id", "period_start", "period_end"}},
      "POST /api/cuts/{id}/confirm": {"description": "Confirm cut", "auth_required": true, "role": ["admin"]},
      "POST /api/cuts/{id}/mark-paid": {"description": "Mark cut as paid", "auth_required": true, "role": ["accounting"]},
      "GET /api/cuts/{id}/pdf": {"description": "Download cut PDF", "auth_required": true}
    },
    "reports": {
      "GET /api/reports/repair-detail": {"description": "Export repair detail report", "auth_required": true, "params": {"format": "pdf|excel|csv"}},
      "GET /api/reports/cut-by-dealer": {"description": "Export cut report", "auth_required": true},
      "GET /api/reports/employee-productivity": {"description": "Export productivity report", "auth_required": true},
      "GET /api/reports/revenue": {"description": "Export revenue report", "auth_required": true, "role": ["admin", "accounting"]},
      "GET /api/reports/email-log": {"description": "Export email log", "auth_required": true},
      "GET /api/reports/signature-audit": {"description": "Export signature audit", "auth_required": true, "role": ["admin"]}
    },
    "config": {
      "GET /api/config/services": {"description": "Get configurable services catalog", "auth_required": true},
      "POST /api/config/services": {"description": "Create service", "auth_required": true, "role": ["admin"]},
      "PUT /api/config/services/{id}": {"description": "Update service", "auth_required": true, "role": ["admin"]},
      "GET /api/config/prices/{dealer_id}": {"description": "Get prices for dealer (with overrides)", "auth_required": true}
    }
  },
  "environment_variables": {
    ".env_example": "DB_HOST=localhost\nDB_NAME=jfdautoc_jfdautoc_portal\nDB_USER=jfdautoc_jfdautoc_portal_user\nDB_PASS=your_secure_password\nAPP_NAME=JFD Auto Care Portal\nAPP_URL=https://portal.jfdautocare.com\nAPP_TIMEZONE=America/Caracas\nAPP_DEBUG=false\nAPP_LOCALE=es\nMAIL_HOST=localhost\nMAIL_PORT=587\nMAIL_USERNAME=info@jfdautocare.com\nMAIL_PASSWORD=\nMAIL_FROM_ADDRESS=info@jfdautocare.com\nMAIL_FROM_NAME=JFD Auto Care Portal\nMAIL_ENCRYPTION=tls\nBCRYPT_COST=12\nSESSION_LIFETIME=480\nSESSION_SECURE=true\nSESSION_HTTPONLY=true\nSESSION_SAMESITE=Lax\nSTORAGE_PATH=../storage\nPDF_STORAGE_PATH=../storage/pdfs\nSIGNATURE_STORAGE_PATH=../storage/firmas\nFEATURE_BATCH_MODE=true\nFEATURE_EMAIL_NOTIFICATIONS=true\nFEATURE_AUDIT_LOG=true\nGLOBAL_ADMIN_EMAIL=admin@jfdautocare.com"
  },
  "implementation_phases": {
    "phase_1_core": {
      "name": "Core Foundation",
      "deliverables": [
        "Login/Logout with bcrypt passwords",
        "Password change on first login",
        "Dashboard basic structure per role",
        "Dealer CRUD (Admin)",
        "Employee CRUD + assignment to dealers (Admin)",
        "Vehicle registration",
        "Service catalog configuration (Admin)",
        "Basic glassmorphism UI + bilingual selector"
      ],
      "estimated_weeks": 2,
      "acceptance_criteria": [
        "Admin can create dealer and employee",
        "Employee can login and see assigned dealers",
        "Vehicle can be registered with VIN uniqueness",
        "Services can be configured with prices",
        "UI displays correctly in ES/EN with glassmorphism"
      ]
    },
    "phase_2_operational": {
      "name": "Inspections & Digital Signatures",
      "deliverables": [
        "Inspection creation form with damage items",
        "Canvas signature integration (initial and final)",
        "PDF generation with embedded signatures",
        "State machine automation (draft→approved→completed→validated)",
        "Pre-approved vehicles exception logic",
        "Batch processing UI for multiple vehicles"
      ],
      "estimated_weeks": 3,
      "acceptance_criteria": [
        "Employee can create inspection and request approval",
        "Manager can sign via canvas link (external email)",
        "System auto-transitions states after signatures",
        "PDF includes both signatures in correct positions",
        "Batch mode processes 5+ vehicles in <2 minutes"
      ]
    },
    "phase_3_financial": {
      "name": "Billing & Cuts",
      "deliverables": [
        "Prefactura generation per vehicle",
        "Consolidated email sending with multiple PDFs",
        "Cut generation (weekly/monthly) per dealer type",
        "Invoice PDF with official format",
        "Payment marking and closure",
        "Financial reports export (Excel/PDF)"
      ],
      "estimated_weeks": 2,
      "acceptance_criteria": [
        "Employee can send consolidated prefacturas email",
        "Admin can generate and confirm cuts",
        "Accounting can mark cuts as paid",
        "Reports export with correct filters and formatting",
        "Email logs track all sends with retry logic"
      ]
    },
    "phase_4_optimization": {
      "name": "Notifications, Audit & Polish",
      "deliverables": [
        "In-app notifications system",
        "Email templates for all transactional events",
        "Audit log implementation with immutable records",
        "Advanced report filters and scheduling",
        "Performance optimization (indexes, caching)",
        "Security hardening (headers, CSP, rate limiting)"
      ],
      "estimated_weeks": 2,
      "acceptance_criteria": [
        "All critical events trigger appropriate notifications",
        "Audit log captures all defined actions with full context",
        "Reports load <3s with 10k+ records",
        "Security headers pass Mozilla Observatory B+ minimum",
        "System handles 50 concurrent users without degradation"
      ]
    }
  },
  "testing": {
    "unit_tests": {
      "framework": "PHPUnit_9_or_native_assertions",
      "coverage_target": "80%",
      "critical_paths": [
        "password_hash_and_verify",
        "state_transitions",
        "price_calculations",
        "pdf_generation_with_signatures",
        "email_consolidation_logic"
      ]
    },
    "integration_tests": {
      "database": "test_db_with_sample_data",
      "email": "mock_PHPMailer_or_test_SMTP",
      "canvas": "headless_browser_signature_simulation"
    },
    "user_acceptance": {
      "scenarios": [
        "Admin creates dealer → employee → vehicle → inspection → approval flow → signature → send prefactura → cut generation",
        "Employee processes batch of 5 vehicles end-to-end",
        "Accounting receives email, marks cut as paid, exports report",
        "Bilingual toggle persists across pages and sessions",
        "Glassmorphism UI renders correctly on mobile/tablet/desktop"
      ]
    }
  },
  "maintenance": {
    "monitoring": {
      "error_logging": "storage/logs/app_YYYY-MM-DD.log",
      "performance_metrics": "simple_timing_wrapper_around_critical_queries",
      "uptime_check": "external_ping_or_cpanel_monitor"
    },
    "updates": {
      "php_version": "test_in_staging_subdomain_before_production",
      "dependency_updates": "manual_review_of_TCPDF_PHPMailer_signature_pad",
      "backup_verification": "monthly_restore_test_to_staging"
    },
    "documentation": {
      "internal": "README.md_with_setup_steps_and_troubleshooting",
      "user_guides": "PDF_manuals_for_Admin_Employee_Accounting_roles",
      "api_docs": "simple_markdown_with_endpoint_examples"
    }
  },
  "constraints_and_exclusions": {
    "no_multimedia": "No photo/video upload or management. All inspections are text/dropdown/structured data only.",
    "no_external_apis": "No third-party services for signatures, PDF, or email. All in-house with cPanel-compatible libraries.",
    "no_real_time_websockets": "Polling or page refresh for status updates only, due to cPanel shared hosting limitations.",
    "no_complex_queue_system": "Cron jobs replace background workers for scheduled tasks.",
    "no_advanced_search": "Basic filters only, no Elasticsearch or full-text search due to hosting constraints."
  },
  "success_metrics": {
    "operational": [
      "Time to create inspection: <2 minutes",
      "Time to process batch of 5 vehicles: <5 minutes",
      "Email delivery success rate: >99%",
      "PDF generation time: <10 seconds per document"
    ],
    "business": [
      "Reduction in manual paperwork: 100% digital",
      "Time from work completion to prefactura send: <1 hour",
      "Cut generation time: <5 minutes for monthly cycle",
      "User satisfaction score: >4.5/5 in post-launch survey"
    ],
    "technical": [
      "Page load time: <2s on 3G connection",
      "Zero critical security vulnerabilities in first 90 days",
      "99.5% uptime during business hours",
      "Successful recovery from backup within RTO (4 hours)"
    ]
  }
}