
-- Legacy Leave Management modal is stored in the modules table for PostgreSQL
INSERT INTO modules (module_id, name, config, org_id, branch_id, icon, aria_label, description) VALUES (
  '442d22f0-a2c9-4b29-a741-ce90111ccfa4'::uuid,
  'leave_management',
  '{"title":
    "Leave Management",
    "modulePath":"modules/leave/leaveManagement",
    
  "header":[
    {"type":
      "button",
      "label":"Apply for Leave",
      "formId":1
    },
    
    {"type":"filter-select",
      "options":{
        "data_column":"status",
      
      "options":[
        {"label":"All",
        "value":""
        },
        
    {"label":"Pending",
      "value":"Pending"
    },
    
    {"label":"Approved",
      "value":"Approved"
    },
      
    {"label":"Rejected",
      "value":"Rejected"
    }
      ]
        }
          },
          
    {"type":
      "filter-date-range",
    
    "options":{
      "data_column":"startdate"
    }
      }
        ],
        
    "body":[
      {"type":
        "table",
        "id":"leaveRequestsTable",
        "options":{"tableName":"leave_requests",

        "columnsToShow":
          ["leavetype",
            "startdate",
            "enddate",
            "reason",
            "status",
            "approvedAt",
            "approvedBy",
            "user_name"
          ],

        "columnLabels":
          {"leavetype":
            "Type",
            "startdate":"Start Date",
            "enddate":"End Date",
            "reason":"Reason",
            "status":"Status"
          },
          
        "showGlobalSearch":false,
          "rowActions":[
            {"label":"Approve",
              "type":"Confirm",
              "prompt":"Do you want to Approve the Leave",
              "columns":{
                "status":"approved"
              }
            }
              ]
                }
                  }
                    ],
                    
          "footer":[
            {"type":
                "button",
                "label":"Close",
                "onClick":"closeModal"
            }
              ]
                }'::jsonb,
  NULL,
  NULL,
  'fa-calendar-check',
  'Leave Management',
  'Leave Requests'
);


-- My Leave module for employees to apply and view their own leave requests
INSERT INTO modules (module_id, name, config, org_id, branch_id, icon, aria_label, description) VALUES (
  '442d22f0-a2c9-4b29-a741-ce90111ccfa5'::uuid,
  'my_leave',
  '{"title":
    "My Leave",
    "modulePath":"modules/leave/myLeave",
    
  "header":[
    {"type":
      "button",
      "label":"Apply",
      "formId":1,
      "class":"btn btn-primary"
    },
    
    {"type":"filter-select",
      "options":{
        "data_column":"status",
      
      "options":[
        {"label":"All",
        "value":""
        },
        
    {"label":"Pending",
      "value":"Pending"
    },
    
    {"label":"Approved",
      "value":"Approved"
    },
      
    {"label":"Rejected",
      "value":"Rejected"
    }
      ]
        }
          },
          
    {"type":
      "filter-date-range",
    
    "options":{
      "data_column":"startdate"
    }
      }
        ],
        
    "body":[
      {"type":
        "table",
        "id":"myLeaveRequestsTable",
        "options":{
          "tableName":"leave_requests",
          "scope":"user",
          "userField":"employee_id",

        "columnLabels":
          {"leavetype":
            "Type",
            "startdate":"Start Date",
            "enddate":"End Date",
            "reason":"Reason",
            "status":"Status"
          },
          
        "showGlobalSearch":false,
        "addButton":false,
        "rowClick":"selectRecord"
                }
                  }
                    ],
                    
          "footer":[
            {"type":
                "button",
                "label":"Close",
                "onClick":"closeModal"
            }
              ]
                }'::jsonb,
  NULL,
  NULL,
  'fa-calendar-days',
  'My Leave',
  'Apply for leave and view your leave requests'
);


-- RFQ Approval Levels module definition
INSERT INTO modules (module_id, name, config, org_id, branch_id, icon, aria_label, description)
SELECT
  'c6d16f2c-4c20-42f7-a637-07f683e4e4d1'::uuid,
  'RfqApprovalLevels',
  '{"title":"RFQ Approval Levels","modulePath":"modules/rfqapprovallevels"}'::jsonb,
  NULL,
  NULL,
  'fa-scale-balanced',
  'RFQ Approval Levels',
  'Configure approval thresholds for RFQ approvers'
WHERE NOT EXISTS (
  SELECT 1 FROM modules WHERE name = 'RfqApprovalLevels'
);


INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES (
  'Vehicles',
  '{"title":"Vehicles","header":[{"type":"button","label":"Add Vehicle","formName":"Vehicle Registration"}],"body":[{"type":"table","options":{"tableName":"vehicles","showGlobalSearch":false,"addButton":false,"editFormId":29}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-car',
  'Vehicles',
  'Vehicles'
);


-- Attendance modal
INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES (
  'Attendance',
  '{"title":"Attendance","body":[{"type":"table","options":{"tableName":"attendance","searchInputTypes":{"employee":"text","date":"date","timeIn":"time","timeOut":"time","timeInLat":"number","timeInLng":"number","timeOutLat":"number","timeOutLng":"number"},"columnsToShow":["employee","date","timeIn","timeOut","hoursWorked","overtime"]}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-user-check',
  'Attendance',
  'Attendance'
);

-- Attendance Dashboard modal
INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES (
  'Attendance Dashboard',
  '{"title":"Attendance Dashboard","body":[{"type":"html","id":"attendanceDash","html":"<div class=\"grid grid-cols-2 gap-4\"><div class=\"bg-base-100 rounded-lg shadow p-4 text-center\"><h3 class=\"text-sm font-medium\">Clocked In</h3><p id=\"adClockIn\" class=\"text-2xl font-bold\">0</p></div><div class=\"bg-base-100 rounded-lg shadow p-4 text-center\"><h3 class=\"text-sm font-medium\">Clocked Out</h3><p id=\"adClockOut\" class=\"text-2xl font-bold\">0</p></div></div>"}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-chart-pie',
  'Attendance Dashboard',
  'Attendance Dashboard'
);


-- Time Clocks modal
INSERT INTO modules (module_id, name, config, org_id, branch_id, icon, aria_label, description) VALUES (
  '0194a8b2-7123-7123-8123-123456789abc'::uuid, 'Time Clocks',
  '{"title":"Time Clocks","modulePath":"modules/timeclocks/timeclocks","header":[{"type":"button","label":"Clock In","action":"clockIn"},{"type":"button","label":"Clock Out","action":"clockOut"}],"body":[
    { "type":"table",
      "options":
      { "tableName":"time_clocks",
        "columnsToShow":["name", "clock_type","clocked_at"],
        "rowActions":[
          {
            "label":"Accidental Flag",
            "icon":"fa-flag",
            "action":"timeclocks:flag-accidental",
            "confirm":"Flag this time clock entry as accidental and view daily details?"
          }
        ]
      }}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-clipboard-user',
  'Time Clocks',
  'Time Clocks'
);

-- Payroll modal
INSERT INTO modules (module_id, name, config, org_id, branch_id, icon, aria_label, description) VALUES (
  '018e3f0a-12d3-7c45-b89a-2f3c4e1d5b6c'::uuid, 'Payroll',
  $json$ {
    "title": "Payroll",
    "header": [
      {
        "type": "filter-date-range",
        "options": {
          "data_column": "start_date",
          "label": "Pay Period"
        }
      },
      { "type": "button", "label": "Generate Pay", "onClick": "generatePayForEmployees" },
      { "type": "button", "label": "Export Excel", "onClick": "exportTimeClockExcel" }
    ],
    "body": [
      {
        "type": "tabs",
        "tabs": [
          {
            "label": "Worked Hours",
            "elements": [
              {
                "type": "table",
                "options": {
                  "tableName": "time_clock_aggregates",
                  "showGlobalSearch": false,
                  "addButton": false,
                  "filterField": "start_date",
                  "listenColumn": "start_date",
                  "syncFilters": true,
                  "columnsToShow": ["name", "start_date", "end_date", "total_net_hours", "total_overtime_hours", "total_regular_hours", "total_payable_hours", "total_days_worked"],
                  "rowClick": "selectRecord",
                  "rowActions": [
                    { "label": "Daily Details", "onClick": "viewDailyDetails" },
                    { "label": "View Details", "onClick": "viewTimeClockDetails" },
                    { "label": "View GPS Map", "onClick": "viewTimeClockGpsMap" }
                  ]
                }
              }
            ]
          },
          {
            "label": "Payslips",
            "elements": [
              {
                "type": "table",
                "options": {
                  "tableName": "generated_payslips",
                  "showGlobalSearch": false,
                  "addButton": false,
                  "filterField": "start_date",
                  "listenColumn": "start_date",
                  "columnsToShow": ["user_name", "org_name", "gross_pay", "net_pay", "start_date", "end_date"]
                }
              }
            ]
          }
        ]
      }
    ],
    "footer": [
      { "type": "button", "label": "Close", "onClick": "closeModal" }
    ]
  } $json$::jsonb,
  NULL,
  NULL,
  'fa-money-check-dollar',
  'Payroll',
  'Manage payroll and timesheets'
) ON CONFLICT (module_id) DO UPDATE 
  SET config = EXCLUDED.config;

-- Time Clock Locations modal
INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES (
  'Time Clock Locations',
  '{"title":"Time Clock Locations","mapLibraries":{"provider":"google","libraries":"drawing"},"body":[{"type":"table","options":{"tableName":"time_clock_locations","searchInputTypes":{"name":"text","shape":"text","radius_m":"number","assigned_to_type":"text"},"columnsToShow":["name","shape","radius_m","assigned_to_type"]}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-map-location-dot',
  'Time Clock Locations',
  'Time Clock Locations'
);


-- Timesheet Approval modal
INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES (
  'Timesheet Approval',
  '{"title":"Timesheet Approval","body":[{"type":"table","options":{"tableName":"pending_timesheets","tableUrl":"../api/timesheets/pending","columnsToShow":["id","user_id","date","standard_hours","overtime_hours","break_hours"],"apiRowActions":[{"buttonText":"Approve","apiUrl":"../api/timesheets/approve/{id}"}]}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-clipboard-check',
  'Timesheet Approval',
  'Timesheet Approval'
);


-- Clock Adjustment modal
INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES (
  'Clock Adjustment',
  '{"title":"Clock Adjustment","body":[{"type":"table","options":{"tableName":"time_clocks","searchInputTypes":{"clocked_at":"datetime-local","approval_comment":"text"},"columnsToShow":["user_id","clock_type","clocked_at","approval_comment"],"addButton":false}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-clock',
  'Clock Adjustment',
  'Clock Adjustment'
);

-- Timesheet Summary modal
INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES (
  'Timesheet Summary',
  '{"title":"Timesheet Summary","body":[{"type":"table","options":{"tableName":"timesheet_summary","tableUrl":"../api/timesheets/summary","columnsToShow":["user_id","approved_hours","rejected_hours","comments"],"addButton":false}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-list-check',
  'Timesheet Summary',
  'Timesheet Summary'
);


-- Timesheet Summary modal
INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES (
  'Timesheet Summary',
  '{"title":"Timesheet Summary","body":[{"type":"table","options":{"tableName":"timesheet_summary","tableUrl":"../api/timesheets/summary","columnsToShow":["user_id","approved_hours","rejected_hours","comments"],"addButton":false}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-list-check',
  'Timesheet Summary',
  'Timesheet Summary'
);

-- User Groups modal
INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES (
  'User Groups',
  '{"title":"User Groups","header":[{"type":"button","label":"Add Group","formName":"User Group"}],"body":[{"type":"table","options":{"tableName":"groups","showGlobalSearch":true,"addButton":false}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-users',
  'User Groups',
  'User Groups'
);

-- Group Members modal
INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES (
  'Group Members',
  '{"title":"Group Members","header":[{"type":"button","label":"Add Member","formName":"Group Member"}],"body":[{"type":"table","options":{"tableName":"user_group_memberships","showGlobalSearch":true,"addButton":false}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-user-group',
  'Group Members',
  'Group Members'
);

-- Form Categories manager modal
INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES (
  'form_group_manager',
  '{"title":"Form Categories","body":[{"type":"table","options":{"tableName":"form_categories","editFormId":68}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-layer-group',
  'Form Categories',
  'Manage form categories'
);


-- Users modal
INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES (
  'Users',
  '{"title":"Users","header":[{"type":"button","label":"Add User","formName":"User"}],"body":[{"type":"table","options":{"tableName":"users","showGlobalSearch":true,"addButton":false}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-users-gear',
  'Manage Users',
  'Manage Users'
);


-- Dashboard card permissions modal
INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES (
  'dashboard_card_permissions',
  '{"title":"Dashboard Card Permissions","body":[{"type":"html","html":"<select id=\"dcpTenantSelect\"><option value=\"\">All</option></select><div class=\"tabs mb-2\" id=\"dcp-tabs\"><a class=\"tab tab-bordered tab-active\" data-tab=\"groups\">Groups</a><a class=\"tab tab-bordered\" data-tab=\"users\">Users</a></div>"},{"type":"table","id":"dcpGroups","options":{"tableName":"groups","addButton":false,"showGlobalSearch":false,"actionsHeader":"Allow"}},{"type":"table","id":"dcpUsers","options":{"tableName":"users","addButton":false,"showGlobalSearch":false,"actionsHeader":"Allow"}}],"footer":[{"type":"button","label":"Save","onClick":"saveDashboardCardPerms"},{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-id-badge',
  'Card Permissions',
  'Card Permissions'
);


-- Dashboard card permissions manager modal
INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES (
  'dashboard_card_permissions_manager',
  '{"title":"Card Permissions Manager","body":[{"type":"html","html":"<select id=\"dcpTenantSelect\"></select><select id=\"dcpmGroupSelect\"></select><select id=\"dcpmUserSelect\"></select>"},{"type":"html","id":"dcpmCards","html":""},{"type":"html","html":"<div id=\"dcpm-detail\" class=\"hidden\"></div>"}],"footer":[{"type":"button","label":"Save","onClick":"saveCardPermissions"},{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-id-badge',
  'Card Permissions Manager',
  'Card Permissions Manager'
);


-- Workflow Builder modal
INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES (
  'workflow_builder',
  '{"title":"Workflow Builder","body":[{"type":"html","id":"wfBuilderContainer","html":""}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-sitemap',
  'Workflow Builder',
  'Workflow Builder'
);


-- Trip Logs modal
INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES (
  'Trip Logs',
  '{"title":"Trip Logs","header":[{"type":"button","label":"Map View","onClick":"openTripMapView"}],"body":[{"type":"table","options":{"tableName":"vehicle_trips","addButton":false,"rowClick":"selectRecord","showGlobalSearch":true}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-road',
  'Trip Logs',
  'Trip Logs'
);

-- Vehicle Reports modal
INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES (
  'Vehicle Reports',
  '{"title":"Vehicle Reports","header":[{"type":"button","label":"Add Report","formName":"Vehicle Issue Report"},{"type":"button","label":"Detail View","onClick":"openSelectedDetail"}],"body":[{"type":"table","id":"vehicleReports","options":{"tableName":"vehicle_reports","showGlobalSearch":false,"addButton":false,"rowClick":"selectRecord","filters":{"status":"open"},"apiRowActions":[{"buttonText":"Accept","apiUrl":"../api/vehicle_reports/{id}/assign"},{"buttonText":"Confirm","apiUrl":"../api/vehicle_reports/{id}/confirm"}]}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-clipboard-list',
  'Vehicle Reports',
  'Vehicle Reports'
);


-- Fleet Analytics modal
INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES (
  'Fleet Analytics',
  '{"title":"Fleet Analytics","body":[{"type":"html","id":"fleetAnalyticsRoot","html":"<div id=\"fleetAnalytics\"></div>"}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-truck-fast',
  'Fleet Analytics',
  'Fleet Analytics'
);

-- Vehicle Downtime modal
INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES (
  'Vehicle Downtime',
  '{"title":"Vehicle Downtime","header":[{"type":"button","label":"Add Downtime","formName":"Vehicle Downtime"}],"body":[{"type":"table","options":{"tableName":"vehicle_downtime","showGlobalSearch":false,"addButton":false}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-clock',
  'Vehicle Downtime',
  'Vehicle Downtime'
);


-- Clients modal
INSERT INTO modules (module_id, name, config, org_id, branch_id, icon, aria_label, description)
SELECT '0194a8b2-aaaa-7123-8123-123456789ac9'::uuid, 'Clients', 
$json$
{
  "title": "Clients",
  "header": [
    {
      "type": "filter-select",
      "options": {
        "source_table": "clients",
        "source_column": "client_id",
        "display_column": "name",
        "data_column": "name",
        "data_column_id": "selected_client_id",
        "placeholder": "Search clients by name...",
        "search_fields": ["name"],
        "max_results": 25,
        "debounce_ms": 250,
        "populateMode": "immediate"
      }
    },
    { "type": "button", "label": "Add Client", "formName": "Client" },
    { "type": "button", "label": "Detail View", "onClick": "openSelectedDetail" }
  ],
  "body": [
    {
      "type": "table",
      "options": {
        "tableName": "clients",
        "showGlobalSearch": false,
        "columnsToShow": ["name", "counsel", "phone", "email"],
        "addButton": false,
        "rowClick": "selectRecord",
        "filterField": "name",
        "listenColumn": "name"
      }
    }
  ],
  "footer": [
    { "type": "button", "label": "Close", "onClick": "closeModal" }
  ]
}
$json$::jsonb,
NULL, NULL, 'fa-users', 'Clients', 'Clients'
WHERE NOT EXISTS (SELECT 1 FROM modules WHERE name = 'Clients');


-- Cases modal
INSERT INTO modules (module_id, name, config, org_id, branch_id, icon, aria_label, description)
SELECT '0194a8b2-bbbb-7123-8123-123456789aca'::uuid, 'Cases', 
$json$
{
  "title": "Cases",
  "header": [
    {
      "type": "filter-select",
      "options": {
        "source_table": "cases",
        "source_column": "case_id",
        "display_column": "title",
        "data_column": "title",
        "data_column_id": "selected_case_id",
        "placeholder": "Search cases by client, number, or title...",
        "search_fields": ["client_name", "case_number", "title"],
        "max_results": 25,
        "debounce_ms": 250,
        "populateMode": "immediate"
      }
    },
    { "type": "button", "label": "Add Case", "formName": "Case" },
    { "type": "button", "label": "Detail View", "onClick": "openSelectedDetail" }
  ],
  "body": [
    {
      "type": "table",
      "options": {
        "tableName": "cases",
        "showGlobalSearch": false,
        "addButton": false,
        "rowClick": "selectRecord",
        "columnsToShow": ["client_name", "case_number", "title", "lead_rep_name", "added_by"],
        "filterField": "title",
        "listenColumn": "title"
      }
    }
  ],
  "footer": [
    { "type": "button", "label": "Close", "onClick": "closeModal" }
  ]
}
$json$::jsonb,
NULL, NULL, 'fa-folder-open', 'Cases', 'Cases'
WHERE NOT EXISTS (SELECT 1 FROM modules WHERE name = 'Cases');



INSERT INTO modules (module_id, name, config, org_id, branch_id, icon, aria_label, description)
SELECT '0194a8b2-8888-7123-8123-123456789ac7'::uuid,
       'Case Management',
       $json$
{
  "title": "Case Management",
  "header": [
    {
      "type": "filter-select",
      "options": {
        "source_table": "clients",
        "source_column": "client_id",
        "display_column": "name",
        "data_column": "client_name",
        "data_column_id": "selected_client_id",
        "placeholder": "Search by client name...",
        "search_fields": ["name"],
        "max_results": 25,
        "debounce_ms": 250,
        "populateMode": "immediate"
      }
    },
    { "type": "button", "label": "Add Client", "formName": "Client" },
    { "type": "button", "label": "Edit Client", "onClick": "openEditForm" },
    { "type": "button", "label": "Add Case", "formName": "Case" },
    { "type": "button", "label": "Edit Case", "onClick": "openEditForm" },
    { "type": "button", "label": "Add Hour", "formName": "Time Entries", "prefillFilter": "case_id", "source_column": "case_id" },
    { "type": "button", "label": "Add Expense", "formName": "Case Expense", "prefillFilter": "case_id" },
    { "type": "button", "label": "Add One Time Cost", "formName": "One Time Cost", "prefillFilter": "case_id" },
    { "type": "button", "label": "Create Cost Schedule", "onClick": "createCostSchedule" },
    { "type": "button", "label": "Create Invoice", "onClick": "createCostSchedule" },
    { "type": "button", "label": "Record Payment", "onClick": "recordGeneralPayment" },
    { "type": "button", "label": "TaxCore Settings", "onClick": "openTaxCoreSettings" },
    { "type": "button", "label": "Transactions", "onClick": "showCaseTransactions" },
    { "type": "button", "label": "Back", "onClick": "backToCases" }
  ],
  "body": [
    {
      "type": "tabs",
      "tabs": [
        {
          "label": "Cases",
          "elements": [
            {
              "type": "table",
              "options": {
                "tableName": "cases",
                "showGlobalSearch": false,
                "addButton": false,
                "columnsToShow": ["client_name", "case_number", "title", "lead_rep_name", "status", "added_by"],
                "filterField": "client_name",
                "listenColumn": "client_name",
                "primaryKeyField": "case_id",
                "rowActions": [
                  { "label": "Select", "onClick": "selectCaseForManagement" }
                ]
              }
            }
          ]
        },
        {
          "label": "Details",
          "elements": [
            { "type": "detail-view", "viewId": 2, "filterField": "case_id", "tableName": "cases" }
          ]
        },
        {
          "label": "Instructions",
          "elements": [
            { "type": "button", "label": "Add Instruction", "formName": "Case Instruction", "prefillFilter": "case_id" },
            { "type": "table", "options": { "tableName": "case_instructions", "inlineEdit": true, "showGlobalSearch": false, "addButton": false, "filterField": "case_id" } }
          ]
        },
        {
          "label": "Documents",
          "elements": [
            { 
              "type": "documents", 
              "options": { 
                "filterField": "case_id",
                "listenColumn": "case_id",
                "metadataFields": {
                  "case_number": "case_number",
                  "case_title": "title",
                  "client_id": "client_id",
                  "client_name": "client_name",
                  "matter_type": "matter_type",
                  "status": "status"
                }
              } 
            }
          ]
        },
        {
          "label": "Hours",
          "elements": [
            {
              "type": "table",
              "options": {
                "tableName": "time_entries",
                "inlineEdit": true,
                "ownerEditOnly": true,
                "tableUrl": "../api/time_entries",
                "showGlobalSearch": false,
                "addButton": false,
                "editFormId": 38,
                "columnsToShow": ["Counsel", "date", "hours", "total", "work_type", "description"],
                "filterField": "reference_id",
                "listenColumn": "case_id",
                "multipleSelect": true
              }
            }
          ]
        },
        {
          "label": "Expenses",
          "elements": [
            {
              "type": "table",
              "options": {
                "tableName": "expenses",
                "inlineEdit": true,
                "ownerEditOnly": true,
                "showGlobalSearch": false,
                "addButton": false,
                "editFormId": 48,
                "columnsToShow": ["date", "counsel", "amount", "description", "billable"],
                "filterField": "reference_id",
                "listenColumn": "case_id",
                "multipleSelect": true
              }
            }
          ]
        },
        {
          "label": "One Time Costs",
          "elements": [
            { "type": "button", "label": "Add One Time Cost", "formName": "One Time Cost", "prefillFilter": "case_id" },
            {
              "type": "table",
              "options": {
                "tableName": "one_time_service_costs",
                "inlineEdit": true,
                "ownerEditOnly": true,
                "showGlobalSearch": false,
                "addButton": false,
                "editFormId": 58,
                "columnsToShow": ["date", "counsel", "amount", "description", "billable"],
                "filterField": "reference_id",
                "listenColumn": "case_id",
                "multipleSelect": true
              }
            }
          ]
        },
        {
          "label": "Invoices",
          "elements": [
            {
              "type": "table",
              "options": {
                "tableName": "invoices",
                "inlineEdit": true,
                "showGlobalSearch": false,
                "addButton": false,
                "filterField": "reference_id",
                "listenColumn": "case_id",
                "filters": { "reference_table": "cases" },
                "columnsToShow": ["invoice_date", "sent_at", "invoice_number", "amount", "amount_paid", "balance"],
                "rowActions": [
                  { "label": "Edit", "onClick": "openCaseInvoiceEditForm" },
                  { "label": "Record Payment", "onClick": "recordInvoicePayment" },
                  { "label": "Submit to TaxCore", "onClick": "submitInvoiceToTaxCore", "icon": "fa-paper-plane", "condition": "status == 'approved'" },
                  { "label": "Download", "onClick": "downloadCaseInvoice" },
                  { "label": "Preview", "onClick": "previewCaseInvoice" }
                ]
              }
            }
          ]
        },
        {
          "label": "Payments",
          "elements": [
            {
              "type": "table",
              "options": {
                "tableName": "payments",
                "inlineEdit": true,
                "showGlobalSearch": false,
                "addButton": false,
                "filterField": "reference_id",
                "listenColumn": "case_id",
                "filters": { "reference_table": "cases" },
                "columnsToShow": ["payment_date", "total_amount", "payment_method", "status", "notes"]
              }
            }
          ]
        }
      ]
    }
  ],
  "footer": [
    { "type": "button", "label": "Close", "onClick": "closeModal" }
  ]
}
$json$::jsonb,
       NULL, NULL,
       'fa-briefcase',
       'Case Management', 'Case Management'
WHERE NOT EXISTS (SELECT 1 FROM modules WHERE name = 'Case Management');

-- Ensure Case Detail modal has invoice download and preview actions
--UPDATE modules SET config='{"title":"Case Detail","body":[{"type":"tabs","tabs":[{"label":"Hours","elements":[{"type":"button","label":"Add Hour","onClick":"openCaseHourForm"},{"type":"table-view","viewId":100,"recordMap":"formatCaseHourRow"}]},{"label":"Documents","elements":[{"type":"button","label":"Upload Document","onClick":"uploadCaseDocument"},{"type":"table","id":"caseDocsTbl","options":{"tableName":"documents","addButton":false,"showGlobalSearch":false}}]},{"label":"Invoices","elements":[{"type":"button","label":"Create Invoice","onClick":"openCaseInvoiceForm"},{"type":"table","id":"caseInvoicesTbl","options":{"tableName":"invoices","addButton":false,"showGlobalSearch":false,"rowActions":[{"label":"Download","onClick":"downloadCaseInvoice"},{"label":"Preview","onClick":"previewCaseInvoice"}]}}]},{"label":"Payments","elements":[{"type":"button","label":"Record Payment","onClick":"openCasePaymentForm"},{"type":"table","id":"casePaymentsTbl","options":{"tableName":"payments","addButton":false,"showGlobalSearch":false,"filterField":"reference_id","filters":{"reference_table":"cases"}}}]}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}' WHERE name='Case Detail';

-- Time Entries & Expenses modal
INSERT INTO modules (module_id, name, config, org_id, branch_id, icon, aria_label, description) VALUES (
  '0194a8b2-9999-7123-8123-123456789ac8'::uuid, 'time_entries_expenses',
  '{
    "title":"Time Entries & Expenses",
    "header":[
      {"type":"filter-select",
        "options":{
          "source_table":"users",
          "source_column":"user_id",
          "display_column":"full_name",
          "default_label":"All",
          "data_column":"user_id",
          "search_fields":["full_name", "email"],
          "placeholder":"Search users..."
        }
      },
      {"type":"filter-select",
        "options":{
          "data_column":"approved",
          "options":[
            {"label":"All","value":""},
            {"label":"Approved","value":true},
            {"label":"Pending","value":false}
          ],
          "value": false
        }
      },
      {"type":"filter-date-range",
        "options":{"data_column":"date"}
      }
    ],
    "body":[
      {"type":"tabs",
        "tabs":[
          {"label":"Time Entries","elements":[
            {"type":"table","options":{
              "tableName":"time_entries",
              "inlineEdit":true,
              "showGlobalSearch":false,
              "addButton":false,
              "editFormId":38,
              "filterField":["user_id","approved","date"],
              "filters":{"approved":false},
              "columnsToShow":["date", "counsel", "client_name","case_name", "hours", "total", "description", "billable","approved","approval_comment"],
              "columnButtons":{
                "billable":{
                  "showValue":false,
                  "buttonMap":{
                    "true":{
                      "text":"✓ Billable",
                      "className":"badge badge-success badge-sm cursor-pointer",
                      "title":"Click to mark as non-billable",
                      "onClick":"genericToggle",
                      "dataset":{
                        "tableName":"time_entries",
                        "primaryKey":"time_entry_id",
                        "field":"billable",
                        "confirmTrue":"Mark as billable?",
                        "confirmFalse":"Mark as non-billable?",
                        "entityName":"entry"
                      }
                    },
                    "false":{
                      "text":"✗ Non-Billable",
                      "className":"badge badge-ghost badge-sm cursor-pointer",
                      "title":"Click to mark as billable",
                      "onClick":"genericToggle",
                      "dataset":{
                        "tableName":"time_entries",
                        "primaryKey":"time_entry_id",
                        "field":"billable",
                        "confirmTrue":"Mark as billable?",
                        "confirmFalse":"Mark as non-billable?",
                        "entityName":"entry"
                      }
                    }
                  }
                },
                "approved":{
                  "showValue":false,
                  "buttonMap":{
                    "true":{
                      "text":"✓ Approved",
                      "className":"badge badge-success badge-sm cursor-pointer",
                      "title":"Click to disapprove",
                      "onClick":"genericToggle",
                      "dataset":{
                        "tableName":"time_entries",
                        "primaryKey":"time_entry_id",
                        "field":"approved",
                        "confirmTrue":"Approve this entry?",
                        "confirmFalse":"Disapprove this entry?",
                        "entityName":"entry"
                      }
                    },
                    "false":{
                      "text":"⏳ Pending",
                      "className":"badge badge-warning badge-sm cursor-pointer",
                      "title":"Click to approve",
                      "onClick":"genericToggle",
                      "dataset":{
                        "tableName":"time_entries",
                        "primaryKey":"time_entry_id",
                        "field":"approved",
                        "confirmTrue":"Approve this entry?",
                        "confirmFalse":"Disapprove this entry?",
                        "entityName":"entry"
                      }
                    }
                  }
                }
              }
            }}
          ]},
          {"label":"Expenses","elements":[
            {"type":"table","options":{
              "tableName":"expenses",
              "inlineEdit":true,
              "showGlobalSearch":false,
              "addButton":false,
              "editFormId": 48,
              "filterField":["user_id","approved","date"],
              "filters":{"approved":false},
              "columnsToShow":["date", "counsel", "client_name","case_name","amount","description","billable","approved","approval_comment"],
              "columnButtons":{
                "billable":{
                  "showValue":false,
                  "buttonMap":{
                    "true":{
                      "text":"✓ Billable",
                      "className":"badge badge-success badge-sm cursor-pointer",
                      "title":"Click to mark as non-billable",
                      "onClick":"genericToggle",
                      "dataset":{
                        "tableName":"expenses",
                        "primaryKey":"expense_id",
                        "field":"billable",
                        "confirmTrue":"Mark as billable?",
                        "confirmFalse":"Mark as non-billable?",
                        "entityName":"expense"
                      }
                    },
                    "false":{
                      "text":"✗ Non-Billable",
                      "className":"badge badge-ghost badge-sm cursor-pointer",
                      "title":"Click to mark as billable",
                      "onClick":"genericToggle",
                      "dataset":{
                        "tableName":"expenses",
                        "primaryKey":"expense_id",
                        "field":"billable",
                        "confirmTrue":"Mark as billable?",
                        "confirmFalse":"Mark as non-billable?",
                        "entityName":"expense"
                      }
                    }
                  }
                },
                "approved":{
                  "showValue":false,
                  "buttonMap":{
                    "true":{
                      "text":"✓ Approved",
                      "className":"badge badge-success badge-sm cursor-pointer",
                      "title":"Click to disapprove",
                      "onClick":"genericToggle",
                      "dataset":{
                        "tableName":"expenses",
                        "primaryKey":"expense_id",
                        "field":"approved",
                        "confirmTrue":"Approve this expense?",
                        "confirmFalse":"Disapprove this expense?",
                        "entityName":"expense"
                      }
                    },
                    "false":{
                      "text":"⏳ Pending",
                      "className":"badge badge-warning badge-sm cursor-pointer",
                      "title":"Click to approve",
                      "onClick":"genericToggle",
                      "dataset":{
                        "tableName":"expenses",
                        "primaryKey":"expense_id",
                        "field":"approved",
                        "confirmTrue":"Approve this expense?",
                        "confirmFalse":"Disapprove this expense?",
                        "entityName":"expense"
                      }
                    }
                  }
                }
              }
            }}
          ]},
          {"label":"One Time Costs","elements":[
            {"type":"table","options":{
              "tableName":"one_time_service_costs",
              "inlineEdit":true,
              "editFormId": 58,
              "filterField":["user_id","approved","date"],
              "filters":{"approved":false},
              "columnsToShow":["date", "counsel", "client_name", "case_name","amount","description","billable","approved","comments"],
              "columnButtons":{
                "billable":{
                  "showValue":false,
                  "buttonMap":{
                    "true":{
                      "text":"✓ Billable",
                      "className":"badge badge-success badge-sm cursor-pointer",
                      "title":"Click to mark as non-billable",
                      "onClick":"genericToggle",
                      "dataset":{
                        "tableName":"one_time_service_costs",
                        "primaryKey":"one_time_service_cost_id",
                        "field":"billable",
                        "confirmTrue":"Mark as billable?",
                        "confirmFalse":"Mark as non-billable?",
                        "entityName":"cost"
                      }
                    },
                    "false":{
                      "text":"✗ Non-Billable",
                      "className":"badge badge-ghost badge-sm cursor-pointer",
                      "title":"Click to mark as billable",
                      "onClick":"genericToggle",
                      "dataset":{
                        "tableName":"one_time_service_costs",
                        "primaryKey":"one_time_service_cost_id",
                        "field":"billable",
                        "confirmTrue":"Mark as billable?",
                        "confirmFalse":"Mark as non-billable?",
                        "entityName":"cost"
                      }
                    }
                  }
                },
                "approved":{
                  "showValue":false,
                  "buttonMap":{
                    "true":{
                      "text":"✓ Approved",
                      "className":"badge badge-success badge-sm cursor-pointer",
                      "title":"Click to disapprove",
                      "onClick":"genericToggle",
                      "dataset":{
                        "tableName":"one_time_service_costs",
                        "primaryKey":"one_time_service_cost_id",
                        "field":"approved",
                        "confirmTrue":"Approve this cost?",
                        "confirmFalse":"Disapprove this cost?",
                        "entityName":"cost"
                      }
                    },
                    "false":{
                      "text":"⏳ Pending",
                      "className":"badge badge-warning badge-sm cursor-pointer",
                      "title":"Click to approve",
                      "onClick":"genericToggle",
                      "dataset":{
                        "tableName":"one_time_service_costs",
                        "primaryKey":"one_time_service_cost_id",
                        "field":"approved",
                        "confirmTrue":"Approve this cost?",
                        "confirmFalse":"Disapprove this cost?",
                        "entityName":"cost"
                      }
                    }
                  }
                }
              }
            }}
          ]}
        ]
      }
    ],
    "footer":[{"type":"button","label":"Close","onClick":"closeModal"}]
  }',
  NULL, NULL, 'fa-clock', 'Time Entries & Expenses', 'Time Entries & Expenses'
);


-- Tenants modal
INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description)
SELECT 'Tenants', '{"title":"Tenants","header":[{"type":"button","label":"Add Tenant","formName":"Tenant"}],"body":[{"type":"table","options":{"tableName":"tenants","showGlobalSearch":false,"addButton":false}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL, NULL, 'fa-users-gear', 'Tenant Admin', 'Tenant Admin'
WHERE NOT EXISTS (SELECT 1 FROM modules WHERE name = 'Tenants');

-- Admins modal definition
INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description)
SELECT 'Admins', '{"title":"Admins","header":[{"type":"button","label":"Add Admin","formName":"Admin"}],"body":[{"type":"table","options":{"tableName":"users","filters":{"is_admin":"1"},"showGlobalSearch":false,"addButton":false}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL, NULL, 'fa-user-shield', 'Admins', 'Admins'
WHERE NOT EXISTS (SELECT 1 FROM modules WHERE name = 'Admins');



-- Table Builder modal
INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES (
  'Table Builder',
  '{"title":"Table Builder","body":[{"type":"html","html":"<div class=\"mb-2\"><label class=\"label\">Table Name</label><input id=\"tbTableName\" class=\"input input-bordered w-full\"/></div>"},{"type":"html","html":"<div class=\"mt-4\"><button id=\"addColumnBtn\" type=\"button\" class=\"btn btn-sm mb-2\">Add Column</button><table id=\"tbColumns\" class=\"table table-sm w-full\"><thead><tr><th>Name</th><th>Type</th><th>Default</th><th>Required</th><th></th></tr></thead><tbody></tbody></table></div>"},{"type":"html","html":"<div class=\"mt-4\"><button id=\"addRelationBtn\" type=\"button\" class=\"btn btn-sm mb-2\">Add Relationship</button><table id=\"tbRelations\" class=\"table table-sm w-full\"><thead><tr><th>Column</th><th>References Table</th><th>References Column</th><th></th></tr></thead><tbody></tbody></table></div>"}],"footer":[{"type":"button","label":"Save","onClick":"submitTableDefinition"},{"type":"button","label":"Close","onClick":"closeModal"}]}' ,
  NULL,
  NULL,
  'fa-table',
  'Table Builder',
  'Table Builder'
);

-- Graph Builder modal
INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES (
  'Graph Builder',
  '{"title":"Graph Builder","body":[{"type":"html","id":"graphBuilderMount","html":"<div id=\"graphBuilderMount\"></div>"}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}' ,
  NULL,
  NULL,
  'fa-chart-line',
  'Graph Builder',
  'Graph Builder'
);


-- Tenant Table Manager modal
INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES (
  'tenant_table_manager',
  '{"title":"Tenant Table Manager","body":[{"type":"table","options":{"tableName":"tenant_tables","showGlobalSearch":false,"addButton":false}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-table-list',
  'Tenant Table Manager',
  'Tenant Table Manager'
);


-- Module Manager modal
INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES (
  'module_manager',
  '{"title":"Module Manager","body":[{"type":"html","id":"moduleManagerContainer","html":""}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-cubes',
  'Module Manager',
  'Module Manager'
);

-- Permissions Manager modal
INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES (
  'permissions_manager',
  '{"title":"Permissions Manager","body":[{"type":"html","id":"permissionsContainer","html":""}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-user-shield',
  'Permissions Manager',
  'Permissions Manager'
);


-- Vendor Quotes modal
INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES (
  'Vendor Quotes',
  '{"title":"Vendor Quotes","header":[{"type":"button","label":"Add Quote","formName":"Vendor Quote"}],"body":[{"type":"table","options":{"tableName":"vendor_quotes","showGlobalSearch":false,"addButton":false}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-file-lines',
  'Vendor Quotes',
  'Vendor Quotes'
);

-- Vendor RFQs (single vendor-side module)
INSERT INTO modules (module_id, name, config, org_id, branch_id, icon, aria_label, description) VALUES (
  '0194a8b2-00a1-7123-8123-123456789abc'::uuid,
  'Vendor RFQs',
  $json$
  {
    "title": "Vendor RFQs",
    "body": [
      { "type": "tabs", "tabs": [
        { "label": "My RFQs", "elements": [
          { "type": "html", "html": "<div class='alert alert-info mb-2'>Select an invite then click Respond to start your quote.</div>" },
          { "type": "table", "id": "vendorInvites", "options": {
              "tableName": "rfq_invites",
              "scope": "user",
              "userField": "vendor_user_id",
              "columnsToShow": ["rfq_id","status","sent_at","opened_at","responded_at"],
              "addButton": false,
              "rowActions": [ { "label": "Respond", "onClick": "openVendorResponse" } ]
            }
          }
        ]},
        { "label": "Response", "elements": [
          { "type": "detail-view", "tableName": "rfq_headers", "filterField": "rfq_id" },
          { "type": "table", "id": "vendorQuotes", "options": {
              "tableName": "vendor_quotes",
              "filterField": ["rfq_id","vendor_id"],
              "columnsToShow": ["status","currency","total_amount","delivery_days","valid_thru","notes"],
              "inlineEdit": true,
              "addButton": false,
              "rowActions": [ { "label": "Select", "onClick": "selectRecord" }, { "label": "Submit", "onClick": "submitVendorQuote" } ]
            }
          },
          { "type": "table", "options": {
              "tableName": "vendor_quote_items",
              "filterField": "quote_id",
              "columnsToShow": ["rfq_item_id","is_alternate","alt_label","unit_price","tax","lead_time_days","notes"],
              "inlineEdit": true,
              "addButton": true
            }
          }
        ]}
      ]}
    ],
    "footer": [ { "type": "button", "label": "Close", "onClick": "closeModal" } ]
  }
  $json$::jsonb,
  NULL, NULL,
  'fa-clipboard-list',
  'Vendor RFQs',
  'Respond to RFQs and submit quotes'
) ON CONFLICT DO NOTHING;

-- Time Entries Entry modal
INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES (
  'Time Entries Entry',
  '{"title":"Time Entries Entry","header":[{"type":"button","label":"Add Hour","formName":"Time Entries"}],"body":[{"type":"table","options":{"tableName":"time_entries","tableUrl":"../api/time_entries","showGlobalSearch":false,"addButton":false,"editFormId":38,"editFormId":38}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-user-clock',
  'Time Entries Entry',
  'Time Entries Entry'
);



INSERT INTO modules (name,config,org_id,branch_id,icon,aria_label,description) VALUES
  ('Drivers','{"title":"Drivers","header":[{"type":"button","label":"Add Driver","formName":"Driver"}],"body":[{"type":"table","options":{"tableName":"users","showGlobalSearch":false,"filterField":"groups.name","filterValue":"Drivers"}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL, NULL,'fa-id-card','Drivers','Drivers');


INSERT INTO modules (name,config,org_id,branch_id,icon,aria_label,description) VALUES
  ('Lawyers','{"title":"Lawyers","header":[{"type":"button","label":"Add Lawyer","formName":"Lawyer"}],"body":[{"type":"table","options":{"tableName":"users","showGlobalSearch":false,"filterField":"groups.name","filterValue":"Lawyers"}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL, NULL,'fa-gavel','Lawyers','Lawyers');

INSERT INTO modules (module_id, name,config,org_id,branch_id,icon,aria_label,description) VALUES
  ('0194a8b2-7777-7123-8123-123456789ac6'::uuid, 'Employees','{"title":"Employee Management","body":[{"type":"custom","module":"Employees","modulePath":"employees"}]}',NULL, NULL,'fa-users','Employees','Manage employees, rates, and types');

INSERT INTO modules (module_id, name,config,org_id,branch_id,icon,aria_label,description) VALUES
  ('0194a8b2-8888-7123-8123-123456789ac6'::uuid, 'User Profile','{"title":"User Profile","body":[{"type":"custom","module":"UserProfile","modulePath":"profile/userprofile"}]}',NULL, NULL,'fa-user-gear','User Profile','Manage MFA or PassKey')
ON CONFLICT (module_id) DO NOTHING;

INSERT INTO modules (name,config,org_id,branch_id,icon,aria_label,description) VALUES
  ('Investigators','{"title":"Investigators","header":[{"type":"button","label":"Add Investigator","formName":"Investigator"}],"body":[{"type":"table","options":{"tableName":"users","showGlobalSearch":false,"filterField":"groups.name","filterValue":"Investigators"}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL, NULL,'fa-user-secret','Investigators','Investigators');


-- Case Detail modal
INSERT INTO modules (name, config, org_id, branch_id) VALUES (
  'Case Detail',
  '{"title":"Case Detail","body":[{"type":"tabs","tabs":[{"label":"Hours","elements":[{"type":"button","label":"Add Hour","onClick":"openCaseHourForm"},{"type":"table-view","viewId":100,"recordMap":"formatCaseHourRow"}]},{"label":"Documents","elements":[{"type":"button","label":"Upload Document","onClick":"uploadCaseDocument"},{"type":"table","id":"caseDocsTbl","options":{"tableName":"documents","addButton":false,"showGlobalSearch":false}}]},{"label":"Invoices","elements":[{"type":"button","label":"Create Invoice","onClick":"openCaseInvoiceForm"},{"type":"table","id":"caseInvoicesTbl","options":{"tableName":"invoices","addButton":false,"showGlobalSearch":false,"rowActions":[{"label":"Download","onClick":"downloadCaseInvoice"},{"label":"Preview","onClick":"previewCaseInvoice"}]}}]},{"label":"Payments","elements":[{"type":"button","label":"Record Payment","onClick":"openCasePaymentForm"},{"type":"table","id":"casePaymentsTbl","options":{"tableName":"payments","addButton":false,"showGlobalSearch":false}}]}]}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}' ,
  NULL,
  NULL
);

-- Case Invoice Preview modal
INSERT INTO modules (name, config, org_id, branch_id) VALUES (
  'Case Invoice Preview',
  '{"title":"Case Invoice","body":[{"type":"html","id":"ciPreview","html":""},{"type":"form","formName":"Case Invoice"}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL
);

-- Workplace Invoice Preview modal
INSERT INTO modules (name, config, org_id, branch_id)
SELECT 'Workplace Invoice Preview',
       '{"title":"Workplace Invoice Preview","body":[{"type":"html","id":"invoicePreview","html":""},{"type":"html","html":"<button id=\"payNowBtn\" class=\"btn\">Pay Now</button>"}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
       NULL, NULL
WHERE NOT EXISTS (SELECT 1 FROM modules WHERE name = 'Workplace Invoice Preview');


INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES (
  'DMS Showcase',
  '{"title":"DMS Showcase","body":[{"type":"documents"}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-folder-open',
  'DMS Showcase',
  'DMS Showcase'
);


INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES (
  'Training Documents',
  '{"title":"Training Documents","body":[{"type":"documents","options":{"category_id":1,"scope":"tenant"}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-folder-open',
  'Training Documents',
  'Training Documents'
);

INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES (
  'Compliance Documents',
  '{"title":"Compliance Documents","body":[{"type":"documents","options":{"category_id":2,"scope":"tenant","showExpiry":true}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-folder-open',
  'Compliance Documents',
  'Compliance Documents'
);

-- Modal using sample detail view
INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES (
  'Sample Detail Modal',
  '{"title":"Sample Detail","body":[{"type":"detail-view","viewId":1}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-address-card',
  'Sample Detail View',
  'Sample Detail View'
);


-- Invoice Configuration modal and workflow
INSERT INTO modules (name, config, org_id, branch_id) VALUES (
  'Invoice Configuration',
  '{"title":"Invoice Configuration","body":[{"type":"form","formId":44}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL
);


INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES
(
  'Compliance Dashboard',
  $json$
  {
    "title": "Compliance Dashboard",
    "body": [
      {
        "type": "html",
        "id": "complianceDash",
        "html": "<div id=\"complianceDashboard\"></div>"
      }
    ],
    "footer": [
      {
        "type": "button",
        "label": "Close",
        "onClick": "closeModal"
      }
    ]
  }
  $json$,
  NULL,
  NULL,
  'fa-gauge',
  'Compliance Dashboard',
  'Compliance Dashboard'
);


INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES
  ('Drill Down Dashboard','{"title":"Drill Down Dashboard","body":[{"type":"table","options":{"tableName":"ohs_incidents"}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL, NULL,'fa-filter','Drill Down Dashboard','Drill Down Dashboard');


INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES
  ('Emergency Preparedness','{"title":"Emergency Preparedness","body":[{"type":"table","options":{"tableName":"ohs_emergency_drills"}},{"type":"table","options":{"tableName":"ohs_emergency_contacts"}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL, NULL,'fa-phone','Emergency Preparedness','Emergency Preparedness');


INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES
  ('Hazard Management','{"title":"Hazard Management","header":[{"type":"button","label":"Add Hazard","formName":"OHS Hazard"}],"body":[{"type":"table","options":{"tableName":"ohs_hazards","showGlobalSearch":false,"addButton":false,"editFormId":7}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL, NULL,'fa-shield-halved','Hazard Management','Hazard Management');


INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES
  ('Hazard Types','{"title":"Hazard Types","header":[{"type":"button","label":"Add Hazard Type","formName":"Hazard Type"}],"body":[{"type":"table","options":{"tableName":"ohs_hazard_types","showGlobalSearch":false,"addButton":false}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL, NULL,'fa-layer-group','Hazard Types','Hazard Types');


INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES
  ('Incident Heatmap','{"title":"Incident Heatmap","body":[{"type":"graph-map","options":{"endpoint":"../api/ohs_dashboard/heatmap","dataPath":"rows"}},{"type":"graph-chart","options":{"endpoint":"../api/ohs_dashboard/heatmap","dataPath":"chart","type":"bar"}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL, NULL,'fa-map','Incident Heatmap','Incident Heatmap');


INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES
  ('Incident Summary Dashboard','{"title":"Incident Summary","body":[{"type":"graph-chart","options":{"endpoint":"../api/ohs_dashboard/summary","type":"pie"}},{"type":"graph-chart","options":{"endpoint":"../api/ohs_dashboard/monthly_trend","type":"line"}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL, NULL,'fa-chart-pie','Incident Summary Dashboard','Incident Summary Dashboard');


INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES
  ('Inspection Audit','{"title":"Inspection Audit","body":[{"type":"table","options":{"tableName":"ohs_inspection_audits"}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL, NULL,'fa-list-check','Inspection Audit','Inspection Audit');


INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES
  ('JSA Training Status','{"title":"JSA Training Status","body":[{"type":"table","options":{"tableName":"ohs_jsas"}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL, NULL,'fa-user-graduate','JSA Training Status','JSA Training Status');


INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES
  ('Near Miss Dashboard','{"title":"Near Miss Dashboard","body":[{"type":"html","id":"nearMissDash","html":"<canvas id=\"nearMissTrend\"></canvas><table class=\"near-miss-table\"></table>"}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL, NULL,'fa-chart-line','Near Miss Dashboard','Near Miss Dashboard');


INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES
  ('OHS Assignment Rules','{"title":"OHS Assignment Rules","body":[{"type":"table","options":{"tableName":"ohs_assignment_rules"}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL, NULL,'fa-route','OHS Assignment Rules','OHS Assignment Rules');

INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES
  ('Inspection Assignment Rules','{"title":"Inspection Assignment Rules","body":[{"type":"table","options":{"tableName":"inspection_assignment_rules"}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL, NULL,'fa-route','Inspection Assignment Rules','Inspection Assignment Rules');
INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES
  ('WorkCOM Inspection Assignment Rules','{"title":"WorkCOM Inspection Assignment Rules","body":[{"type":"table","options":{"tableName":"inspection_assignment_rules"}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL, NULL,'fa-route','WorkCOM Inspection Assignment Rules','WorkCOM Inspection Assignment Rules');

INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES
  ('OHS Incident Types','{"title":"OHS Incident Types","header":[{"type":"button","label":"Add Incident Type","formName":"Incident Type"}],"body":[{"type":"table","options":{"tableName":"ohs_incident_types","showGlobalSearch":false,"addButton":false,"editFormId":57}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL, NULL,'fa-clipboard-list','OHS Incident Types','OHS Incident Types');

INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES
  ('OHS Inspection Types','{"title":"OHS Inspection Types","header":[{"type":"button","label":"Add Inspection Type","formName":"Inspection Type"}],"body":[{"type":"table","options":{"tableName":"ohs_inspection_types","showGlobalSearch":false,"addButton":false,"editFormId":68}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL, NULL,'fa-clipboard-list','OHS Inspection Types','OHS Inspection Types');

INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES
  ('OHS Inspection Templates','{"title":"OHS Inspection Templates","header":[{"type":"button","label":"Add Template","formName":"Inspection Template"}],"body":[{"type":"table","options":{"tableName":"ohs_inspection_templates","showGlobalSearch":false,"addButton":false,"editFormId":74}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL, NULL,'fa-clipboard-list','OHS Inspection Templates','OHS Inspection Templates');

INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES
  ('WorkCOM Inspection Types','{"title":"WorkCOM Inspection Types","header":[{"type":"button","label":"Add Inspection Type","formName":"WorkCOM Inspection Type"}],"body":[{"type":"table","options":{"tableName":"workcom_inspection_types","showGlobalSearch":false,"addButton":false,"editFormId":104}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL, NULL,'fa-clipboard-list','WorkCOM Inspection Types','WorkCOM Inspection Types');


INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES
  ('OHS Incident Wizard','{"title":"OHS Incident Wizard","body":[{"type":"html","id":"incidentWizard","html":"<div id=\"incidentWizard\"></div>"}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL, NULL,'fa-wand-magic-sparkles','OHS Incident Wizard','OHS Incident Wizard');


INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES
  ('OHS Incidents','{"title":"OHS Incidents","header":[{"type":"button","label":"Add Incident","wizardId":1}],"body":[{"type":"table","options":{"tableName":"ohs_incidents","showGlobalSearch":false,"addButton":false,"editFormLookup":{"table":"ohs_incident_types","field":"classification","valueColumn":"name","formColumn":"form_id"}}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL, NULL,'fa-exclamation-triangle','OHS Incidents','OHS Incidents');

INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES
  ('OHS Field Incident','{"title":"OHS Field Incident","header":[{"type":"button","label":"Add Field Incident","wizardId":1}],"body":[{"type":"table","options":{"tableName":"ohs_incidents","showGlobalSearch":false,"addButton":false,"filterField":"classification","filterValue":"Field Incident","editFormLookup":{"table":"ohs_incident_types","field":"classification","valueColumn":"name","formColumn":"form_id"}}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL, NULL,'fa-exclamation-triangle','OHS Field Incident','OHS Field Incident');


INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES
  ('OHS Inspections','{"title":"OHS Inspections","header":[{"type":"button","label":"Add Inspection","wizardId":3}],"body":[{"type":"table","options":{"tableName":"ohs_inspections","showGlobalSearch":false,"addButton":false,"editFormLookup":{"table":"ohs_inspection_types","field":"inspection_type_id","valueColumn":"id","formColumn":"form_id"}}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL, NULL,'fa-clipboard-check','OHS Inspections','OHS Inspections');

INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES
  ('My Inspections','{"title":"My Inspections","header":[{"type":"button","label":"Add Inspection","wizardId":3}],"body":[{"type":"table","options":{"tableName":"ohs_inspections","scope":"user","userField":"inspector_id","editFormLookup":{"table":"ohs_inspection_types","field":"inspection_type_id","valueColumn":"id","formColumn":"form_id"}}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL, NULL,'fa-clipboard-check','My Inspections','My Inspections');

INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES
  ('WorkCOM Inspections','{"title":"WorkCOM Inspections","header":[{"type":"button","label":"Add Inspection","wizardId":5}],"body":[{"type":"table","options":{"tableName":"workcom_inspections","showGlobalSearch":false,"addButton":false,"editFormLookup":{"table":"workcom_inspection_types","field":"inspection_type_id","valueColumn":"id","formColumn":"form_id"}}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL, NULL,'fa-clipboard-check','WorkCOM Inspections','WorkCOM Inspections');


INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES
  ('OHS Investigation Dashboard','{"title":"Investigation Dashboard","header":[{"type":"button","label":"Add Incident","wizardId":1}],"body":[{"type":"table","options":{"tableName":"ohs_incidents","editFormId":4,"rowClick":"selectRecord"}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL, NULL,'fa-clipboard-question','OHS Investigation Dashboard','OHS Investigation Dashboard');
INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES (
  'WorkCOM Inspection Dashboard',
  '{"title":"WorkCOM Inspection Dashboard","body":[{"type":"table","options":{"tableName":"workcom_inspections","calculatedColumns":{"status":"inspector_id ? ''Complete'' : ''Pending''"},"searchInputTypes":{"status":{"type":"select","options":["Pending","Complete"]}}}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL, NULL, 'fa-chart-bar', 'WorkCOM Inspection Dashboard', 'WorkCOM Inspection Dashboard'
);

INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES (
  'Inspector Workload',
  '{"title":"Inspector Workload","body":[{"type":"table","options":{"tableName":"workcom_inspections","scope":"user","userField":"inspector_id","calculatedColumns":{"pending_count":"inspector_id ? 0 : 1","completed_count":"inspector_id ? 1 : 0"}}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL, NULL, 'fa-tasks', 'Inspector Workload', 'Inspector Workload'
);


INSERT INTO modules (
  name, config, org_id, branch_id, icon, aria_label, description
) VALUES (
  'WorkCOM Inspection Kanban',
  $json$
  {
    "title": "WorkCOM Inspection Kanban",
    "body": [
      {
        "type": "html",
        "html": "<div id=\"workcomKanban\"></div>"
      }
    ],
    "footer": [
      {
        "type": "button",
        "label": "Close",
        "onClick": "closeModal"
      }
    ]
  }
  $json$::jsonb,
  NULL, NULL, 'fa-table-columns', 'WorkCOM Inspection Kanban', 'WorkCOM Inspection Kanban'
);

INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES
  ('Investigation Form','{"title":"Investigation Form","body":[{"type":"html","html":"<div id=\"whyList\"></div><button id=\"addWhyBtn\" type=\"button\">Add Why</button><button id=\"saveInvBtn\" type=\"button\">Save</button>"}],"footer":[]}',NULL,NULL,'fa-question','Investigation Form','Investigation Form');


INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES
  ('OHS JSA','{"title":"OHS JSA","header":[{"type":"button","label":"Create JSA","formName":"Job Safety Analysis"}],"body":[{"type":"table","options":{"tableName":"ohs_jsas","showGlobalSearch":false,"addButton":false,"editFormId":6}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL, NULL,'fa-helmet-safety','OHS JSA','OHS JSA');


INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES
  ('Safety Documents','{"title":"Safety Documents","body":[{"type":"table","options":{"tableName":"safety_documents"}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL, NULL,'fa-file-lines','Safety Documents','Safety Documents');

INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES (
  'Safety Incidents',
  '{"title":"Safety Incidents","header":[{"type":"button","label":"Add Incident","wizardId":6}],"body":[{"type":"table","options":{"tableName":"safety_incidents","showGlobalSearch":false,"addButton":false,"editFormLookup":{"table":"safety_incident_types","field":"incident_type","valueColumn":"id","formColumn":"form_id"},"columnLabels":{"document_ids":"Documents"}}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-helmet-safety',
  'Safety Incidents',
  'Safety Incidents'
);

INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description)
SELECT 'Safety Field Incident', '{"title":"Safety Field Incident","header":[{"type":"button","label":"Add Field Incident","wizardId":6}],"body":[{"type":"table","options":{"tableName":"safety_incidents","showGlobalSearch":false,"addButton":false,"filterField":"incident_type","filterValue":6,"editFormLookup":{"table":"safety_incident_types","field":"incident_type","valueColumn":"id","formColumn":"form_id"}}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}' , NULL, NULL, 'fa-helmet-safety', 'Safety Field Incident', 'Safety Field Incident'
WHERE NOT EXISTS (SELECT 1 FROM modules WHERE name='Safety Field Incident');


INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES
('Ohs Reports','{"title": "OHS Reports", "header": [{"type": "html", "html": "<button class=\"btn btn-sm\" onclick=\"location.href=''../api/ohs_reports/export/excel''\">Export Excel</button><button class=\"btn btn-sm ml-2\" onclick=\"location.href=''../api/ohs_reports/export/pdf''\">Export PDF</button>"}], "body": [{"type": "graph-chart", "options": {"endpoint": "../api/ohs_reports/trendsByDepartment", "type": "line"}}, {"type": "graph-chart", "options": {"endpoint": "../api/ohs_reports/locationBenchmark", "type": "bar"}}], "footer": [{"type": "button", "label": "Close", "onClick": "closeModal"}]}',NULL,NULL,'fa-chart-bar','OHS Reports','OHS Reports');


INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES
  ('Risk Matrix Dashboard','{"title":"Risk Matrix Dashboard","body":[{"type":"heatmap","id":"riskMatrixHeatmap","options":{"endpoint":"../api/ohs_risk_matrices"}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL, NULL,'fa-table-cells','Risk Matrix Dashboard','Risk Matrix Dashboard');


INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES
  ('Root Cause Dashboard','{"title":"Root Cause Dashboard","body":[{"type":"html","html":"<div id=\"rootCauseDashboard\"></div>"}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL, NULL,'fa-magnifying-glass-chart','Root Cause Dashboard','Root Cause Dashboard');



INSERT INTO modules (name, config, org_id, branch_id) VALUES ('Fishbone Example','{"title":"Fishbone Example","body":[{"type":"fishbone-diagram","options":{"diagramId":1}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL, NULL);


INSERT INTO modules (name, config, org_id, branch_id) VALUES ('Graph Demo','{"title":"Graph Demo","body":[{"type":"graph-d3","graphId":1}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL, NULL);


INSERT INTO modules (name, config, org_id, branch_id) VALUES ('Fishbone Diagram Manager','{"title":"Fishbone Diagram Manager","header":[{"type":"button","label":"Add Diagram","onClick":"addFishboneDiagram"}],"body":[{"type":"table","id":"fishboneList","options":{"tableName":"fishbone_diagrams","showGlobalSearch":false,"addButton":false,"rowActions":[{"label":"Edit","onClick":"editFishboneDiagram"}]}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL, NULL);
INSERT INTO modules (name, config, org_id, branch_id) VALUES ('Fault Tree Manager','{"title":"Fault Tree Manager","header":[{"type":"button","label":"Add Diagram","onClick":"addFaultTreeDiagram"}],"body":[{"type":"table","id":"ftList","options":{"tableName":"ohs_fault_trees","showGlobalSearch":false,"addButton":false,"rowActions":[{"label":"Edit","onClick":"editFaultTreeDiagram"}]}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL, NULL);
INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description)
VALUES (
  'Five Whys Manager',
  '{"title":"Five Whys Manager","header":[{"type":"button","label":"Add Whys","onClick":"addFiveWhys"}],"body":[{"type":"table","options":{"tableName":"ohs_five_whys","showGlobalSearch":false,"rowActions":[{"label":"Edit","onClick":"editFiveWhys"}],"editFormId":83}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL, NULL, 'fa-question', 'Five Whys Manager','Five Whys Manager'
);


INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES
  ('Severity Dashboard','{"title":"Severity Dashboard","body":[{"type":"html","id":"severityDash","html":"<canvas id=\"sevChart\"></canvas><table class=\"treat-outcomes\"></table>"}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL, NULL,'fa-notes-medical','Severity Dashboard','Severity Dashboard');

INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES
  ('OHS Actions','{"title":"OHS Actions","header":[{"type":"button","label":"Add Action","formName":"OHS Action"}],"body":[{"type":"table","options":{"tableName":"ohs_actions","showGlobalSearch":false,"rowClick":"selectRecord"}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL, NULL,'fa-list-check','OHS Actions','OHS Actions');


INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES
  ('OHS Regulations','{"title":"OHS Regulations","header":[{"type":"button","label":"Add Regulation","formName":"OHS Regulation"}],"body":[{"type":"table","options":{"tableName":"ohs_regulations","showGlobalSearch":false,"rowClick":"selectRecord"}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL, NULL,'fa-book','OHS Regulations','OHS Regulations');


INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES
  ('OHS Compliance Tasks','{"title":"OHS Compliance Tasks","header":[{"type":"button","label":"Add Task","formName":"OHS Compliance Task"}],"body":[{"type":"table","options":{"tableName":"ohs_compliance_tasks","showGlobalSearch":false,"rowClick":"selectRecord"}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL, NULL,'fa-list-check','OHS Compliance Tasks','OHS Compliance Tasks');


INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES
  ('Safety Inductions','{"title":"Safety Inductions","header":[{"type":"button","label":"Add Induction","formName":"Safety Induction"}],"body":[{"type":"table","options":{"tableName":"safety_inductions","showGlobalSearch":false,"rowClick":"selectRecord","editFormId":10}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL, NULL,'fa-helmet-safety','Safety Inductions','Safety Inductions');


INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES
  ('Issues Log','{"title":"Issues Log","header":[{"type":"button","label":"Add Issue","formName":"Issues Log"}],"body":[{"type":"table","options":{"tableName":"ohs_issues","showGlobalSearch":false,"addButton":false,"editFormId":66}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL, NULL,'fa-bug','Issues Log','Issues Log');


-- Employee Licenses modal
INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES
  ('Employee Licenses','{"title":"Employee Licenses","header":[{"type":"button","label":"Add License","formId":11}],"body":[{"type":"table","options":{"tableName":"employee_licenses","showGlobalSearch":false,"editFormId":11}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL, NULL,'fa-id-card','Employee Licenses','Employee Licenses');


-- Permits modal
INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES
  ('Permits','{"title":"Permits","header":[{"type":"button","label":"Add Application","formId":15}],"body":[{"type":"table","options":{"tableName":"permit_applications","showGlobalSearch":false,"addButton":false,"editFormId":15,"nestedTableConfig":{"childTableName":"permit_inspections","linkField":"permit_application_id","columnsToShow":["inspector_id","scheduled_for","result","notes","hours_logged"],"editFormId":55}}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL, NULL,'fa-passport','Permits','Permits');
INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES ('Certification Tracking','{"title":"Certification Tracking","header":[{"type":"button","label":"Add New","formName":"Training Certificate"}],"body":[{"type":"table","options":{"tableName":"training_certificates","showGlobalSearch":false,"addButton":false}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL, NULL,'fa-certificate','Certification Tracking','Certification Tracking');


-- Needs & Expectations modal
INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description)
VALUES ('Needs & Expectations','{"title":"Needs & Expectations","header":[{"type":"button","label":"Add Assessment","formName":"Needs & Expectations Assessment"}],"body":[{"type":"table","options":{"tableName":"ohs_needs_expectations","showGlobalSearch":false,"rowClick":"selectRecord"}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL, NULL,'fa-hands-helping','Needs & Expectations','Needs & Expectations');


INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES (
  'Incident Alert Rules',
  '{"title":"Incident Alert Rules","header":[{"type":"button","label":"Add Rule","formName":"Incident Alert Rule"}],"body":[{"type":"table","options":{"tableName":"incident_alert_rules","showGlobalSearch":false,"addButton":false,"editFormId":98}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-bell',
  'Incident Alert Rules',
  'Incident Alert Rules'
);


-- Risk Assessment Types modal
INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES (
  'Risk Assessment Types',
  '{"title":"Risk Assessment Types","header":[{"type":"button","label":"Add Type","formName":"Risk Assessment Type"}],"body":[{"type":"table","options":{"tableName":"risk_assessment_types","showGlobalSearch":false,"addButton":false,"editFormId":74}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-layer-group',
  'Risk Assessment Types',
  'Risk Assessment Types'
);

-- Risk Assessments modal
INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES (
  'Risk Assessments',
  '{"title":"Risk Assessments","header":[{"type":"button","label":"Add Assessment","wizardId":4}],"body":[{"type":"table","options":{"tableName":"risk_assessments","showGlobalSearch":false,"addButton":false,"editFormLookup":{"table":"risk_assessment_types","field":"risk_assessment_type_id","valueColumn":"id","formColumn":"form_id"}}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-clipboard-list',
  'Risk Assessments',
  'Risk Assessments'
);


-- Risk Categories Manager modal
INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description)
SELECT 'Risk Categories Manager',
       '{"title":"Risk Categories Manager","header":[{"type":"button","label":"Add Category","formName":"Risk Category"}],"body":[{"type":"table","options":{"tableName":"risk_categories","showGlobalSearch":false,"addButton":false,"rowClick":"selectRecord","editFormId":74}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
       NULL, NULL, 'fa-tags', 'Risk Categories Manager', 'Risk Categories Manager'
WHERE NOT EXISTS (SELECT 1 FROM modules WHERE name = 'Risk Categories Manager');



-- Risk Identification Manager modal
INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description)
SELECT 'Risk Identification Manager',
       '{"title":"Risk Identification Manager","header":[{"type":"button","label":"Add Risk","formName":"Risk Identification"}],"body":[{"type":"table","options":{"tableName":"risk_identifications","showGlobalSearch":false,"addButton":false,"rowClick":"selectRecord","editFormId":75}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
       NULL, NULL, 'fa-exclamation-triangle', 'Risk Identification Manager', 'Risk Identification Manager'
WHERE NOT EXISTS (SELECT 1 FROM modules WHERE name = 'Risk Identification Manager');


INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES (
  'Calendar Categories',
  '{"title":"Calendar Categories","header":[{"type":"button","label":"Add Category","formName":"Calendar Category"}],"body":[{"type":"table","options":{"tableName":"calendar_categories","showGlobalSearch":false,"addButton":false,"editFormId":74}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-tags',
  'Calendar Categories',
  'Calendar Categories'
);




INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES (
  'Inspection Templates',
  '{"title":"Inspection Templates","header":[{"type":"button","label":"Add Template","formName":"Inspection Template"}],"body":[{"type":"table","options":{"tableName":"inspection_templates","showGlobalSearch":false,"addButton":false,"editFormId":70}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-clipboard-list',
  'Inspection Templates',
  'Inspection Templates'
);



INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description)
VALUES (
  'OHS Incident Statuses',
  '{"title":"OHS Incident Statuses","header":[{"type":"button","label":"Add Incident Status","formName":"Incident Status"}],"body":[{"type":"table","options":{"tableName":"ohs_incident_statuses","showGlobalSearch":false,"addButton":false,"editFormId":72}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-clipboard-check',
  'OHS Incident Statuses',
  'OHS Incident Statuses'
);


INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description)
VALUES (
  'Corrective Action Tracking',
  '{"title":"Corrective Action Tracking","header":[{"type":"button","label":"Add Corrective Action","formName":"Corrective Action"}],"body":[{"type":"table","options":{"tableName":"corrective_actions","columnsToShow":["incident_id","name","description","steps","responsible_user_id","status"],"showGlobalSearch":false}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-list-check',
  'Corrective Action Tracking',
  'Corrective Action Tracking'
);



-- Insert Incidents by classification modal referencing saved graph
INSERT INTO modules
  (name, config, org_id, branch_id, icon, aria_label, description)
VALUES (
  'Incidents by classification',
  '{"title":"Incidents by classification","body":[{"type":"graph-d3","graphId":1}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL, NULL, 'fa-chart-line', 'Incidents by classification', 'Incidents by classification');

-- Insert Incident Trends modal referencing second graph
INSERT INTO modules
  (name, config, org_id, branch_id, icon, aria_label, description)
VALUES (
  'Incident Trends',
  '{"title":"Incident Trends","body":[{"type":"graph-d3","graphId":2,"options":{"timeUnits":["day","week","month","year"]}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL, NULL, 'fa-chart-bar', 'Incident Trends', 'Incident Trends');

INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES ('Workplace Registration','{"title":"Workplace Registration","header":[{"type":"button","label":"New Registration","formName":"Workplace Registration"}],"body":[{"type":"table","options":{"tableName":"workplace_registrations","rowClick":"selectRecord","rowActions":[{"label":"Detail","onClick":"openSelectedDetail"},{"label":"Invoice","onClick":"openWorkplaceInvoiceForm"},{"label":"Review","onClick":"openWorkplaceReview"}],"inlineEdit":true,"editFormId":98}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL,NULL,'fa-building','Workplace Registration','Workplace Registration');


INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES (
  'Inspection Request',
  '{"title":"Inspection Request","header":[{"type":"button","label":"Add Request","formName":"Inspection Request"}],"body":[{"type":"table","options":{"tableName":"inspection_requests","rowClick":"selectRecord","rowActions":[{"label":"Detail","onClick":"openSelectedDetail"}],"inlineEdit":true,"editFormId":99}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL, NULL, 'fa-clipboard-list', 'Inspection Request', 'Inspection Request');


INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES (
  'WorkCOM Inspection Assignment',
  '{"title":"Assign Inspector","header":[{"type":"button","label":"Add Assignment","formName":"WorkCOM Inspection Assignment"}],"body":[{"type":"table","options":{"tableName":"workplace_inspections","showGlobalSearch":false,"addButton":false,"editFormId":100}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL, NULL, 'fa-user-check', 'WorkCOM Inspection Assignment', 'WorkCOM Inspection Assignment');

-- WorkCOM OHS Inspections modal with Assign Inspector action
INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES (
  'WorkCOM OHS Inspections',
  '{"title":"WorkCOM OHS Inspections","header":[{"type":"button","label":"New Inspection","wizardId":5}],"body":[{"type":"table","options":{"tableName":"workplace_inspections","showGlobalSearch":false,"addButton":false,"rowActions":[{"label":"Assign Inspector","formName":"WorkCOM Inspection Assignment"}]}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL, NULL, 'fa-clipboard-check', 'WorkCOM OHS Inspections', 'WorkCOM OHS Inspections');


INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES (
  'Workplace Notice',
  '{"title":"Workplace Notice","body":[{"type":"form","formName":"Workplace Notice"}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL, NULL, 'fa-file-invoice', 'Workplace Notice', 'Workplace Notice');


INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES (
  'Safety Incident Types',
  '{"title":"Safety Incident Types","header":[{"type":"button","label":"Add Type","formName":"Safety Incident Type"}],"body":[{"type":"table","options":{"tableName":"safety_incident_types","showGlobalSearch":false,"addButton":false,"editFormId":105}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL, NULL, 'fa-list', 'Safety Incident Types', 'Safety Incident Types'
);


-- Workplace Registration modal
INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES ('Workplace Registration','{"title":"Workplace Registration","header":[{"type":"button","label":"New Registration","formName":"Workplace Registration"}],"body":[{"type":"table","options":{"tableName":"workplace_registrations","rowClick":"selectRecord","rowActions":[{"label":"Detail","onClick":"openSelectedDetail"},{"label":"Invoice","onClick":"openWorkplaceInvoiceForm"},{"label":"Review","onClick":"openWorkplaceReview"}],"inlineEdit":true,"editFormId":106}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',NULL,NULL,'fa-building','Workplace Registration','Workplace Registration');
-- Form Submission Review modal
INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES (
  'Form Submission Review',
  '{"title":"Form Submission Review","body":[{"type":"html","id":"formReviewMount","html":"<div id=\"formReviewMount\" data-submission-id=\"{{submissionId}}\"></div>"}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-clipboard-check',
  'Form Submission Review',
  'Form Submission Review'
);
INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES (
  'Certificates',
  '{"title":"Certificates","body":[{"type":"html","html":"<div id=\"certificatePreview\"></div><div id=\"certificatesMount\"></div>"}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-certificate',
  'Certificates',
  'Certificates'
);


INSERT INTO modules (module_id, name, config, org_id, branch_id, icon, aria_label, description)
VALUES (
  '0194a8b2-0017-7123-8123-123456789abc'::uuid,
  'Vendor Management',
  '{"title":"Vendor Management","header":[{"type":"button","label":"Add Vendor","formName":"Vendor"},{"type":"filter-select","id":"vendorFilter","options":{"source_table":"vendors","source_column":"vendor_id","display_column":"vendorname","data_column":"vendor_id","placeholder":"Search vendors...","default_label":"All Vendors"}},{"type":"filter-select","id":"vendorStatusFilter","options":{"data_column":"lifecycle_status","default_label":"All Statuses","options":[{"label":"Pending","value":"pending"},{"label":"Onboarding","value":"onboarding"},{"label":"Active","value":"active"},{"label":"Suspended","value":"suspended"},{"label":"Offboarded","value":"offboarded"}]}}],"body":[{"type":"html","html":"<div class=\"alert alert-info mb-4\"><span class=\"font-semibold\">Tip:</span> Pick a vendor from the dropdown to focus every tab. Use the lifecycle filter to narrow the vendor list before diving into contacts, documents, or performance.</div>"},{"type":"tabs","tabs":[{"label":"Vendors","elements":[{"type":"html","html":"<p class=\"text-sm text-gray-600 mb-3\">Use the filters above to focus on a lifecycle stage or specific vendor. Row actions open the profile or start editing without leaving this modal.</p>"},{"type":"table","options":{"tableName":"vendors","showGlobalSearch":true,"addButton":false,"editFormId":110,"filterField":["vendor_id","lifecycle_status"],"rowActions":[{"label":"Edit","formName":"Vendor"},{"label":"Open Detail","onClick":"openVendorDetail"}],"columnsToShow":["vendorname","businessRegNumber","lifecycle_status","avg_rating","last_reviewed_at"]}}]},{"label":"Contacts","elements":[{"type":"html","html":"<p class=\"text-sm text-gray-600 mb-3\">Select a vendor to see their contact roster. Mark one primary so reminders and workflows know who to reach out to.</p>"},{"type":"button","label":"Add Contact","formName":"Vendor Contact","prefillFilter":"vendor_id","class":"btn btn-primary btn-sm mb-3"},{"type":"table","options":{"tableName":"vendor_contacts","showGlobalSearch":false,"addButton":false,"editFormId":610,"filterField":"vendor_id","filterValue":{"vendor_id":"__none__"},"columnsToShow":["contact_name","contact_role","email","phone_number","is_primary"]}}]},{"label":"Addresses","elements":[{"type":"html","html":"<p class=\"text-sm text-gray-600 mb-3\">Track billing, shipping, and registered addresses so logistics and compliance teams stay aligned.</p>"},{"type":"button","label":"Add Address","formName":"Vendor Address","prefillFilter":"vendor_id","class":"btn btn-primary btn-sm mb-3"},{"type":"table","options":{"tableName":"vendor_addresses","showGlobalSearch":false,"addButton":false,"editFormId":611,"filterField":"vendor_id","filterValue":{"vendor_id":"__none__"},"columnsToShow":["address_type","line1","city","state_region","country_code","is_primary"]}}]},{"label":"Capabilities","elements":[{"type":"html","html":"<p class=\"text-sm text-gray-600 mb-3\">Log competencies, certifications, and experience to drive better RFQ shortlists.</p>"},{"type":"button","label":"Add Capability","formName":"Vendor Capability","prefillFilter":"vendor_id","class":"btn btn-primary btn-sm mb-3"},{"type":"table","options":{"tableName":"vendor_capabilities","showGlobalSearch":false,"addButton":false,"editFormId":612,"filterField":"vendor_id","filterValue":{"vendor_id":"__none__"},"columnsToShow":["capability_category","experience_years","competency_score","capacity_notes"]}}]},{"label":"Documents","elements":[{"type":"html","html":"<p class=\"text-sm text-gray-600 mb-3\">Keep compliance documents current. Expiring records appear here first so you can chase renewals.</p>"},{"type":"button","label":"Add Document","formName":"Vendor Document","prefillFilter":"vendor_id","class":"btn btn-primary btn-sm mb-3"},{"type":"table","options":{"tableName":"vendor_documents","showGlobalSearch":false,"addButton":false,"editFormId":613,"filterField":"vendor_id","filterValue":{"vendor_id":"__none__"},"columnsToShow":["doc_type","filetype","validity"]}}]},{"label":"Certificates","elements":[{"type":"html","html":"<p class=\"text-sm text-gray-600 mb-3\">Track certification renewals and attach evidence for compliance reviews.</p>"},{"type":"button","label":"Add Certificate","formName":"Vendor Certificate","prefillFilter":"vendor_id","class":"btn btn-primary btn-sm mb-3"},{"type":"table","options":{"tableName":"vendor_certificates","showGlobalSearch":false,"addButton":false,"editFormId":616,"filterField":"vendor_id","filterValue":{"vendor_id":"__none__"},"columnsToShow":["certificate_name","issued_at","expiry_date"]}}]},{"label":"Supporting Docs","elements":[{"type":"html","html":"<p class=\"text-sm text-gray-600 mb-3\">Store questionnaires, insurance, and policy artefacts so onboarding evidence is one click away.</p>"},{"type":"button","label":"Add Supporting Doc","formName":"Vendor Supporting Document","prefillFilter":"vendor_id","class":"btn btn-primary btn-sm mb-3"},{"type":"table","options":{"tableName":"vendor_supporting_docs","showGlobalSearch":false,"addButton":false,"editFormId":614,"filterField":"vendor_id","filterValue":{"vendor_id":"__none__"},"columnsToShow":["type","filetype","validity"]}}]},{"label":"Performance","elements":[{"type":"html","html":"<p class=\"text-sm text-gray-600 mb-3\">Log periodic KPI reviews to monitor delivery trends and trigger requalification when scores fall.</p>"},{"type":"button","label":"Log Metric","formName":"Vendor Performance Metric","prefillFilter":"vendor_id","class":"btn btn-primary btn-sm mb-3"},{"type":"table","options":{"tableName":"vendor_performance_metrics","showGlobalSearch":false,"addButton":false,"editFormId":615,"filterField":"vendor_id","filterValue":{"vendor_id":"__none__"},"columnsToShow":["kpi_name","rating","period_start","period_end","reviewer_id"]}}]}]}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-store',
  'Vendor Management',
  'Vendor Management'
);

INSERT INTO modules (module_id, name, config, org_id, branch_id, icon, aria_label, description)
VALUES (
  '0194a8b2-0020-7123-8123-123456789abc'::uuid,
  'RFQ Templates',
  '{"title":"RFQ Templates","header":[{"type":"button","label":"Add Template","formName":"RFQ Template"},{"type":"filter-select","id":"templateFilter","options":{"source_table":"rfq_templates","source_column":"rfq_template_id","display_column":"name","data_column":"rfq_template_id","placeholder":"Select template...","default_label":"All Templates"}}],"body":[{"type":"html","html":"<div class=\"alert alert-info mb-4\"><span class=\"font-semibold\">Tip:</span> Define reusable sections once and reuse them across every RFQ. Use the template filter to scope sections, preview content, and manage attachments before issuing a request.</div>"},{"type":"tabs","tabs":[{"label":"Overview","elements":[{"type":"table","options":{"tableName":"rfq_templates","showGlobalSearch":true,"addButton":false,"editFormId":620,"filterField":"rfq_template_id","columnsToShow":["name","category","is_default","valid_from","valid_until"]}}]},{"label":"Sections","elements":[{"type":"html","html":"<p class=\"text-sm text-gray-600 mb-3\">Break the RFQ into modular sections (scope, schedule, evaluation) so teams can tailor content per category.</p>"},{"type":"button","label":"Add Section","formName":"RFQ Template Section","prefillFilter":"rfq_template_id","class":"btn btn-primary btn-sm mb-3"},{"type":"table","options":{"tableName":"rfq_template_sections","showGlobalSearch":false,"addButton":false,"editFormId":621,"filterField":"rfq_template_id","columnsToShow":["heading","section_key","sort_order","is_required","include_in_print"]}}]},{"label":"Preview","elements":[{"type":"html","html":"<p class=\"text-sm text-gray-600 mb-3\">Sections render below in sort order so you can review the narrative before publishing the template.</p>"},{"type":"table","options":{"tableName":"rfq_template_sections","showGlobalSearch":false,"addButton":false,"editFormId":621,"filterField":"rfq_template_id","columnsToShow":["sort_order","heading","body_markdown","body_html"]}}]},{"label":"Attachments","elements":[{"type":"html","html":"<p class=\"text-sm text-gray-600 mb-3\">Attach boilerplate documents like NDAs or compliance packs that should accompany the RFQ.</p>"},{"type":"button","label":"Add Attachment","formName":"RFQ Template Attachment","prefillFilter":"rfq_template_id","class":"btn btn-primary btn-sm mb-3"},{"type":"table","options":{"tableName":"rfq_template_attachments","showGlobalSearch":false,"addButton":false,"editFormId":622,"filterField":"rfq_template_id","columnsToShow":["label","filetype","include_when","sort_order"]}}]}]}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-file-contract',
  'RFQ Templates',
  'Manage RFQ templates'
);


INSERT INTO modules (module_id, name, config, org_id, branch_id, icon, aria_label, description) VALUES (
'0194a8b2-0fff-7123-8123-123456789afe'::uuid,
'Customer Management',
'{"title":"Customer Management","header":[{"type":"button","label":"Add Customer","formName":"Customer"}],"body":[{"type":"table","options":{"tableName":"customers","showGlobalSearch":false,"addButton":false,"editFormId":109,"rowActions":[{"label":"Pay","onClick":"payCustomer"}]}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
NULL,
NULL,
'fa-users',
'Customer Management',
'Customer Management'
);



-- Roster Management module (JavaScript-based)
INSERT INTO modules (module_id, name, config, org_id, branch_id, icon, aria_label, description, isDeleted) VALUES (
  '0194a8b2-0120-7123-8123-123456789abc'::uuid,
  'Roster',
  $json$
  {
    "title": "Roster Management",
    "modulePath": "roster",
    "type": "javascript",
    "module": "Roster",
    "header": [
      {
        "type": "filter-select",
        "options": {
          "source_table": "branches",
          "source_column": "branch_id", 
          "display_column": "name",
          "data_column": "branch_id",
          "data_column_id": "selected_branch_id",
          "placeholder": "Select Branch...",
          "default_label": "All Branches",
          "search_fields": ["name"],
          "class": "flex-1 mr-2"
        }
      },
      {
        "type": "filter-date-range",
        "options": {
          "data_column": "date",
          "label": "Date",
          "single_date": true,
          "class": "flex-1 ml-2"
        }
      }
    ],
    "body": [
      {
        "type": "table",
        "options": {
          "tableName": "roster_employees",
          "showGlobalSearch": false,
          "addButton": false,
          "columnsToShow": ["employee_name_1", "employee_name_2", "employee_name_3"],
          "columnLabels": {
            "employee_name_1": "Employee Name 1",
            "employee_name_2": "Employee Name 2", 
            "employee_name_3": "Employee Name 3"
          }
        }
      }
    ],
    "footer": [
      {
        "type": "button",
        "label": "Export Schedule",
        "onClick": "exportRosterToExcel",
        "icon": "fa-download",
        "class": "btn btn-outline btn-success"
      },
      {
        "type": "button",
        "label": "Close",
        "onClick": "closeModal"
      }
    ]
  }
  $json$::jsonb,
  NULL,
  NULL,
  'fa-calendar-week',
  'Roster Management',
  'Manage employee shifts and schedules',
  FALSE
)
ON CONFLICT (module_id) DO UPDATE SET
  config = EXCLUDED.config,
  isDeleted = EXCLUDED.isDeleted;


-- Departments module
INSERT INTO modules (module_id, name, config, org_id, branch_id, icon, aria_label, description)
SELECT
  '0194a8b2-0018-7123-8123-123456789abc'::uuid,
  'Departments',
  '{"title":"Departments","header":[{"type":"button","label":"Add Department","formName":"Department"}],"body":[{"type":"table","options":{"tableName":"departments","showGlobalSearch":false,"addButton":false,"editFormId":121,"rowClick":"selectRecord","rowActions":[{"label":"Detail","onClick":"openSelectedDetail"}]}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-building',
  'Departments',
  'Manage organizational departments'
WHERE NOT EXISTS (SELECT 1 FROM modules WHERE module_id = '0194a8b2-0018-7123-8123-123456789abc'::uuid);


-- Product Management module
INSERT INTO modules (module_id, name, config, org_id, branch_id, icon, aria_label, description)
VALUES (
  '0194a8b2-c3f1-7123-8123-123456789ab1'::uuid,
  'Products',
  '{"title":"Products","header":[
    {
      "type": "filter-select",
      "options": {
        "source_table": "products",
        "source_column": "name",
        "display_column": "name",
        "data_column": "name",
        "data_column_id": "selected_product_id",
        "placeholder": "Search products by name...",
        "search_fields": ["name", "brand", "sku", "product_number"],
        "max_results": 25,
        "debounce_ms": 250,
        "populateMode": "immediate"
      }
    },
    {"type":"button",
      "label":"Add Product",
      "formName":"Product"},
    {"type":"button",
      "label":"Auto Orders",
      "formName":"Auto Order"},
    {"type":"button",
      "label":"Generate Barcode",
      "action":"products:generate-barcode"},
    {"type":"button",
      "label":"Generate QR Code",
      "action":"products:generate-qrcode"},
    {"type":"button",
      "label":"Import Products",
      "onClick":"importProducts",
      "class":"btn-outline btn-info"},
    {"type":"button",
      "label":"Export Products",
      "onClick":"exportProducts",
      "class":"btn-outline btn-success"}
  ],

  "body":[
    {"type":"tabs",
  "tabs":[
    {"label":"Products",
  "elements":[
  {"type":"table",
  "options":{
  "tableName":"products",
  "showGlobalSearch":true,
  "addButton":false,
  "editFormId":111,
  "filterField": "name",
  "listenColumn": "name",
  "limit": 1000,
  "columns":[
    {"field":"name","label":"Name"},
    {"field":"price","label":"Price"},
    {"field":"brand","label":"Brand"},
    {"field":"tax_rates","label":"Tax Rates","renderer":"json","rendererOptions":{"maxInlineItems":3}}
  ],
  "rowActions":[
    {"label":"Discount","formId":150,"icon":"fa-tags","class":"btn-sm btn-info"}
  ]}
      }
    ]
  },

    {"label":"Auto Orders",
  "elements":[
    {"type":"table",
  "options":{"tableName":"auto_orders",
  "showGlobalSearch":false,"addButton":false,"editFormId":131,
  "limit": 1000,
  "columnsToShow":[
  "product_name","minimum_stock_qty","order_qty"]
            }
          }
        ]
      }
    ]
  }
  ],
  
  "footer":[
  {"type":"button","label":"Close","onClick":"closeModal"}
    ]
  }',

  
  NULL,
  NULL,
  'fa-box',
  'Products',
  'Products'
);


-- Quotations module
INSERT INTO modules (name, config, icon, aria_label, description)
VALUES (
  'Quotations',
  $json${
    "title": "Quotations Management",
    "modulePath": "quotations",
    "header": [
      {
        "type": "button",
        "label": "New Quotation",
        "icon": "fa-plus",
        "class": "btn btn-primary",
        "action": "openQuotationForm",
        "ariaLabel": "Create new quotation"
      },
      {
        "type": "filter-select",
        "options": {
          "data_column": "status",
          "label": "Status",
          "options": [
            {"label": "All", "value": ""},
            {"label": "Draft", "value": "draft"},
            {"label": "Sent", "value": "sent"},
            {"label": "Accepted", "value": "accepted"},
            {"label": "Rejected", "value": "rejected"},
            {"label": "Expired", "value": "expired"},
            {"label": "Converted", "value": "converted"}
          ]
        }
      },
      {
        "type": "filter-date-range",
        "options": {
          "data_column": "date",
          "label": "Date Range"
        }
      },
      {
        "type": "button",
        "label": "Refresh",
        "icon": "fa-sync",
        "class": "btn btn-ghost",
        "action": "refresh",
        "ariaLabel": "Refresh quotations list"
      },
      {
        "type": "button",
        "label": "Transactions",
        "icon": "fa-receipt",
        "class": "btn btn-info",
        "action": "showTaxCoreTransactions",
        "ariaLabel": "View TaxCore transaction history"
      },
      {
        "type": "button",
        "label": "TaxCore Settings",
        "icon": "fa-cog",
        "class": "btn btn-secondary",
        "action": "showTaxCoreSettings",
        "ariaLabel": "Configure TaxCore settings"
      }
    ],
    "body": [
      {
        "type": "table",
        "id": "quotationsTable",
        "options": {
          "tableName": "quotations",
          "primaryKeyField": "quotation_id",
          "showGlobalSearch": true,
          "columnsToShow": ["quotation_number", "date", "customer_id", "total_amount", "tax_amount", "status", "sent_at", "expires_at"],
          "columnLabels": {
            "quotation_number": "Quote #",
            "date": "Date",
            "customer_id": "Customer",
            "total_amount": "Amount",
            "tax_amount": "Tax",
            "status": "Status",
            "sent_at": "Sent",
            "expires_at": "Expires"
          },
          "rowClick": "selectRecord",
          "rowActions": [
            {
              "label": "View",
              "icon": "fa-eye",
              "class": "btn btn-info btn-xs",
              "action": "openSelectedDetail",
              "ariaLabel": "View quotation details"
            },
            {
              "label": "Send",
              "icon": "fa-paper-plane",
              "class": "btn btn-primary btn-xs",
              "action": "quotations:send",
              "condition": "status == \"draft\"",
              "confirm": "Send this quotation to the customer?",
              "ariaLabel": "Send quotation to customer"
            },
            {
              "label": "Convert",
              "icon": "fa-file-invoice",
              "class": "btn btn-success btn-xs",
              "action": "quotations:convert",
              "condition": "status == \"sent\" || status == \"accepted\"",
              "confirm": "Convert this quotation to an invoice?",
              "ariaLabel": "Convert quotation to invoice"
            },
            {
              "label": "Accept",
              "icon": "fa-check",
              "class": "btn btn-success btn-xs",
              "action": "quotations:accept",
              "condition": "status == \"sent\"",
              "confirm": "Accept this quotation?",
              "ariaLabel": "Accept quotation"
            },
            {
              "label": "Reject",
              "icon": "fa-times",
              "class": "btn btn-error btn-xs",
              "action": "quotations:reject",
              "condition": "status == \"sent\"",
              "confirm": "Reject this quotation?",
              "ariaLabel": "Reject quotation"
            },
            {
              "label": "Duplicate",
              "icon": "fa-copy",
              "class": "btn btn-ghost btn-xs",
              "action": "quotations:duplicate",
              "ariaLabel": "Duplicate quotation"
            },
            {
              "label": "PDF",
              "icon": "fa-file-pdf",
              "class": "btn btn-secondary btn-xs",
              "action": "quotations:pdf",
              "ariaLabel": "Download quotation PDF"
            },
            {
              "label": "Delete",
              "icon": "fa-trash",
              "class": "btn btn-error btn-xs btn-outline",
              "action": "records:delete",
              "condition": "status == \"draft\" || status == \"expired\"",
              "confirm": "Are you sure you want to delete this quotation?",
              "ariaLabel": "Delete quotation"
            }
          ]
        }
      }
    ],
    "footer": [
      {
        "type": "button",
        "label": "Close",
        "class": "btn btn-ghost",
        "action": "close",
        "ariaLabel": "Close quotations module"
      }
    ],
    "dataSources": {
      "quotations": {
        "table": "quotations",
        "syncPolicy": "default",
        "autoRefresh": true,
        "refreshInterval": 30000
      }
    }
  }$json$::jsonb,
  'fa-file-alt',
  'Quotations Management',
  'Create, send, and manage quotations. Convert quotations to invoices.'
);


-- Invoices module
INSERT INTO modules (name, config, icon, aria_label, description)
VALUES (
  'Invoices',
  $json${
    "title": "Invoices Management",
    "modulePath": "invoices",
    "header": [
      {
        "type": "button",
        "label": "New Invoice",
        "icon": "fa-plus",
        "class": "btn btn-primary",
        "action": "openInvoiceForm",
        "ariaLabel": "Create new invoice"
      },
      {
        "type": "filter-select",
        "options": {
          "data_column": "status",
          "label": "Status",
          "options": [
            {"label": "All", "value": ""},
            {"label": "Draft", "value": "draft"},
            {"label": "Pending", "value": "pending"},
            {"label": "Submitted", "value": "submitted"},
            {"label": "Paid", "value": "paid"},
            {"label": "Overdue", "value": "overdue"},
            {"label": "Cancelled", "value": "cancelled"}
          ]
        }
      },
      {
        "type": "filter-select",
        "options": {
          "data_column": "is_proforma",
          "label": "Type",
          "options": [
            {"label": "All", "value": ""},
            {"label": "Standard", "value": "false"},
            {"label": "Proforma", "value": "true"},
            {"label": "Advance Payment", "value": "advance"},
            {"label": "Refund", "value": "refund"}
          ]
        }
      },
      {
        "type": "filter-date-range",
        "options": {
          "data_column": "invoice_date",
          "label": "Date Range"
        }
      },
      {
        "type": "button",
        "label": "Refresh",
        "icon": "fa-sync",
        "class": "btn btn-ghost",
        "action": "refresh",
        "ariaLabel": "Refresh invoices list"
      },
      {
        "type": "button",
        "label": "Transactions",
        "icon": "fa-receipt",
        "class": "btn btn-info",
        "action": "showTaxCoreTransactions",
        "ariaLabel": "View TaxCore transaction history"
      },
      {
        "type": "button",
        "label": "TaxCore Settings",
        "icon": "fa-cog",
        "class": "btn btn-secondary",
        "action": "showTaxCoreSettings",
        "ariaLabel": "Configure TaxCore settings"
      }
    ],
    "body": [
      {
        "type": "table",
        "id": "invoicesTable",
        "options": {
          "tableName": "invoices",
          "primaryKeyField": "invoice_id",
          "showGlobalSearch": true,
          "columnsToShow": ["invoice_number", "invoice_date", "name", "amount", "amount_paid", "status", "is_proforma", "taxcore_submission_id", "sent_at"],
          "columnLabels": {
            "invoice_number": "Invoice #",
            "invoice_date": "Date",
            "name": "Customer",
            "amount": "Amount",
            "amount_paid": "Paid",
            "status": "Status",
            "is_proforma": "Proforma",
            "taxcore_submission_id": "TaxCore ID",
            "sent_at": "Sent"
          },
          "rowClick": "selectRecord",
          "rowActions": [
            {
              "label": "View",
              "icon": "fa-eye",
              "class": "btn btn-info btn-xs",
              "action": "openSelectedDetail",
              "ariaLabel": "View invoice details"
            },
            {
              "label": "Submit to TaxCore",
              "icon": "fa-upload",
              "class": "btn btn-primary btn-xs",
              "action": "invoices:submit-taxcore",
              "condition": "status == \"draft\" && taxcore_submission_id == null",
              "confirm": "Submit this invoice to the tax authority?",
              "ariaLabel": "Submit invoice to tax authority"
            },
            {
              "label": "TaxCore Receipt",
              "icon": "fa-receipt",
              "class": "btn btn-success btn-xs",
              "action": "invoices:taxcore-receipt",
              "condition": "taxcore_submission_id != null",
              "ariaLabel": "View TaxCore receipt"
            },
            {
              "label": "Record Payment",
              "icon": "fa-credit-card",
              "class": "btn btn-success btn-xs",
              "action": "payments:initiate",
              "condition": "status != \"paid\" && status != \"cancelled\"",
              "ariaLabel": "Record payment for invoice"
            },
            {
              "label": "PDF",
              "icon": "fa-file-pdf",
              "class": "btn btn-secondary btn-xs",
              "action": "invoices:pdf",
              "ariaLabel": "Download invoice PDF"
            },
            {
              "label": "Cancel",
              "icon": "fa-ban",
              "class": "btn btn-error btn-xs btn-outline",
              "action": "records:cancel",
              "condition": "status != \"paid\" && status != \"cancelled\"",
              "confirm": "Are you sure you want to cancel this invoice?",
              "ariaLabel": "Cancel invoice"
            }
          ]
        }
      }
    ],
    "footer": [
      {
        "type": "button",
        "label": "Close",
        "class": "btn btn-ghost",
        "action": "close",
        "ariaLabel": "Close invoices module"
      }
    ],
    "dataSources": {
      "invoices": {
        "table": "invoices",
        "syncPolicy": "default",
        "autoRefresh": true,
        "refreshInterval": 30000
      }
    }
  }$json$::jsonb,
  'fa-file-invoice',
  'Invoices Management',
  'Create, submit, and manage invoices. Integrate with TaxCore for tax submissions.'
);


-- Auto Orders module
INSERT INTO modules (module_id, name, config, org_id, branch_id, icon, aria_label, description) VALUES (
  '0194a8b2-a1b2-7123-8123-123456789abc'::uuid,
  'Auto Orders',
  '{"title":"Auto Orders","header":[{"type":"button","label":"Add Auto Order","formName":"Auto Order"}],"body":[{"type":"table","options":{"tableName":"auto_orders","showGlobalSearch":false,"addButton":false,"editFormId":131}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-shopping-cart',
  'Auto Orders',
  'Manage Auto Orders for Products'
);


-- Software Info module
INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES (
  'Software Info',
  '{"title":"Software Info","header":[{"type":"button","label":"Add Software Info","formName":"Software Info"}],"body":[{"type":"table","options":{"tableName":"software_info","showGlobalSearch":false,"addButton":false,"editFormId":112}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-info-circle',
  'Software Info',
  'Software Info'
);


-- POS Settings module with transaction import/export
INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description)
VALUES (
  'POS Settings',
  '{"title":"POS Settings","header":[{"type":"button","label":"Edit Settings","formName":"POS Settings"},{"type":"button","label":"Import Transactions","onClick":"importPOSTransactions","class":"btn-outline btn-info","icon":"fa-upload"},{"type":"button","label":"Export Transactions","onClick":"exportPOSTransactions","class":"btn-outline btn-success","icon":"fa-download"}],"body":[{"type":"tabs","tabs":[{"label":"Settings","elements":[{"type":"table","options":{"tableName":"pos_settings","showGlobalSearch":false,"addButton":false,"editFormId":113}}]},{"label":"Sales Receipts","elements":[{"type":"table","options":{"tableName":"sales_receipts","showGlobalSearch":true,"addButton":false,"columnsToShow":["invoiceNumber","type","transactiontype","totalAmount","sdcDateTime","businessName"]}}]},{"label":"Transactions","elements":[{"type":"table","options":{"tableName":"lineitems_payments","showGlobalSearch":false,"addButton":false}}]}]}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-cash-register',
  'POS Settings',
  'POS Settings and transaction data management'
);

INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description)
VALUES (
  'Procurement',
  '{"title":"Procurement","header":[{"type":"button","label":"Add Procurement","formName":"Procurement","onSubmit":"closeModal"}],"body":[{"type":"table","options":{"tableName":"procurements","showGlobalSearch":false,"addButton":false,"editFormId":115}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-file-invoice-dollar',
  'Procurement',
  'Procurement Management'
);


-- Restaurant Products module
INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES (
  'Restaurant Products',
  '{
    "title": "Restaurant Products",
    "header": [
      {
        "type": "button",
        "label": "Add Ingredient",
        "formName": "Ingredients"
      },
      {
        "type": "button",
        "label": "Add Product",
        "formName": "Restaurant Product"
      }
    ],
    "body": [
      {
        "type": "tabs",
        "tabs": [
          {
            "label": "Ingredients",
            "elements": [
              {
                "type": "table",
                "options": {
                  "tableName": "ingredients",
                  "editFormId": 116
                }
              }
            ]
          },
          {
            "label": "Products",
            "elements": [
              {
                "type": "table",
                "options": {
                  "tableName": "products",
                  "editFormId": 114
                }
              }
            ]
          }
        ]
      }
    ],
    "footer": [
      {
        "type": "button",
        "label": "Close",
        "onClick": "closeModal"
      }
    ]
  }',
  NULL,
  NULL,
  'fa-utensils',
  'Restaurant Products',
  'Restaurant Products'
);

  -- Purchase Order Module
  INSERT INTO modules (module_id,name, config, org_id, branch_id, icon, aria_label, description) VALUES (
    '0194a8b2-acd0-7123-8123-123456789acd'::uuid, 'Purchase Orders',
    '{"title":"Purchase Orders","header":[{"type":"button","label":"Add Purchase Order","formId":130}],"body":[{"type":"table","options":{"tableName":"purchase_orders","showGlobalSearch":false,"addButton":false,"editFormId":130}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
    NULL,
    NULL,
    'fa-file-invoice-dollar',
    'Purchase Orders',
    'Manage purchase orders'
  );


-- Employee Profile Modal
INSERT INTO modules (name, config, org_id, branch_id) VALUES (
  'Employee Profile',
  '{
    "title": "Employee Profile",
    "header": [
      {
        "type": "button",
        "label": "Add Employee",
        "formName": "Employee Form"
      }
    ],
    "body": [
      {
        "type": "table",
        "options": {
          "tableName": "Employees",
          "showGlobalSearch": true,
          "addButton": false,
          "editFormId": 113
        }
      }
    ],
    "footer": [
      {
        "type": "button",
        "label": "Close",
        "onClick": "closeModal"
      }
    ]
  }',
  NULL,
  NULL
);


-- Open Positions Modal
INSERT INTO modules (module_id, name, config, org_id, branch_id, icon, aria_label, description) VALUES (
  '6861955c-f882-44db-ab95-89c1a9b8e307'::uuid,
  'Open Positions',
  '{
    "title": "Open Positions",
    "body": [
      {
        "type": "tabs",
        "tabs": [
          {
            "label": "Positions",
            "elements": [
              {
                "type": "button",
                "label": "Add Position",
                "formId": 117
              },
              {
                "type": "table",
                "options": {
                  "tableName": "open_positions",
                  "showGlobalSearch": true,
                  "editFormId": 117
                }
              }
            ]
          },
          {
            "label": "Applications",
            "elements": [
              {
                "type": "button",
                "label": "Add Application",
                "formId": 118
              },
              {
                "type": "table",
                "options": {
                  "tableName": "applications",
                  "showGlobalSearch": true,
                  "editFormId": 118,
                  "multiselect": true,
                  "rowActions": [
                    {
                      "label": "ShortList",
                      "onClick": "shortlistApplication"
                    }
                  ]
                }
              }
            ]
          },
          {
            "label": "Interview",
            "elements": [
              {
                "type": "button",
                "label": "Schedule Interview",
                "formId": 119
              },
              {
                "type": "table",
                "options": {
                  "tableName": "interviews",
                  "showGlobalSearch": true,
                  "editFormId": 119
                }
              }
            ]
          },
          {
            "label": "New Employee",
            "elements": [
              {
                "type": "button",
                "label": "Add New Employee",
                "formId": 140
              },
              {
                "type": "table",
                "options": {
                  "tableName": "users_profiles",
                  "showGlobalSearch": true,
                  "editFormId": 140
                }
              }
            ]
          }
        ]
      }
    ],
    "footer": [
      {
        "type": "button",
        "label": "Close",
        "onClick": "closeModal"
      }
    ]
  }',
  NULL,
  NULL,
  'fa-briefcase',
  'Open Positions',
  'Manage open job positions'
);


-- Default Policies module
INSERT INTO modules (
    name,
    config,
    org_id,
    branch_id,
    icon,
    aria_label,
    description
) VALUES (
    'Policies',
    '{
  "title": "Policies",
  "header": [
    {
      "type": "html",
      "html": "<h3 class=\"text-lg font-bold\">Policies Management</h3>"
    }
  ],
  "body": [
    {
      "type": "table",
      "options": {
        "tableName": "policies",
        "showGlobalSearch": true,
        "editFormId": 1,
        "syncManager": {},
        "rowActions": [
          {
            "label": "Edit",
            "formId": 1
          },
          {
            "label": "Delete",
            "action": "delete"
          }
        ]
      }
    },
    {
      "type": "form",
      "formId": 1,
      "options": {
        "submitText": "Save Policy"
      },
      "elements": [
        {
          "label": "Title",
          "field_name": "title",
          "data_column": "title",
          "type_id": 1,
          "order_index": 1,
          "required": true
        },
        {
          "label": "Content",
          "field_name": "content",
          "data_column": "content",
          "type_id": 7,
          "order_index": 2
        },
        {
          "label": "Content Type",
          "field_name": "content_type",
          "data_column": "content_type",
          "type_id": 9,
          "order_index": 3,
          "options_table": null,
          "options": ["html", "pdf"]
        },
        {
          "label": "Policy Type",
          "field_name": "policy_type",
          "data_column": "policy_type",
          "type_id": 1,
          "order_index": 4
        },
        {
          "label": "PDF URL",
          "field_name": "pdf_url",
          "data_column": "pdf_url",
          "type_id": 1,
          "order_index": 5
        },
        {
          "label": "Language Code",
          "field_name": "language_code",
          "data_column": "language_code",
          "type_id": 1,
          "order_index": 6,
          "default": "en"
        },
        {
          "label": "Expiry Date",
          "field_name": "expiry_date",
          "data_column": "expiry_date",
          "type_id": 4,
          "order_index": 7
        },
        {
          "label": "Renewal Status",
          "field_name": "renewal_status",
          "data_column": "renewal_status",
          "type_id": 1,
          "order_index": 8
        },
        {
          "label": "Visible to Roles",
          "field_name": "visible_to_roles",
          "data_column": "visible_to_roles",
          "type_id": 1,
          "order_index": 9
        },
        {
          "label": "Visible to Group",
          "field_name": "visible_to_group",
          "data_column": "visible_to_group",
          "type_id": 1,
          "order_index": 10
        },
        {
          "label": "Visible to All",
          "field_name": "visible_to_all",
          "data_column": "visible_to_all",
          "type_id": 3,
          "order_index": 11
        },
        {
          "label": "Version",
          "field_name": "version",
          "data_column": "version",
          "type_id": 2,
          "order_index": 12,
          "default": 1
        }
      ]
    }
  ],
  "footer": [
    {
      "type": "button",
      "label": "Close",
      "onClick": "closeModal"
    },
    {
      "type": "button",
      "label": "Submit",
      "api": {
        "url": "/api/policies",
        "method": "POST"
      }
    }
  ]
}',
    NULL,
    NULL,
    'fa-file-text',
    'Policies',
    'Manage company policies'
);


-- RFQ Template Builder module
INSERT INTO modules (module_id, name, config, org_id, branch_id, icon, aria_label, description)
SELECT
  '0194a8b2-0021-7123-8123-123456789abc'::uuid,
  'RFQ Template Builder',
  $json$
  {
    "title": "RFQ Template Builder",
    "header": [
      { "type": "html", "html": "<div class=\"alert alert-info\"><span class=\"font-semibold\">Drag & Drop:</span> Create and edit RFQ templates by arranging sections and attachments. Use Preview to sanity-check the narrative.</div>" },
      { "type": "button", "label": "Open Builder", "onClick": "openRfqTemplateBuilder", "class": "btn btn-primary btn-sm" }
    ],
    "body": [
      { "type": "html", "id": "rfqTplBuilderRoot", "html": "<div id=\"rfqTplBuilderRoot\"></div>" }
    ],
    "footer": [ { "type": "button", "label": "Close", "onClick": "closeModal" } ]
  }
  $json$::jsonb,
  NULL, NULL,
  'fa-diagram-project', 'RFQ Template Builder', 'RFQ Template Builder'
WHERE NOT EXISTS (SELECT 1 FROM modules WHERE module_id = '0194a8b2-0021-7123-8123-123456789abc'::uuid);

-- RFQs list module
INSERT INTO modules (module_id, name, config, org_id, branch_id, icon, aria_label, description)
SELECT
  '0194a8b2-0030-7123-8123-123456789abc'::uuid,
  'RFQs',
  $json$
  {
    "title": "RFQs",
    "header": [
      { "type":"button","label":"Create From Template","onClick":"createRfqFromTemplate","class":"btn btn-primary" },
      { "type":"filter-select","options":{"data_column":"status","options":[{"label":"All","value":""},{"label":"Draft","value":"draft"},{"label":"Open","value":"open"},{"label":"Paused","value":"paused"},{"label":"Closed","value":"closed"},{"label":"Awarded","value":"awarded"}]}},
      { "type":"filter-date-range","options":{"data_column":"due_at"} }
    ],
    "body": [
      { "type":"table","options":{
        "tableName":"rfq_headers","showGlobalSearch":true,"addButton":false,
        "columnsToShow":["rfq_number","title","type","status","due_at"],
        "rowActions":[
          {"label":"Open","onClick":"openRfqDetail"},
          {"label":"Submit For Approval","onClick":"submitForApproval"},
          {"label":"Publish","onClick":"publishRfq"},
          {"label":"Pause","onClick":"pauseRfq"},
          {"label":"Resume","onClick":"resumeRfq"},
          {"label":"Close","onClick":"closeRfq"},
          {"label":"Remind","onClick":"remindVendors"}
        ]
      }}
    ],
    "footer":[{"type":"button","label":"Close","onClick":"closeModal"}]
  }
  $json$::jsonb,
  NULL, NULL, 'fa-file-contract', 'RFQs', 'RFQ list'
WHERE NOT EXISTS (SELECT 1 FROM modules WHERE module_id = '0194a8b2-0030-7123-8123-123456789abc'::uuid);

-- RFQ Detail module
INSERT INTO modules (module_id, name, config, org_id, branch_id, icon, aria_label, description)
SELECT
  '0194a8b2-0031-7123-8123-123456789abc'::uuid,
  'RFQ Detail',
  $json$
  {
    "title": "RFQ Detail",
    "header": [
      { "type":"button","label":"Generate Contract Draft","onClick":"generateRfqContract","class":"btn btn-primary btn-sm" },
      { "type":"button","label":"Open Latest Contract","onClick":"openLatestRfqContract","class":"btn btn-ghost btn-sm" }
    ],
    "body": [
      { "type":"tabs","tabs":[
        { "label":"Overview","elements":[
          { "type":"table","options":{"tableName":"rfq_headers","filterField":"rfq_id","columnsToShow":["title","type","status","due_at","category","currency","created_by_name"],"addButton":false} },
          { "type":"html","html":"<div class='divider my-2'>Attachments</div>" },
          { "type":"table","options": { "tableName":"rfq_attachments", "filterField":"rfq_id", "columnsToShow":["label","filetype","file_url","include_when"], "addButton": false } },
          { "type":"html","html":"<div class='divider my-2'>Invites &amp; Responses</div>" },
          { "type":"table","options": { "tableName":"rfq_invites", "filterField":"rfq_id", "columnsToShow":["vendor_name","contact_name","contact_email","contact_phone","status","sent_at","opened_at","responded_at"], "addButton": false } },
          { "type":"table","options": { "tableName":"vendor_quotes", "filterField":"rfq_id", "columnsToShow":["vendor_id","status"], "addButton": false } },
          { "type":"html","html":"<div class='divider my-2'>Recent Activity</div>" },
          { "type":"table","options": { "tableName":"rfq_events", "filterField":"rfq_id", "columnsToShow":["type","actor_type","created_at"], "addButton": false } },
          { "type":"html","html":"<div id='rfq-sections-preview' class='prose max-w-none mt-2'></div>" }
        ]},
        { "label":"Items","elements":[
          { "type":"button","label":"Add Item","onClick":"addRfqItem","class":"btn btn-primary btn-sm" },
          { "type":"table","options":{"tableName":"rfq_items","filterField":"rfq_id","columnsToShow":["description","quantity","uom","delivery_terms","delivery_location","is_optional"],"inlineEdit":true,"addButton":false} }
        ]},
        { "label":"Shortlist","elements":[
          { "type":"button","label":"Add Vendor","onClick":"addInvite","class":"btn btn-primary btn-sm" },
          { "type":"table","options":{"tableName":"rfq_invites","filterField":"rfq_id","columnsToShow":["vendor_name","contact_name","contact_email","contact_phone","status","sent_at","opened_at","responded_at"],"inlineEdit":true,"addButton":false} }
        ]},
        { "label":"Invitations","elements":[
          { "type":"button","label":"Remind Pending","onClick":"remindVendors","class":"btn btn-sm" },
          { "type":"table","options":{"tableName":"rfq_invites","filterField":"rfq_id","columnsToShow":["vendor_name","contact_name","contact_email","contact_phone","status","sent_at","opened_at","responded_at","reminder_count"],"addButton":false} }
        ]},
        { "label":"Responses","elements":[
          { "type":"html","html":"<div class='flex items-center gap-2 mb-2'><button class='btn btn-sm btn-warning' onclick=\"openTenderBoxForSelected()\">Open Tender Box</button><span class='text-xs opacity-70'>(Available after RFQ is closed)</span></div>" },
          { "type":"table","options":{
              "tableName":"vendor_quotes",
              "filterField":"rfq_id",
              "columnsToShow":["vendor_name","status"],
              "addButton":false,
              "rowActions":[ {"label":"Open Quote","onClick":"openVendorQuoteDetail"} ]
            } }
        ]},
        { "label":"Compare","elements":[ { "type":"html","html":"<div id='rfq-compare-matrix'></div>" } ]},
        { "label":"Contracts","elements":[
          { "type":"table","options":{
              "tableName":"rfq_contracts",
              "filterField":"rfq_id",
              "columnsToShow":["contract_number","vendor_name","status","total_value","currency","created_at"],
              "columnLabels": { "contract_number":"Contract #","vendor_name":"Vendor","total_value":"Total","created_at":"Created" },
              "addButton":false,
              "rowActions":[ {"label":"Open","onClick":"openContractDetail"} ]
            } }
        ]},
        { "label":"Timeline","elements":[ { "type":"table","options":{"tableName":"rfq_events","filterField":"rfq_id","addButton":false} } ]}
        ,
        { "label":"Messages","elements":[
          { "type":"html","html":"<div class='flex gap-2 mb-4'><button class='btn btn-sm' onclick=\"postInternalMessage()\">New Internal</button><button class='btn btn-sm btn-primary' onclick=\"postBroadcastMessage()\">New Broadcast</button></div>" },
          { "type":"html","html":"<div class='tabs tabs-boxed mb-4'><a class='tab tab-active' onclick=\"filterMessagesByType('all')\">All</a><a class='tab' onclick=\"filterMessagesByType('internal')\">Internal</a><a class='tab' onclick=\"filterMessagesByType('vendor')\">Vendor Q&A</a><a class='tab' onclick=\"filterMessagesByType('broadcast')\">Broadcast</a></div>" },
          { "type":"html","html":"<div id='rfq-messages-container' class='space-y-4 max-h-96 overflow-y-auto'></div>" },
       { "type":"table","id":"rfqMsgs","options": {"tableName":"rfq_messages","filterField":"rfq_id",
         "columnsToShow":["vendor_name","status","created_at","body_markdown"],
         "columnLabels": { "created_at": "Date", "body_markdown": "Messages" },
         "addButton":false,
          "rowActions":[{"label":"Approve","onClick":"approvePendingMessage"},{"label":"Reply","onClick":"replyToMessage"}] }, "hidden":true }
        ]}
      ]}
    ],
    "footer":[{"type":"button","label":"Close","onClick":"closeModal"}]
  }
  $json$::jsonb,
  NULL, NULL, 'fa-diagram-project', 'RFQ Detail', 'RFQ Detail'
WHERE NOT EXISTS (SELECT 1 FROM modules WHERE module_id = '0194a8b2-0031-7123-8123-123456789abc'::uuid);

-- Vendor Quote Detail (view-only) module
INSERT INTO modules (module_id, name, config, org_id, branch_id, icon, aria_label, description)
SELECT
  '0194a8b2-0032-7123-8123-123456789abc'::uuid,
  'Vendor Quote Detail',
  $json$
  {
    "title": "Vendor Quote Detail",
    "body": [
      { "type":"tabs","tabs":[
        { "label":"Summary","elements":[
          { "type":"detail-view", "tableName":"vendor_quotes", "filterField":"quote_id" },
          { "type":"html", "id":"aiQuoteActions", "html":"<div class='flex justify-between items-center my-2'><div class='font-semibold'>AI Analysis</div><div><button class='btn btn-sm btn-primary' onclick='summarizeVendorQuoteWithAI()'>Summarize with AI</button></div></div>" },
          { "type":"html", "id":"aiQuoteSummary", "html":"<div id='aiQuoteSummaryBody' class='prose prose-sm max-w-none whitespace-pre-wrap hidden'></div>" },
          { "type":"html", "html":"<div class='divider my-2'>Line Items</div>" },
          { "type":"table", "options": { "tableName":"vendor_quote_items", "filterField":"quote_id", "columnsToShow":["item_description","is_alternate","alt_label","unit_price","tax","lead_time_days","notes"], "addButton": false } }
        ]},
        { "label":"Attachments","elements":[
          { "type":"html", "html":"<div id='quote-attachments'><div data-role='attachments-list' class='space-y-1'></div></div>" }
        ]}
      ]}
    ],
    "footer":[{"type":"button","label":"Close","onClick":"closeModal"}]
  }
  $json$::jsonb,
  NULL, NULL, 'fa-file-circle-check', 'Vendor Quote Detail', 'View-only summary of a vendor quote'
WHERE NOT EXISTS (SELECT 1 FROM modules WHERE module_id = '0194a8b2-0032-7123-8123-123456789abc'::uuid);

-- Procurement Contract Detail module
INSERT INTO modules (module_id, name, config, org_id, branch_id, icon, aria_label, description)
SELECT
  '0194a8b2-1035-7123-8123-123456789abc'::uuid,
  'Procurement Contract Detail',
  $json$
  {
    "title": "Procurement Contract Detail",
    "body": [
      { "type":"detail-view", "tableName":"rfq_contracts", "filterField":"contract_id",
        "columnLabels": {
          "contract_number": "Contract #",
          "vendor_name": "Vendor",
          "status": "Status",
          "total_value": "Total Value",
          "currency": "Currency",
          "effective_date": "Effective",
          "expiry_date": "Expiry",
          "created_at": "Created",
          "updatedAt": "Updated"
        }
      },
  { "type":"html","id":"aiDraftActions","html":"<div class='flex justify-between items-center my-2'><div class='font-semibold'>AI Draft</div><div><button class='btn btn-sm btn-primary' onclick='generateContractAiDraft()'>Generate with AI</button> <button class='btn btn-sm btn-ghost' onclick='viewContractAiDraft()'>View Draft</button></div></div>" },
  { "type":"html","html":"<div class='divider my-2'>Summary</div>" },
  { "type":"html","id":"contractSummaryContainer","html":"<div id='contractSummary' class='grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3'></div>" },
  { "type":"html","html":"<div class='divider my-2'>Line Items</div>" },
  { "type":"html","id":"contractLineItems","html":"<div class='overflow-x-auto'><table class='table table-zebra w-full text-sm'><thead><tr><th>Description</th><th class='text-right'>Qty</th><th>UoM</th><th class='text-right'>Unit Price</th><th class='text-right'>Line Total</th></tr></thead><tbody id='contractLineItemsBody'><tr class='opacity-70'><td colspan='5'>No line items captured yet.</td></tr></tbody></table></div>" }
    ],
    "footer":[{"type":"button","label":"Close","onClick":"closeModal"}]
  }
  $json$::jsonb,
  NULL, NULL, 'fa-file-contract', 'Procurement Contract Detail', 'View of generated RFQ contract payload'
WHERE NOT EXISTS (SELECT 1 FROM modules WHERE module_id = '0194a8b2-1035-7123-8123-123456789abc'::uuid);

-- Service Types modal
INSERT INTO modules (name, config, org_id, branch_id, icon, aria_label, description) VALUES (
  'Service Types',
  '{"title":"Service Types","header":[{"type":"button","label":"Add Service Type","formName":"Service Type"}],"body":[{"type":"table","options":{"tableName":"service_types","showGlobalSearch":false,"addButton":false,"editFormId":31}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}',
  NULL,
  NULL,
  'fa-wrench',
  'Service Types',
  'Service Types'
);

-- Additional modules from Dashboard
INSERT INTO modules (module_id, name, config, org_id, branch_id, icon, aria_label, description) VALUES
  ('0194a8b2-0001-7123-8123-123456789abc'::uuid, 'SystemSettings', '{"title":"System Settings","body":[{"type":"html","html":"System settings content"}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}', NULL, NULL, 'fa-gear', 'System Settings', 'System Settings'),
  ('0194a8b2-0002-7123-8123-123456789abc'::uuid, 'WorkflowInstances', '{"title":"Workflow Instances","body":[{"type":"html","html":"Workflow instances content"}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}', NULL, NULL, 'fa-clock-rotate-left', 'Workflow Instances', 'Workflow Instances'),
  ('0194a8b2-0003-7123-8123-123456789abc'::uuid, 'CustomizeDashboard', '{"title":"Customize Dashboard","body":[{"type":"html","html":"Customize dashboard content"}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}', NULL, NULL, 'fa-pen-to-square', 'Customize Dashboard', 'Customize Dashboard'),
  ('0194a8b2-0004-7123-8123-123456789abc'::uuid, 'FormBuilder', '{"title":"Form Builder","body":[{"type":"html","html":"Form builder content"}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}', NULL, NULL, 'fa-wpforms', 'Form Builder', 'Form Builder'),
  ('0194a8b2-0005-7123-8123-123456789abc'::uuid, 'DetailViewBuilder', '{"title":"Detail View Builder","body":[{"type":"html","html":"Detail view builder content"}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}', NULL, NULL, 'fa-address-card', 'Detail View Builder', 'Detail View Builder'),
  ('0194a8b2-0006-7123-8123-123456789abc'::uuid, 'PageCustomizer', '{"title":"Page Customizer","body":[{"type":"html","html":"Page customizer content"}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}', NULL, NULL, 'fa-object-group', 'Page Customizer', 'Page Customizer'),
  ('0194a8b2-0007-7123-8123-123456789abc'::uuid, 'PageConfigBuilder', '{"title":"Page Config Builder","body":[{"type":"html","html":"Page config builder content"}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}', NULL, NULL, 'fa-layer-group', 'Page Config Builder', 'Page Config Builder'),
  ('0194a8b2-0008-7123-8123-123456789abc'::uuid, 'ModuleBuilder', '{"title":"Module Builder","body":[{"type":"html","html":"Module builder content"}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}', NULL, NULL, 'fa-puzzle-piece', 'Module Builder', 'Module Builder'),
  ('0194a8b2-0009-7123-8123-123456789abc'::uuid, 'TableBuilder', '{"title":"Table Builder","body":[{"type":"html","html":"Table builder content"}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}', NULL, NULL, 'fa-table', 'Table Builder', 'Table Builder'),
  ('0194a8b2-0010-7123-8123-123456789abc'::uuid, 'TableManager', '{"title":"Table Manager","body":[{"type":"html","html":"Table manager content"}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}', NULL, NULL, 'fa-table-list', 'Table Manager', 'Table Manager'),
  ('0194a8b2-0011-7123-8123-123456789abc'::uuid, 'ModuleManager', '{"title":"Module Manager","body":[{"type":"html","html":"Module manager content"}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}', NULL, NULL, 'fa-cubes', 'Module Manager', 'Module Manager'),
  ('0194a8b2-0012-7123-8123-123456789abc'::uuid, 'PermissionsManager', '{"title":"Permissions Manager","body":[{"type":"html","html":"Permissions manager content"}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}', NULL, NULL, 'fa-user-shield', 'Permissions Manager', 'Permissions Manager'),
  ('0194a8b2-0013-7123-8123-123456789abc'::uuid, 'CreateUser', '{"title":"Create User","body":[{"type":"html","html":"Create user content"}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}', NULL, NULL, 'fa-user-plus', 'Create User', 'Create User'),
  ('0194a8b2-0014-7123-8123-123456789abc'::uuid, 'Payments', '{"title":"Payments","body":[{"type":"html","html":"Payments content"}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}', NULL, NULL, 'fa-money-check-dollar', 'Payments', 'Payments'),
  ('0194a8b2-0015-7123-8123-123456789abc'::uuid, 'POS', '{"title":"POS","fullscreen":true,"body":[{"type":"html","html":"POS content"}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}],"legacy":true}', NULL, NULL, 'fa-cash-register', 'POS', 'POS'),
  ('0194a8b2-0016-7123-8123-123456789abc'::uuid, 'InventoryManagement', '{
        "title": "Inventory Management",
        "header": [],
        "body": [
            {
                "type": "tabs",
                "tabs": [
                    {
                        "label": "Receive",
                        "icon": "fa-arrow-down",
                        "body": [
                            {
                                "type": "button",
                                "label": "Receive Inventory",
                                "icon": "fa-plus",
                                "class": "btn btn-primary mb-4",
                                "formName": "inventory_receive_form"
                            },
                            {
                                "type": "table",
                                "options": {
                                    "tableName": "inventory_receive",
                                    "showGlobalSearch": true,
                                    "addButton": false,
                                    "columnsToShow": ["delivery_note_number", "vendor", "branch", "lpo_number", "invoice_number", "truck", "date"],
                                    "rowActions": [
                                        {
                                            "label": "View",
                                            "icon": "fa-eye",
                                            "onClick": "viewInventoryReceive"
                                        },
                                        {
                                            "label": "Edit",
                                            "icon": "fa-edit",
                                            "onClick": "editInventoryReceive"
                                        }
                                    ]
                                }
                            }
                        ]
                    },
                    {
                        "label": "Stocks",
                        "icon": "fa-warehouse",
                        "body": [
                            {
                                "type": "button",
                                "label": "Adjust Stock",
                                "icon": "fa-edit",
                                "class": "btn btn-warning",
                                "formName": "inventory_adjustment_form"
                            },
                            {
                                "type": "button",
                                "label": "Transfer",
                                "icon": "fa-exchange-alt",
                                "class": "btn btn-secondary",
                                "formName": "inventory_transfer_form"
                            },
                            {
                                "type": "button",
                                "label": "Break Bulk",
                                "icon": "fa-cut",
                                "class": "btn btn-secondary",
                                "action": "inventory:break"
                            },
                            {
                                "type": "button",
                                "label": "Export",
                                "icon": "fa-download",
                                "class": "btn btn-secondary",
                                "onClick": "exportInventory"
                            },
                            {
                                "type": "table",
                                "options": {
                                    "tableName": "inventory",
                                    "showGlobalSearch": true,
                                    "addButton": false,
                                    "editFormName": "inventory_adjustment_form",
                                    "columnsToShow": ["product_name", "batch_number", "warehouse", "current_qty", "unit_type", "expiry_date"],
                                    "rowActions": [
                                        {
                                            "label": "Adjust",
                                            "icon": "fa-edit",
                                            "action": "edit"
                                        },
                                        {
                                            "label": "History",
                                            "icon": "fa-history",
                                            "onClick": "viewInventoryHistory"
                                        }
                                    ]
                                }
                            }
                        ]
                    },
                    {
                        "label": "Transfers",
                        "icon": "fa-exchange-alt",
                        "body": [
                            {
                                "type": "button",
                                "label": "New Transfer",
                                "icon": "fa-plus",
                                "class": "btn btn-primary mb-4",
                                "formName": "inventory_transfer_form"
                            },
                            {
                                "type": "table",
                                "options": {
                                    "tableName": "inventory_transfers",
                                    "showGlobalSearch": true,
                                    "addButton": false,
                                    "columnsToShow": ["reference_number", "transfer_date", "status"],
                                    "rowActions": [
                                        {
                                            "label": "Complete Transfer",
                                            "icon": "fa-check",
                                            "confirm": "Complete this transfer? This will automatically move stock between branches.",
                                            "update": {
                                                "status": "completed"
                                            },
                                            "condition": "row.status === ''pending''"
                                        }
                                    ]
                                }
                            }
                        ]
                    },
                    {
                        "label": "Warehouses",
                        "icon": "fa-building",
                        "body": [
                            {
                                "type": "button",
                                "label": "Add Warehouse",
                                "icon": "fa-plus",
                                "class": "btn btn-primary mb-4",
                                "formName": "warehouse_form"
                            },
                            {
                                "type": "table",
                                "options": {
                                    "tableName": "branches",
                                    "showGlobalSearch": true,
                                    "addButton": false,
                                    "editFormName": "warehouse_form",
                                    "columnsToShow": ["name", "code", "type", "address"],
                                    "rowActions": [
                                        {
                                            "label": "View Stock",
                                            "icon": "fa-boxes",
                                            "onClick": "viewWarehouseStock"
                                        },
                                        {
                                            "label": "Deactivate",
                                            "icon": "fa-ban",
                                            "onClick": "deactivateWarehouse"
                                        }
                                    ]
                                }
                            }
                        ]
                    },
                    {
                        "label": "Stock Movement",
                        "icon": "fa-truck-moving",
                        "body": [
                            {
                                "type": "html",
                                "html": "<div class=\"alert alert-info mb-4\"><span class=\"font-semibold\">Stock Movement Report:</span> View detailed product movement history including sales, receipts, transfers, and adjustments. Use filters below to narrow by date, product, category, or warehouse.</div>"
                            },
                            {
                                "type": "filter-group",
                                "filters": [
                                    {
                                        "type": "filter-date-range",
                                        "options": {
                                            "data_column": "movement_date",
                                            "label": "Date Range",
                                            "default_from": "-30 days",
                                            "default_to": "today"
                                        }
                                    },
                                    {
                                        "type": "filter-select",
                                        "options": {
                                            "source_table": "branches",
                                            "source_column": "branch_id",
                                            "display_column": "name",
                                            "data_column": "branch_id",
                                            "placeholder": "All Warehouses",
                                            "default_label": "All Warehouses"
                                        }
                                    },
                                    {
                                        "type": "filter-select",
                                        "options": {
                                            "source_table": "product_categories",
                                            "source_column": "category_id",
                                            "display_column": "name",
                                            "data_column": "category_id",
                                            "placeholder": "All Categories",
                                            "default_label": "All Categories"
                                        }
                                    },
                                    {
                                        "type": "filter-select",
                                        "options": {
                                            "source_table": "products",
                                            "source_column": "product_id",
                                            "display_column": "name",
                                            "data_column": "product_id",
                                            "placeholder": "Search products...",
                                            "search_fields": ["name", "barcode", "product_number"],
                                            "max_results": 50,
                                            "debounce_ms": 300,
                                            "multiple": true
                                        }
                                    }
                                ]
                            },
                            {
                                "type": "table",
                                "options": {
                                    "tableName": "stock_movement_daily",
                                    "customEndpoint": "../api/stock-movement/report",
                                    "showGlobalSearch": true,
                                    "addButton": false,
                                    "columnsToShow": [
                                        "movement_date",
                                        "product_name",
                                        "product_category",
                                        "branch_name",
                                        "opening_balance",
                                        "received_qty",
                                        "sold_qty",
                                        "transfer_in_qty",
                                        "transfer_out_qty",
                                        "adjustment_in_qty",
                                        "adjustment_out_qty",
                                        "wastage_qty",
                                        "closing_balance"
                                    ],
                                    "columnLabels": {
                                        "movement_date": "Date",
                                        "product_name": "Product",
                                        "product_category": "Category",
                                        "branch_name": "Warehouse",
                                        "opening_balance": "Opening",
                                        "received_qty": "Received",
                                        "sold_qty": "Sold",
                                        "transfer_in_qty": "Transfer In",
                                        "transfer_out_qty": "Transfer Out",
                                        "adjustment_in_qty": "Adj. In",
                                        "adjustment_out_qty": "Adj. Out",
                                        "wastage_qty": "Wastage",
                                        "closing_balance": "Closing"
                                    },
                                    "columnFormats": {
                                        "movement_date": "date",
                                        "opening_balance": "number",
                                        "received_qty": "number",
                                        "sold_qty": "number",
                                        "transfer_in_qty": "number",
                                        "transfer_out_qty": "number",
                                        "adjustment_in_qty": "number",
                                        "adjustment_out_qty": "number",
                                        "wastage_qty": "number",
                                        "closing_balance": "number"
                                    },
                                    "filterField": ["movement_date", "branch_id", "category_id", "product_id"],
                                    "rowActions": [
                                        {
                                            "label": "View Details",
                                            "icon": "fa-eye",
                                            "onClick": "viewMovementDetails"
                                        }
                                    ],
                                    "sortable": true,
                                    "pagination": true,
                                    "pageSize": 50
                                }
                            }
                        ]
                    },
                    {
                        "label": "ReOrders",
                        "icon": "fa-redo",
                        "body": [
                            {
                                "type": "alert",
                                "class": "alert-warning mb-4",
                                "content": "<i class=\"fa fa-exclamation-triangle\"></i> <strong>Products Below Minimum Stock Levels</strong><br>These products need to be reordered based on your configured thresholds."
                            },
                            {
                                "type": "table",
                                "options": {
                                    "tableName": "auto_orders_reorder",
                                    "showGlobalSearch": true,
                                    "addButton": false,
                                    "columnsToShow": ["product_name", "current_qty", "minimum_stock_qty", "order_qty"],
                                    "rowActions": [
                                        {
                                            "label": "Adjust Threshold",
                                            "icon": "fa-edit",
                                            "action": "edit"
                                        }
                                    ]
                                }
                            }
                        ]
                    },
                    {
                        "label": "Shrinkage/Wastage",
                        "icon": "fa-exclamation-triangle",
                        "body": [
                            {
                                "type": "table",
                                "options": {
                                    "tableName": "inventory_txn",
                                    "showGlobalSearch": true,
                                    "addButton": false,
                                    "columnsToShow": ["updatedAt", "product_name", "change", "unit_type", "reason", "batch_number", "notes", "branch_name"],
                                    "searchInputTypes": {
                                        "reason": {
                                            "type": "select",
                                            "options": [
                                                {"value": "", "label": "All Shrinkage Types"},
                                                {"value": "damage", "label": "Damaged Goods"},
                                                {"value": "theft", "label": "Theft/Loss"},
                                                {"value": "expired", "label": "Expired Product"}
                                            ]
                                        },
                                        "updatedAt": {
                                            "type": "dateRange"
                                        }
                                    },
                                    "rowActions": [
                                        {
                                            "label": "View Details",
                                            "icon": "fa-eye",
                                            "onClick": "viewTransactionDetails"
                                        }
                                    ]
                                }
                            }
                        ]
                    }
                ]
            }
        ],
        "footer": [
            {
                "type": "button",
                "label": "Close",
                "onClick": "closeModal"
            }
        ]
    }'::jsonb, NULL, NULL, 'fa-boxes', 'Inventory Management', 'Complete inventory management with receiving, transfers, break bulk operations, and warehouse management');


--DEPRECIATED -- 

-- Link OHS modals to their forms and disable search/add buttons
UPDATE modules SET config='{"title":"OHS Incidents","header":[{"type":"button","label":"Add Incident","wizardId":1}],"body":[{"type":"table","options":{"tableName":"ohs_incidents","showGlobalSearch":false,"addButton":false,"editFormLookup":{"table":"ohs_incident_types","field":"classification","valueColumn":"name","formColumn":"form_id"}}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}' WHERE name='OHS Incidents';

UPDATE modules SET config='{"title":"OHS Inspections","header":[{"type":"button","label":"Add Inspection","wizardId":3}],"body":[{"type":"table","options":{"tableName":"ohs_inspections","showGlobalSearch":false,"addButton":false,"editFormLookup":{"table":"ohs_inspection_types","field":"inspection_type_id","valueColumn":"id","formColumn":"form_id"}}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}' WHERE name='OHS Inspections';

UPDATE modules SET config='{"title":"Hazard Management","header":[{"type":"button","label":"Add Hazard","formName":"OHS Hazard"}],"body":[{"type":"table","options":{"tableName":"ohs_hazards","showGlobalSearch":false,"addButton":false,"editFormId":7}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}' WHERE name='Hazard Management';

UPDATE modules SET config='{"title":"Hazard Types","header":[{"type":"button","label":"Add Hazard Type","formName":"Hazard Type"}],"body":[{"type":"table","options":{"tableName":"ohs_hazard_types","showGlobalSearch":false,"addButton":false,"editFormId":56}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}' WHERE name='Hazard Types';

UPDATE modules SET config='{"title":"OHS JSA","header":[{"type":"button","label":"Create JSA","formName":"Job Safety Analysis"}],"body":[{"type":"table","options":{"tableName":"ohs_jsas","showGlobalSearch":false,"addButton":false,"editFormId":6}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}' WHERE name='OHS JSA';

UPDATE modules SET config='{"title":"OHS Assignment Rules","header":[{"type":"button","label":"Add Rule","formId":58}],"body":[{"type":"table","options":{"tableName":"ohs_assignment_rules","addButton":false,"editFormId":58}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}' WHERE name='OHS Assignment Rules';

UPDATE modules SET config='{"title":"Inspection Assignment Rules","header":[{"type":"button","label":"Add Rule","formId":84}],"body":[{"type":"table","options":{"tableName":"inspection_assignment_rules","addButton":false,"editFormId":84}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}' WHERE name='Inspection Assignment Rules';
UPDATE modules SET config='{"title":"WorkCOM Inspection Assignment Rules","header":[{"type":"button","label":"Add Rule","formId":101}],"body":[{"type":"table","options":{"tableName":"inspection_assignment_rules","addButton":false,"editFormId":101,"columnsToShow":["location","type","severity","inspector_id","district","assign","email","phone","send_email","send_sms","send_push"]}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}' WHERE name='WorkCOM Inspection Assignment Rules';

UPDATE modules SET config='{"title":"WorkCOM OHS Inspections","header":[{"type":"button","label":"New Inspection","wizardId":5}],"body":[{"type":"table","options":{"tableName":"workplace_inspections","showGlobalSearch":false,"addButton":false,"rowActions":[{"label":"Assign Inspector","formName":"WorkCOM Inspection Assignment"}]}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}' WHERE name='WorkCOM OHS Inspections';

-- ============================================================================
-- -- PHASE 7: FINANCE INTEGRATION - MODULE DEFINITIONS
-- -- ============================================================================
-- -- Description: UI modules for payment reminders, credit management,
-- --              and financial reports (9 total modules)
-- -- Created: October 18, 2025
-- -- ============================================================================
-- 
-- -- ============================================================================
-- -- PHASE 7 TASK 2: PAYMENT REMINDERS DECLARATIVE MODULES
-- -- ============================================================================
-- -- Description: Module definitions for Payment Reminders management
-- -- Dependencies: migrations/phase7_payment_reminders_schema.sql
-- --               migrations/phase7_email_templates_schema.sql
-- -- Author: AI Assistant
-- -- Date: October 18, 2025
-- -- ============================================================================
-- 
-- -- ============================================================================
-- -- MODULE 1: PAYMENT REMINDERS LIST
-- -- ============================================================================
-- -- Purpose: List view for payment reminders with filters, stats, and actions
-- -- Type: list
-- -- ============================================================================
-- 
-- INSERT INTO modules (
--     module_id,
--     module_code,
--     module_name,
--     module_type,
--     category,
--     description,
--     icon,
--     config,
--     is_active,
--     priority,
--     created_at,
--     updated_at
-- ) VALUES (
--     uuid_generate_v7(),
--     'payment_reminders_list',
--     'Payment Reminders',
--     'list',
--     'finance',
--     'View and manage payment reminders with delivery tracking and statistics',
--     'fa-bell',
--     '{
--         "dataSource": {
--             "endpoint": "/api/payment-reminders/list",
--             "method": "GET",
--             "params": {
--                 "limit": 50,
--                 "offset": 0
--             }
--         },
--         "refreshInterval": 30000,
--         "columns": [
--             {
--                 "key": "reminder_id",
--                 "label": "Reminder ID",
--                 "type": "text",
--                 "width": "120px",
--                 "sortable": true,
--                 "formatter": "truncate",
--                 "formatterOptions": {
--                     "length": 8
--                 }
--             },
--             {
--                 "key": "invoice_number",
--                 "label": "Invoice",
--                 "type": "link",
--                 "width": "120px",
--                 "sortable": true,
--                 "linkTemplate": "/invoices/{{invoice_id}}"
--             },
--             {
--                 "key": "customer_name",
--                 "label": "Customer",
--                 "type": "text",
--                 "width": "200px",
--                 "sortable": true
--             },
--             {
--                 "key": "amount_due",
--                 "label": "Amount Due",
--                 "type": "currency",
--                 "width": "120px",
--                 "sortable": true,
--                 "align": "right"
--             },
--             {
--                 "key": "reminder_stage",
--                 "label": "Stage",
--                 "type": "badge",
--                 "width": "140px",
--                 "sortable": true,
--                 "badgeConfig": {
--                     "7_days_before": {"color": "success", "label": "7 Days Before"},
--                     "due_date": {"color": "warning", "label": "Due Date"},
--                     "3_days_after": {"color": "error", "label": "3 Days Overdue"},
--                     "7_days_after": {"color": "error", "label": "7 Days Overdue"},
--                     "30_days_after": {"color": "error", "label": "30+ Days Overdue"}
--                 }
--             },
--             {
--                 "key": "delivery_method",
--                 "label": "Method",
--                 "type": "badge",
--                 "width": "100px",
--                 "sortable": true,
--                 "badgeConfig": {
--                     "email": {"color": "info", "icon": "fa-envelope"},
--                     "sms": {"color": "primary", "icon": "fa-mobile"},
--                     "portal": {"color": "secondary", "icon": "fa-desktop"}
--                 }
--             },
--             {
--                 "key": "delivery_status",
--                 "label": "Status",
--                 "type": "badge",
--                 "width": "120px",
--                 "sortable": true,
--                 "badgeConfig": {
--                     "pending": {"color": "warning", "label": "Pending"},
--                     "sent": {"color": "success", "label": "Sent"},
--                     "delivered": {"color": "success", "label": "Delivered"},
--                     "opened": {"color": "info", "label": "Opened"},
--                     "clicked": {"color": "primary", "label": "Clicked"},
--                     "failed": {"color": "error", "label": "Failed"},
--                     "bounced": {"color": "error", "label": "Bounced"}
--                 }
--             },
--             {
--                 "key": "sent_at",
--                 "label": "Sent At",
--                 "type": "datetime",
--                 "width": "160px",
--                 "sortable": true
--             },
--             {
--                 "key": "opened_at",
--                 "label": "Opened",
--                 "type": "datetime",
--                 "width": "160px",
--                 "sortable": true
--             },
--             {
--                 "key": "attempts",
--                 "label": "Attempts",
--                 "type": "number",
--                 "width": "80px",
--                 "sortable": true,
--                 "align": "center"
--             }
--         ],
--         "filters": [
--             {
--                 "key": "reminder_stage",
--                 "label": "Reminder Stage",
--                 "type": "select",
--                 "options": [
--                     {"value": "7_days_before", "label": "7 Days Before"},
--                     {"value": "due_date", "label": "Due Date"},
--                     {"value": "3_days_after", "label": "3 Days Overdue"},
--                     {"value": "7_days_after", "label": "7 Days Overdue"},
--                     {"value": "30_days_after", "label": "30+ Days Overdue"}
--                 ],
--                 "multiple": true
--             },
--             {
--                 "key": "delivery_status",
--                 "label": "Delivery Status",
--                 "type": "select",
--                 "options": [
--                     {"value": "pending", "label": "Pending"},
--                     {"value": "sent", "label": "Sent"},
--                     {"value": "delivered", "label": "Delivered"},
--                     {"value": "opened", "label": "Opened"},
--                     {"value": "clicked", "label": "Clicked"},
--                     {"value": "failed", "label": "Failed"},
--                     {"value": "bounced", "label": "Bounced"}
--                 ],
--                 "multiple": true
--             },
--             {
--                 "key": "delivery_method",
--                 "label": "Delivery Method",
--                 "type": "select",
--                 "options": [
--                     {"value": "email", "label": "Email"},
--                     {"value": "sms", "label": "SMS"},
--                     {"value": "portal", "label": "Portal Notification"}
--                 ],
--                 "multiple": true
--             },
--             {
--                 "key": "customer_id",
--                 "label": "Customer",
--                 "type": "select",
--                 "dataSource": "/api/customers/list-simple",
--                 "valueKey": "customer_id",
--                 "labelKey": "customer_name"
--             },
--             {
--                 "key": "date_from",
--                 "label": "From Date",
--                 "type": "date"
--             },
--             {
--                 "key": "date_to",
--                 "label": "To Date",
--                 "type": "date"
--             }
--         ],
--         "rowActions": [
--             {
--                 "label": "View Details",
--                 "icon": "fa-eye",
--                 "action": "payment-reminders:view-details",
--                 "color": "info"
--             },
--             {
--                 "label": "View Invoice",
--                 "icon": "fa-file-invoice",
--                 "action": "invoices:view",
--                 "color": "primary"
--             },
--             {
--                 "label": "Resend",
--                 "icon": "fa-paper-plane",
--                 "action": "payment-reminders:resend",
--                 "condition": "delivery_status == \"failed\" || delivery_status == \"bounced\"",
--                 "color": "warning",
--                 "confirm": "Resend this payment reminder?"
--             },
--             {
--                 "label": "Mark as Sent",
--                 "icon": "fa-check",
--                 "action": "payment-reminders:mark-sent",
--                 "condition": "delivery_status == \"pending\"",
--                 "color": "success",
--                 "confirm": "Mark this reminder as sent?"
--             }
--         ],
--         "bulkActions": [
--             {
--                 "label": "Resend Selected",
--                 "icon": "fa-paper-plane",
--                 "action": "payment-reminders:resend-bulk",
--                 "color": "warning",
--                 "confirm": "Resend {{count}} payment reminders?"
--             },
--             {
--                 "label": "Export CSV",
--                 "icon": "fa-download",
--                 "action": "payment-reminders:export-csv",
--                 "color": "secondary"
--             },
--             {
--                 "label": "Export PDF",
--                 "icon": "fa-file-pdf",
--                 "action": "payment-reminders:export-pdf",
--                 "color": "error"
--             }
--         ],
--         "summaryWidgets": [
--             {
--                 "type": "stat",
--                 "label": "Total Reminders",
--                 "key": "total_reminders",
--                 "icon": "fa-bell",
--                 "color": "primary",
--                 "format": "number"
--             },
--             {
--                 "type": "stat",
--                 "label": "Sent Today",
--                 "key": "sent_today",
--                 "icon": "fa-paper-plane",
--                 "color": "info",
--                 "format": "number"
--             },
--             {
--                 "type": "stat",
--                 "label": "Opened",
--                 "key": "opened_count",
--                 "icon": "fa-envelope-open",
--                 "color": "success",
--                 "format": "number"
--             },
--             {
--                 "type": "stat",
--                 "label": "Open Rate",
--                 "key": "open_rate",
--                 "icon": "fa-percentage",
--                 "color": "success",
--                 "format": "percentage"
--             },
--             {
--                 "type": "stat",
--                 "label": "Failed",
--                 "key": "failed_count",
--                 "icon": "fa-exclamation-triangle",
--                 "color": "error",
--                 "format": "number"
--             },
--             {
--                 "type": "stat",
--                 "label": "Pending",
--                 "key": "pending_count",
--                 "icon": "fa-clock",
--                 "color": "warning",
--                 "format": "number"
--             }
--         ],
--         "charts": [
--             {
--                 "type": "pie",
--                 "title": "Reminders by Stage",
--                 "dataKey": "reminders_by_stage",
--                 "labelKey": "stage_label",
--                 "valueKey": "count",
--                 "height": 300
--             },
--             {
--                 "type": "bar",
--                 "title": "Delivery Status",
--                 "dataKey": "reminders_by_status",
--                 "labelKey": "status_label",
--                 "valueKey": "count",
--                 "height": 300
--             },
--             {
--                 "type": "line",
--                 "title": "Reminders Sent (Last 7 Days)",
--                 "dataKey": "reminders_trend",
--                 "xKey": "date",
--                 "yKey": "count",
--                 "height": 300
--             }
--         ],
--         "defaultSort": {
--             "column": "sent_at",
--             "direction": "desc"
--         },
--         "pagination": {
--             "enabled": true,
--             "pageSize": 50,
--             "pageSizeOptions": [25, 50, 100, 200]
--         },
--         "search": {
--             "enabled": true,
--             "placeholder": "Search by invoice, customer, or reminder ID...",
--             "fields": ["invoice_number", "customer_name", "reminder_id"]
--         }
--     }'::jsonb,
--     true,
--     200,
--     CURRENT_TIMESTAMP,
--     CURRENT_TIMESTAMP
-- ) ON CONFLICT (module_code) DO UPDATE SET
--     module_name = EXCLUDED.module_name,
--     config = EXCLUDED.config,
--     updated_at = CURRENT_TIMESTAMP;
-- 
-- -- ============================================================================
-- -- MODULE 2: PAYMENT REMINDERS CONFIGURATION
-- -- ============================================================================
-- -- Purpose: Configure payment reminder settings per organization
-- -- Type: form
-- -- ============================================================================
-- 
-- INSERT INTO modules (
--     module_id,
--     module_code,
--     module_name,
--     module_type,
--     category,
--     description,
--     icon,
--     config,
--     is_active,
--     priority,
--     created_at,
--     updated_at
-- ) VALUES (
--     uuid_generate_v7(),
--     'payment_reminders_config',
--     'Payment Reminder Settings',
--     'form',
--     'finance',
--     'Configure payment reminder schedules, templates, and delivery settings',
--     'fa-cog',
--     '{
--         "dataSource": {
--             "endpoint": "/api/payment-reminders/config",
--             "method": "GET"
--         },
--         "saveEndpoint": "/api/payment-reminders/config",
--         "saveMethod": "POST",
--         "sections": [
--             {
--                 "title": "General Settings",
--                 "icon": "fa-sliders-h",
--                 "fields": [
--                     {
--                         "key": "enabled",
--                         "label": "Enable Payment Reminders",
--                         "type": "toggle",
--                         "default": true,
--                         "help": "Master switch for payment reminder system"
--                     },
--                     {
--                         "key": "from_name",
--                         "label": "From Name",
--                         "type": "text",
--                         "required": true,
--                         "placeholder": "Your Company Name",
--                         "help": "Name that appears in reminder emails"
--                     },
--                     {
--                         "key": "from_email",
--                         "label": "From Email",
--                         "type": "email",
--                         "required": true,
--                         "placeholder": "reminders@yourcompany.com",
--                         "help": "Email address for sending reminders"
--                     },
--                     {
--                         "key": "reply_to_email",
--                         "label": "Reply-To Email",
--                         "type": "email",
--                         "placeholder": "support@yourcompany.com",
--                         "help": "Email address for customer replies"
--                     },
--                     {
--                         "key": "cc_emails",
--                         "label": "CC Recipients",
--                         "type": "tags",
--                         "placeholder": "accounting@yourcompany.com",
--                         "help": "Additional recipients (comma-separated)"
--                     },
--                     {
--                         "key": "bcc_emails",
--                         "label": "BCC Recipients",
--                         "type": "tags",
--                         "placeholder": "admin@yourcompany.com",
--                         "help": "Hidden copy recipients (comma-separated)"
--                     }
--                 ]
--             },
--             {
--                 "title": "Reminder Schedule",
--                 "icon": "fa-calendar-alt",
--                 "fields": [
--                     {
--                         "key": "send_7_days_before",
--                         "label": "Send 7 Days Before Due Date",
--                         "type": "toggle",
--                         "default": true,
--                         "help": "Friendly advance notice"
--                     },
--                     {
--                         "key": "send_on_due_date",
--                         "label": "Send On Due Date",
--                         "type": "toggle",
--                         "default": true,
--                         "help": "Payment due today reminder"
--                     },
--                     {
--                         "key": "send_3_days_after",
--                         "label": "Send 3 Days After Due Date",
--                         "type": "toggle",
--                         "default": true,
--                         "help": "First overdue notice"
--                     },
--                     {
--                         "key": "send_7_days_after",
--                         "label": "Send 7 Days After Due Date",
--                         "type": "toggle",
--                         "default": true,
--                         "help": "Second overdue notice with late fees"
--                     },
--                     {
--                         "key": "send_30_days_after",
--                         "label": "Send 30 Days After Due Date",
--                         "type": "toggle",
--                         "default": true,
--                         "help": "Final notice before collections"
--                     },
--                     {
--                         "key": "reminder_time",
--                         "label": "Send Time (24-hour)",
--                         "type": "time",
--                         "default": "09:00",
--                         "help": "Time of day to send reminders"
--                     }
--                 ]
--             },
--             {
--                 "title": "Delivery Methods",
--                 "icon": "fa-paper-plane",
--                 "fields": [
--                     {
--                         "key": "email_enabled",
--                         "label": "Email Delivery",
--                         "type": "toggle",
--                         "default": true,
--                         "help": "Send reminders via email"
--                     },
--                     {
--                         "key": "sms_enabled",
--                         "label": "SMS Delivery",
--                         "type": "toggle",
--                         "default": false,
--                         "help": "Send reminders via SMS (requires Twilio)"
--                     },
--                     {
--                         "key": "portal_notification_enabled",
--                         "label": "Portal Notifications",
--                         "type": "toggle",
--                         "default": true,
--                         "help": "Show reminders in customer portal"
--                     }
--                 ]
--             },
--             {
--                 "title": "Twilio Configuration (SMS)",
--                 "icon": "fa-mobile",
--                 "condition": "sms_enabled == true",
--                 "fields": [
--                     {
--                         "key": "twilio_account_sid",
--                         "label": "Twilio Account SID",
--                         "type": "text",
--                         "placeholder": "ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
--                         "help": "Your Twilio Account SID"
--                     },
--                     {
--                         "key": "twilio_auth_token",
--                         "label": "Twilio Auth Token",
--                         "type": "password",
--                         "placeholder": "Enter your Twilio auth token",
--                         "help": "Your Twilio authentication token"
--                     },
--                     {
--                         "key": "twilio_phone_number",
--                         "label": "Twilio Phone Number",
--                         "type": "tel",
--                         "placeholder": "+1234567890",
--                         "help": "Your Twilio phone number (E.164 format)"
--                     },
--                     {
--                         "key": "sms_template",
--                         "label": "SMS Template",
--                         "type": "textarea",
--                         "rows": 4,
--                         "default": "Payment reminder: Invoice {{invoice_number}} for ${{amount_due}} is due on {{due_date}}. Pay now: {{payment_link}}",
--                         "help": "SMS message template (max 160 characters). Use {{variables}} for dynamic content."
--                     }
--                 ]
--             },
--             {
--                 "title": "Late Fees & Penalties",
--                 "icon": "fa-dollar-sign",
--                 "fields": [
--                     {
--                         "key": "late_fee_enabled",
--                         "label": "Enable Late Fees",
--                         "type": "toggle",
--                         "default": false,
--                         "help": "Automatically apply late fees to overdue invoices"
--                     },
--                     {
--                         "key": "late_fee_type",
--                         "label": "Late Fee Type",
--                         "type": "select",
--                         "options": [
--                             {"value": "fixed", "label": "Fixed Amount"},
--                             {"value": "percentage", "label": "Percentage"}
--                         ],
--                         "default": "fixed",
--                         "condition": "late_fee_enabled == true"
--                     },
--                     {
--                         "key": "late_fee_amount",
--                         "label": "Late Fee Amount",
--                         "type": "number",
--                         "min": 0,
--                         "step": 0.01,
--                         "default": 25,
--                         "condition": "late_fee_enabled == true && late_fee_type == \"fixed\"",
--                         "help": "Fixed late fee amount"
--                     },
--                     {
--                         "key": "late_fee_percentage",
--                         "label": "Late Fee Percentage",
--                         "type": "number",
--                         "min": 0,
--                         "max": 100,
--                         "step": 0.1,
--                         "default": 5,
--                         "condition": "late_fee_enabled == true && late_fee_type == \"percentage\"",
--                         "help": "Late fee as percentage of invoice amount"
--                     },
--                     {
--                         "key": "late_fee_grace_period",
--                         "label": "Grace Period (days)",
--                         "type": "number",
--                         "min": 0,
--                         "default": 7,
--                         "condition": "late_fee_enabled == true",
--                         "help": "Days after due date before applying late fees"
--                     }
--                 ]
--             },
--             {
--                 "title": "Tracking & Analytics",
--                 "icon": "fa-chart-line",
--                 "fields": [
--                     {
--                         "key": "track_email_opens",
--                         "label": "Track Email Opens",
--                         "type": "toggle",
--                         "default": true,
--                         "help": "Insert tracking pixel to detect email opens"
--                     },
--                     {
--                         "key": "track_link_clicks",
--                         "label": "Track Link Clicks",
--                         "type": "toggle",
--                         "default": true,
--                         "help": "Track when customers click payment links"
--                     },
--                     {
--                         "key": "max_attempts",
--                         "label": "Maximum Retry Attempts",
--                         "type": "number",
--                         "min": 1,
--                         "max": 10,
--                         "default": 3,
--                         "help": "Maximum retry attempts for failed deliveries"
--                     }
--                 ]
--             },
--             {
--                 "title": "Customer Preferences",
--                 "icon": "fa-user-cog",
--                 "fields": [
--                     {
--                         "key": "allow_opt_out",
--                         "label": "Allow Customer Opt-Out",
--                         "type": "toggle",
--                         "default": true,
--                         "help": "Allow customers to opt out of reminders"
--                     },
--                     {
--                         "key": "opt_out_text",
--                         "label": "Opt-Out Link Text",
--                         "type": "text",
--                         "default": "Unsubscribe from payment reminders",
--                         "condition": "allow_opt_out == true",
--                         "help": "Text for opt-out link in emails"
--                     },
--                     {
--                         "key": "respect_customer_timezone",
--                         "label": "Respect Customer Timezone",
--                         "type": "toggle",
--                         "default": false,
--                         "help": "Send reminders based on customer timezone"
--                     }
--                 ]
--             }
--         ],
--         "actions": [
--             {
--                 "label": "Save Configuration",
--                 "action": "save",
--                 "color": "primary",
--                 "icon": "fa-save"
--             },
--             {
--                 "label": "Test Email Delivery",
--                 "action": "payment-reminders:test-email",
--                 "color": "info",
--                 "icon": "fa-envelope",
--                 "confirm": "Send a test payment reminder email to {{from_email}}?"
--             },
--             {
--                 "label": "Test SMS Delivery",
--                 "action": "payment-reminders:test-sms",
--                 "color": "warning",
--                 "icon": "fa-mobile",
--                 "condition": "sms_enabled == true",
--                 "confirm": "Send a test SMS to {{twilio_phone_number}}?"
--             },
--             {
--                 "label": "View Email Templates",
--                 "action": "navigation:goto",
--                 "params": {"path": "/email-templates"},
--                 "color": "secondary",
--                 "icon": "fa-file-alt"
--             },
--             {
--                 "label": "Reset to Defaults",
--                 "action": "payment-reminders:reset-config",
--                 "color": "error",
--                 "icon": "fa-undo",
--                 "confirm": "Reset all settings to default values? This cannot be undone."
--             }
--         ],
--         "validation": {
--             "rules": [
--                 {
--                     "field": "from_email",
--                     "rule": "email",
--                     "message": "Please enter a valid email address"
--                 },
--                 {
--                     "field": "reply_to_email",
--                     "rule": "email",
--                     "message": "Please enter a valid reply-to email address"
--                 },
--                 {
--                     "field": "twilio_phone_number",
--                     "rule": "phone",
--                     "message": "Please enter a valid phone number in E.164 format",
--                     "condition": "sms_enabled == true"
--                 }
--             ]
--         }
--     }'::jsonb,
--     true,
--     190,
--     CURRENT_TIMESTAMP,
--     CURRENT_TIMESTAMP
-- ) ON CONFLICT (module_code) DO UPDATE SET
--     module_name = EXCLUDED.module_name,
--     config = EXCLUDED.config,
--     updated_at = CURRENT_TIMESTAMP;
-- 
-- -- ============================================================================
-- -- REGISTER ACTIONS IN ActionRegistry
-- -- ============================================================================
-- -- Note: These actions should be registered in FrontEnd/js/ActionRegistry.js
-- -- 
-- -- Actions needed:
-- -- 1. payment-reminders:view-details - Open reminder details modal
-- -- 2. payment-reminders:resend - Resend single reminder
-- -- 3. payment-reminders:resend-bulk - Resend multiple reminders
-- -- 4. payment-reminders:mark-sent - Manually mark as sent
-- -- 5. payment-reminders:export-csv - Export to CSV
-- -- 6. payment-reminders:export-pdf - Export to PDF
-- -- 7. payment-reminders:test-email - Send test email
-- -- 8. payment-reminders:test-sms - Send test SMS
-- -- 9. payment-reminders:reset-config - Reset configuration
-- -- ============================================================================
-- 
-- -- ============================================================================
-- -- VERIFICATION QUERIES
-- -- ============================================================================
-- 
-- -- Verify modules were created
-- SELECT 
--     module_code,
--     module_name,
--     module_type,
--     is_active,
--     priority
-- FROM modules
-- WHERE module_code IN ('payment_reminders_list', 'payment_reminders_config')
-- ORDER BY priority DESC;
-- 
-- -- Count total modules
-- SELECT COUNT(*) as total_modules FROM modules WHERE category = 'finance';
-- 
-- -- ============================================================================
-- -- ROLLBACK (IF NEEDED)
-- -- ============================================================================
-- -- To remove these modules, run:
-- -- DELETE FROM modules WHERE module_code IN ('payment_reminders_list', 'payment_reminders_config');
-- -- ============================================================================
-- 
-- -- Migration complete
-- SELECT 'Payment Reminders modules created successfully!' AS status;
-- -- ============================================================================
-- -- PHASE 7 TASK 3: CREDIT MANAGEMENT DECLARATIVE MODULES
-- -- ============================================================================
-- -- Description: Declarative module definitions for Credit Management UI
-- -- Created: 2025-10-18
-- -- Dependencies: 
-- --   - migrations/phase7_credit_management_schema.sql
-- --   - api/controllers/CreditManagementController.php
-- --   - api/services/CreditManagementService.php
-- -- ============================================================================
-- 
-- -- ============================================================================
-- -- MODULE 1: CREDIT UTILIZATION DASHBOARD
-- -- ============================================================================
-- -- Purpose: Real-time credit health monitoring dashboard
-- -- Type: dashboard
-- -- Features:
-- --   - Summary widgets showing credit health distribution
-- --   - Charts for utilization trends and at-risk customers
-- --   - Unacknowledged alerts panel
-- --   - Auto-refresh every 30 seconds
-- -- ============================================================================
-- 
-- INSERT INTO modules (
--     module_id,
--     module_name,
--     module_type,
--     title,
--     description,
--     icon,
--     config,
--     is_active,
--     created_at
-- ) VALUES (
--     'credit-utilization-dashboard',
--     'CreditUtilizationDashboard',
--     'dashboard',
--     'Credit Utilization Dashboard',
--     'Real-time credit health monitoring and risk management dashboard',
--     'fa-credit-card',
--     '{
--         "dataSource": {
--             "summaries": "/api/credit/utilization-summary/:orgId",
--             "alerts": "/api/credit/alerts/:orgId"
--         },
--         "autoRefresh": 30000,
--         "layout": {
--             "type": "grid",
--             "columns": 12
--         },
--         "widgets": [
--             {
--                 "id": "healthy_count",
--                 "type": "stat",
--                 "title": "Healthy",
--                 "icon": "fa-check-circle",
--                 "color": "success",
--                 "position": { "row": 1, "col": 1, "width": 2 },
--                 "dataSource": "summaries",
--                 "value": "{{data.filter(c => c.health_status === ''healthy'').length}}",
--                 "description": "Customers with good credit standing"
--             },
--             {
--                 "id": "caution_count",
--                 "type": "stat",
--                 "title": "Caution",
--                 "icon": "fa-exclamation-triangle",
--                 "color": "info",
--                 "position": { "row": 1, "col": 3, "width": 2 },
--                 "dataSource": "summaries",
--                 "value": "{{data.filter(c => c.health_status === ''caution'').length}}",
--                 "description": "60-79% credit utilization"
--             },
--             {
--                 "id": "warning_count",
--                 "type": "stat",
--                 "title": "Warning",
--                 "icon": "fa-exclamation",
--                 "color": "warning",
--                 "position": { "row": 1, "col": 5, "width": 2 },
--                 "dataSource": "summaries",
--                 "value": "{{data.filter(c => c.health_status === ''warning'').length}}",
--                 "description": "80-99% credit utilization"
--             },
--             {
--                 "id": "critical_count",
--                 "type": "stat",
--                 "title": "Critical",
--                 "icon": "fa-ban",
--                 "color": "error",
--                 "position": { "row": 1, "col": 7, "width": 2 },
--                 "dataSource": "summaries",
--                 "value": "{{data.filter(c => c.health_status === ''critical'').length}}",
--                 "description": "100%+ credit utilization"
--             },
--             {
--                 "id": "on_hold_count",
--                 "type": "stat",
--                 "title": "On Hold",
--                 "icon": "fa-pause-circle",
--                 "color": "error",
--                 "position": { "row": 1, "col": 9, "width": 2 },
--                 "dataSource": "summaries",
--                 "value": "{{data.filter(c => c.on_hold).length}}",
--                 "description": "Accounts with credit hold"
--             },
--             {
--                 "id": "total_exposure",
--                 "type": "currency",
--                 "title": "Total Credit Exposure",
--                 "icon": "fa-dollar-sign",
--                 "color": "primary",
--                 "position": { "row": 1, "col": 11, "width": 2 },
--                 "dataSource": "summaries",
--                 "value": "{{data.reduce((sum, c) => sum + parseFloat(c.total_utilized || 0), 0)}}",
--                 "description": "Total outstanding across all customers",
--                 "format": "currency"
--             },
--             {
--                 "id": "utilization_chart",
--                 "type": "chart",
--                 "title": "Credit Utilization Distribution",
--                 "chartType": "doughnut",
--                 "position": { "row": 2, "col": 1, "width": 6 },
--                 "dataSource": "summaries",
--                 "config": {
--                     "labels": ["Healthy (0-59%)", "Caution (60-79%)", "Warning (80-99%)", "Critical (100%+)", "On Hold"],
--                     "datasets": [{
--                         "label": "Customer Count",
--                         "data": [
--                             "{{data.filter(c => c.health_status === ''healthy'').length}}",
--                             "{{data.filter(c => c.health_status === ''caution'').length}}",
--                             "{{data.filter(c => c.health_status === ''warning'').length}}",
--                             "{{data.filter(c => c.health_status === ''critical'').length}}",
--                             "{{data.filter(c => c.on_hold).length}}"
--                         ],
--                         "backgroundColor": [
--                             "#10b981",
--                             "#3b82f6",
--                             "#f59e0b",
--                             "#ef4444",
--                             "#6b7280"
--                         ]
--                     }]
--                 }
--             },
--             {
--                 "id": "top_at_risk",
--                 "type": "chart",
--                 "title": "Top 10 At-Risk Customers",
--                 "chartType": "horizontalBar",
--                 "position": { "row": 2, "col": 7, "width": 6 },
--                 "dataSource": "summaries",
--                 "config": {
--                     "labels": "{{data.filter(c => c.utilization_percentage >= 80).sort((a,b) => b.utilization_percentage - a.utilization_percentage).slice(0,10).map(c => c.customer_name)}}",
--                     "datasets": [{
--                         "label": "Utilization %",
--                         "data": "{{data.filter(c => c.utilization_percentage >= 80).sort((a,b) => b.utilization_percentage - a.utilization_percentage).slice(0,10).map(c => c.utilization_percentage)}}",
--                         "backgroundColor": "#ef4444"
--                     }]
--                 }
--             },
--             {
--                 "id": "alerts_panel",
--                 "type": "list",
--                 "title": "Unacknowledged Alerts",
--                 "icon": "fa-bell",
--                 "position": { "row": 3, "col": 1, "width": 12 },
--                 "dataSource": "alerts",
--                 "emptyMessage": "No unacknowledged alerts",
--                 "itemTemplate": "<div class=\"alert alert-{{item.severity}} mb-2\"><div class=\"flex items-center justify-between\"><div><strong>{{item.customer_name}}</strong> - {{item.alert_type}}</div><div><span class=\"badge badge-{{item.severity}}\">{{item.severity}}</span><button class=\"btn btn-sm btn-ghost ml-2\" data-action=\"credit:acknowledge-alert\" data-alert-id=\"{{item.alert_id}}\">Acknowledge</button></div></div><div class=\"text-sm mt-1\">{{item.message}}</div><div class=\"text-xs text-gray-500 mt-1\">{{item.created_at | formatDateTime}}</div></div>",
--                 "maxItems": 10
--             },
--             {
--                 "id": "recent_holds",
--                 "type": "table",
--                 "title": "Recent Credit Holds",
--                 "icon": "fa-pause-circle",
--                 "position": { "row": 4, "col": 1, "width": 12 },
--                 "dataSource": "summaries",
--                 "filter": "{{data.filter(c => c.on_hold)}}",
--                 "columns": [
--                     {
--                         "field": "customer_name",
--                         "label": "Customer",
--                         "sortable": true
--                     },
--                     {
--                         "field": "credit_limit",
--                         "label": "Credit Limit",
--                         "type": "currency",
--                         "sortable": true
--                     },
--                     {
--                         "field": "total_utilized",
--                         "label": "Utilized",
--                         "type": "currency",
--                         "sortable": true
--                     },
--                     {
--                         "field": "utilization_percentage",
--                         "label": "Utilization %",
--                         "type": "percentage",
--                         "sortable": true
--                     },
--                     {
--                         "field": "hold_reason",
--                         "label": "Hold Reason",
--                         "sortable": false
--                     },
--                     {
--                         "field": "hold_applied_at",
--                         "label": "Hold Applied",
--                         "type": "datetime",
--                         "sortable": true
--                     }
--                 ],
--                 "rowActions": [
--                     {
--                         "label": "Remove Hold",
--                         "icon": "fa-play-circle",
--                         "action": "credit:remove-hold",
--                         "style": "success",
--                         "confirm": "Remove credit hold for this customer?"
--                     },
--                     {
--                         "label": "View History",
--                         "icon": "fa-history",
--                         "action": "credit:view-history",
--                         "style": "ghost"
--                     }
--                 ],
--                 "maxRows": 10
--             }
--         ]
--     }'::jsonb,
--     true,
--     NOW()
-- );
-- 
-- -- ============================================================================
-- -- MODULE 2: CREDIT APPROVAL REQUESTS
-- -- ============================================================================
-- -- Purpose: Manage credit approval requests for over-limit transactions
-- -- Type: list
-- -- Features:
-- --   - Pending approval requests with priority sorting
-- --   - Filters by priority, request type, customer
-- --   - Row actions: approve, reject, view details
-- --   - Bulk actions: approve selected, reject selected
-- --   - Auto-refresh every 30 seconds
-- -- ============================================================================
-- 
-- INSERT INTO modules (
--     module_id,
--     module_name,
--     module_type,
--     title,
--     description,
--     icon,
--     config,
--     is_active,
--     created_at
-- ) VALUES (
--     'credit-approval-requests',
--     'CreditApprovalRequests',
--     'list',
--     'Credit Approval Requests',
--     'Manage pending credit approval requests for over-limit transactions',
--     'fa-check-square',
--     '{
--         "dataSource": "/api/credit/approval/pending/:orgId",
--         "autoRefresh": 30000,
--         "pagination": {
--             "enabled": true,
--             "pageSize": 50,
--             "pageSizeOptions": [25, 50, 100]
--         },
--         "columns": [
--             {
--                 "field": "request_id",
--                 "label": "Request ID",
--                 "type": "text",
--                 "width": "120px",
--                 "sortable": true,
--                 "template": "<code class=\"text-xs\">{{value.substring(0,8)}}</code>"
--             },
--             {
--                 "field": "priority",
--                 "label": "Priority",
--                 "type": "badge",
--                 "width": "100px",
--                 "sortable": true,
--                 "template": "<span class=\"badge badge-{{value === ''high'' ? ''error'' : value === ''medium'' ? ''warning'' : ''info''}}\">{{value}}</span>"
--             },
--             {
--                 "field": "customer_name",
--                 "label": "Customer",
--                 "type": "text",
--                 "width": "200px",
--                 "sortable": true
--             },
--             {
--                 "field": "request_type",
--                 "label": "Request Type",
--                 "type": "text",
--                 "width": "150px",
--                 "sortable": true,
--                 "template": "{{value.replace(''_'', '' '').toUpperCase()}}"
--             },
--             {
--                 "field": "current_limit",
--                 "label": "Current Limit",
--                 "type": "currency",
--                 "width": "120px",
--                 "sortable": true
--             },
--             {
--                 "field": "requested_amount",
--                 "label": "Requested",
--                 "type": "currency",
--                 "width": "120px",
--                 "sortable": true
--             },
--             {
--                 "field": "over_limit_amount",
--                 "label": "Over Limit By",
--                 "type": "currency",
--                 "width": "120px",
--                 "sortable": true,
--                 "template": "<span class=\"text-error font-semibold\">{{value | currency}}</span>"
--             },
--             {
--                 "field": "requested_by_name",
--                 "label": "Requested By",
--                 "type": "text",
--                 "width": "150px",
--                 "sortable": true
--             },
--             {
--                 "field": "expires_at",
--                 "label": "Expires",
--                 "type": "datetime",
--                 "width": "150px",
--                 "sortable": true,
--                 "template": "{{value | relativeTime}}"
--             },
--             {
--                 "field": "created_at",
--                 "label": "Created",
--                 "type": "datetime",
--                 "width": "150px",
--                 "sortable": true
--             }
--         ],
--         "filters": [
--             {
--                 "field": "priority",
--                 "label": "Priority",
--                 "type": "select",
--                 "options": [
--                     { "value": "", "label": "All Priorities" },
--                     { "value": "high", "label": "High" },
--                     { "value": "medium", "label": "Medium" },
--                     { "value": "low", "label": "Low" }
--                 ]
--             },
--             {
--                 "field": "request_type",
--                 "label": "Request Type",
--                 "type": "select",
--                 "options": [
--                     { "value": "", "label": "All Types" },
--                     { "value": "over_limit_purchase", "label": "Over Limit Purchase" },
--                     { "value": "limit_increase", "label": "Limit Increase" },
--                     { "value": "temporary_increase", "label": "Temporary Increase" },
--                     { "value": "hold_removal", "label": "Hold Removal" }
--                 ]
--             },
--             {
--                 "field": "customer_id",
--                 "label": "Customer",
--                 "type": "select",
--                 "dataSource": "/api/customers/list/:orgId",
--                 "valueField": "customer_id",
--                 "labelField": "customer_name"
--             },
--             {
--                 "field": "date_from",
--                 "label": "From Date",
--                 "type": "date"
--             },
--             {
--                 "field": "date_to",
--                 "label": "To Date",
--                 "type": "date"
--             }
--         ],
--         "rowActions": [
--             {
--                 "label": "Approve",
--                 "icon": "fa-check",
--                 "action": "credit:approve-request",
--                 "style": "success",
--                 "confirm": "Approve this credit request?",
--                 "condition": "status === ''pending''"
--             },
--             {
--                 "label": "Reject",
--                 "icon": "fa-times",
--                 "action": "credit:reject-request",
--                 "style": "error",
--                 "confirm": "Reject this credit request?",
--                 "condition": "status === ''pending''"
--             },
--             {
--                 "label": "View Details",
--                 "icon": "fa-eye",
--                 "action": "credit:view-request-details",
--                 "style": "ghost"
--             },
--             {
--                 "label": "View Customer Credit",
--                 "icon": "fa-user",
--                 "action": "credit:view-customer-credit",
--                 "style": "ghost"
--             },
--             {
--                 "label": "View History",
--                 "icon": "fa-history",
--                 "action": "credit:view-history",
--                 "style": "ghost"
--             }
--         ],
--         "bulkActions": [
--             {
--                 "label": "Approve Selected",
--                 "icon": "fa-check-double",
--                 "action": "credit:approve-bulk",
--                 "style": "success",
--                 "confirm": "Approve {{count}} selected requests?"
--             },
--             {
--                 "label": "Reject Selected",
--                 "icon": "fa-times-circle",
--                 "action": "credit:reject-bulk",
--                 "style": "error",
--                 "confirm": "Reject {{count}} selected requests?"
--             },
--             {
--                 "label": "Export CSV",
--                 "icon": "fa-file-csv",
--                 "action": "credit:export-csv",
--                 "style": "ghost"
--             }
--         ],
--         "summaryWidgets": [
--             {
--                 "id": "total_pending",
--                 "type": "stat",
--                 "title": "Total Pending",
--                 "icon": "fa-clock",
--                 "color": "info",
--                 "value": "{{data.length}}",
--                 "description": "Approval requests awaiting review"
--             },
--             {
--                 "id": "high_priority",
--                 "type": "stat",
--                 "title": "High Priority",
--                 "icon": "fa-exclamation-triangle",
--                 "color": "error",
--                 "value": "{{data.filter(r => r.priority === ''high'').length}}",
--                 "description": "Urgent requests requiring attention"
--             },
--             {
--                 "id": "total_requested",
--                 "type": "currency",
--                 "title": "Total Requested",
--                 "icon": "fa-dollar-sign",
--                 "color": "warning",
--                 "value": "{{data.reduce((sum, r) => sum + parseFloat(r.requested_amount || 0), 0)}}",
--                 "description": "Total amount in pending requests"
--             },
--             {
--                 "id": "expiring_soon",
--                 "type": "stat",
--                 "title": "Expiring Soon",
--                 "icon": "fa-hourglass-end",
--                 "color": "warning",
--                 "value": "{{data.filter(r => new Date(r.expires_at) - new Date() < 24*60*60*1000).length}}",
--                 "description": "Requests expiring within 24 hours"
--             },
--             {
--                 "id": "avg_over_limit",
--                 "type": "currency",
--                 "title": "Avg Over Limit",
--                 "icon": "fa-chart-line",
--                 "color": "primary",
--                 "value": "{{data.length > 0 ? data.reduce((sum, r) => sum + parseFloat(r.over_limit_amount || 0), 0) / data.length : 0}}",
--                 "description": "Average over-limit amount"
--             }
--         ],
--         "defaultSort": {
--             "field": "priority",
--             "order": "desc",
--             "thenBy": [
--                 { "field": "expires_at", "order": "asc" },
--                 { "field": "created_at", "order": "asc" }
--             ]
--         },
--         "emptyStateMessage": "No pending credit approval requests",
--         "emptyStateIcon": "fa-check-circle",
--         "emptyStateAction": {
--             "label": "View All Requests",
--             "action": "credit:view-all-requests"
--         }
--     }'::jsonb,
--     true,
--     NOW()
-- );
-- 
-- -- ============================================================================
-- -- VERIFICATION QUERIES
-- -- ============================================================================
-- -- Run these queries to verify the modules were created successfully
-- 
-- -- Check module creation
-- SELECT 
--     module_id,
--     module_name,
--     module_type,
--     title,
--     is_active,
--     created_at
-- FROM modules
-- WHERE module_id IN ('credit-utilization-dashboard', 'credit-approval-requests')
-- ORDER BY module_id;
-- 
-- -- Verify JSON structure
-- SELECT 
--     module_id,
--     jsonb_pretty(config) as module_config
-- FROM modules
-- WHERE module_id = 'credit-utilization-dashboard';
-- 
-- SELECT 
--     module_id,
--     jsonb_pretty(config) as module_config
-- FROM modules
-- WHERE module_id = 'credit-approval-requests';
-- 
-- -- ============================================================================
-- -- ROLLBACK (if needed)
-- -- ============================================================================
-- -- To remove these modules, uncomment and run:
-- /*
-- DELETE FROM modules 
-- WHERE module_id IN ('credit-utilization-dashboard', 'credit-approval-requests');
-- */
-- -- ============================================================================
-- -- PHASE 7 TASK 5: FINANCIAL REPORTS DECLARATIVE MODULES
-- -- ============================================================================
-- -- Description: Declarative UI modules for financial reporting (Phase 4 pattern)
-- -- Dependencies: 
-- --   - phase7_financial_reports_schema.sql (database views)
-- --   - api/controllers/ReportsController.php (API endpoints)
-- --   - FrontEnd/js/core/ModuleLoader.js
-- --   - FrontEnd/js/core/ActionRegistry.js
-- -- Created: October 18, 2025
-- -- ============================================================================
-- 
-- -- ============================================================================
-- -- MODULE 1: FINANCIAL REPORTS DASHBOARD
-- -- ============================================================================
-- -- Purpose: Executive dashboard with key financial metrics and trends
-- -- Type: dashboard
-- -- Features:
-- --   - 8 summary widgets (stats, gauges, metrics)
-- --   - 4 charts (revenue trends, top customers, top products, payment methods)
-- --   - 3 quick link lists (recent invoices, outstanding AR, tax summary)
-- --   - Auto-refresh every 60 seconds
-- -- ============================================================================
-- 
-- INSERT INTO modules (
--     module_id,
--     name,
--     title,
--     icon,
--     type,
--     category,
--     description,
--     config,
--     is_active,
--     created_at
-- ) VALUES (
--     'financial-reports-dashboard',
--     'FinancialReportsDashboard',
--     'Financial Reports Dashboard',
--     'fa-chart-line',
--     'dashboard',
--     'Finance',
--     'Executive financial dashboard with revenue, collections, and efficiency metrics',
--     '{
--         "layout": "grid",
--         "columns": 3,
--         "autoRefresh": 60000,
--         "widgets": [
--             {
--                 "id": "total-revenue-widget",
--                 "type": "stat",
--                 "title": "Total Revenue",
--                 "icon": "fa-dollar-sign",
--                 "color": "success",
--                 "dataSource": "/api/reports/dashboard-summary/:orgId",
--                 "dataPath": "data.summary.total_revenue",
--                 "format": "currency",
--                 "trend": {
--                     "dataPath": "data.summary.revenue_growth",
--                     "format": "percentage"
--                 },
--                 "size": "large",
--                 "position": {"row": 1, "col": 1}
--             },
--             {
--                 "id": "outstanding-ar-widget",
--                 "type": "stat",
--                 "title": "Outstanding AR",
--                 "icon": "fa-file-invoice-dollar",
--                 "color": "warning",
--                 "dataSource": "/api/reports/dashboard-summary/:orgId",
--                 "dataPath": "data.summary.total_outstanding",
--                 "format": "currency",
--                 "subtitle": {
--                     "dataPath": "data.summary.overdue_count",
--                     "format": "count",
--                     "suffix": " overdue"
--                 },
--                 "size": "large",
--                 "position": {"row": 1, "col": 2}
--             },
--             {
--                 "id": "collection-rate-widget",
--                 "type": "gauge",
--                 "title": "Collection Rate",
--                 "icon": "fa-percent",
--                 "dataSource": "/api/reports/collection-efficiency/:orgId",
--                 "dataPath": "data.collection_rate",
--                 "format": "percentage",
--                 "ranges": [
--                     {"min": 0, "max": 50, "color": "error", "label": "Poor"},
--                     {"min": 50, "max": 75, "color": "warning", "label": "Fair"},
--                     {"min": 75, "max": 90, "color": "info", "label": "Good"},
--                     {"min": 90, "max": 100, "color": "success", "label": "Excellent"}
--                 ],
--                 "size": "large",
--                 "position": {"row": 1, "col": 3}
--             },
--             {
--                 "id": "dso-widget",
--                 "type": "metric",
--                 "title": "Days Sales Outstanding",
--                 "icon": "fa-calendar-days",
--                 "color": "info",
--                 "dataSource": "/api/reports/collection-efficiency/:orgId",
--                 "dataPath": "data.days_sales_outstanding",
--                 "format": "number",
--                 "suffix": " days",
--                 "size": "medium",
--                 "position": {"row": 2, "col": 1}
--             },
--             {
--                 "id": "avg-collection-time-widget",
--                 "type": "metric",
--                 "title": "Avg Collection Time",
--                 "icon": "fa-clock",
--                 "color": "info",
--                 "dataSource": "/api/reports/collection-efficiency/:orgId",
--                 "dataPath": "data.avg_days_to_collect",
--                 "format": "number",
--                 "suffix": " days",
--                 "size": "medium",
--                 "position": {"row": 2, "col": 2}
--             },
--             {
--                 "id": "tax-collected-widget",
--                 "type": "stat",
--                 "title": "Tax Collected (YTD)",
--                 "icon": "fa-receipt",
--                 "color": "primary",
--                 "dataSource": "/api/reports/dashboard-summary/:orgId",
--                 "dataPath": "data.summary.tax_collected",
--                 "format": "currency",
--                 "size": "medium",
--                 "position": {"row": 2, "col": 3}
--             },
--             {
--                 "id": "monthly-revenue-widget",
--                 "type": "stat",
--                 "title": "Revenue (This Month)",
--                 "icon": "fa-calendar-check",
--                 "color": "accent",
--                 "dataSource": "/api/reports/dashboard-summary/:orgId",
--                 "dataPath": "data.summary.current_month_revenue",
--                 "format": "currency",
--                 "trend": {
--                     "dataPath": "data.summary.month_over_month_growth",
--                     "format": "percentage"
--                 },
--                 "size": "medium",
--                 "position": {"row": 3, "col": 1}
--             },
--             {
--                 "id": "invoice-count-widget",
--                 "type": "stat",
--                 "title": "Invoices (This Month)",
--                 "icon": "fa-file-invoice",
--                 "color": "secondary",
--                 "dataSource": "/api/reports/dashboard-summary/:orgId",
--                 "dataPath": "data.summary.current_month_invoices",
--                 "format": "count",
--                 "size": "medium",
--                 "position": {"row": 3, "col": 2}
--             },
--             {
--                 "id": "revenue-trends-chart",
--                 "type": "chart",
--                 "title": "Revenue Trends (6 Months)",
--                 "chartType": "line",
--                 "dataSource": "/api/reports/revenue-trends/:orgId?months=6",
--                 "xAxis": {
--                     "dataPath": "data.month_name",
--                     "label": "Month"
--                 },
--                 "yAxis": [
--                     {
--                         "dataPath": "data.total_revenue",
--                         "label": "Total Revenue",
--                         "color": "#10b981",
--                         "format": "currency"
--                     },
--                     {
--                         "dataPath": "data.paid_revenue",
--                         "label": "Paid Revenue",
--                         "color": "#3b82f6",
--                         "format": "currency"
--                     }
--                 ],
--                 "size": "xlarge",
--                 "position": {"row": 4, "col": 1, "colspan": 2}
--             },
--             {
--                 "id": "top-customers-chart",
--                 "type": "chart",
--                 "title": "Top 10 Customers",
--                 "chartType": "bar",
--                 "dataSource": "/api/reports/dashboard-summary/:orgId",
--                 "dataPath": "data.top_customers",
--                 "xAxis": {
--                     "dataPath": "customer_name",
--                     "label": "Customer"
--                 },
--                 "yAxis": [
--                     {
--                         "dataPath": "total_revenue",
--                         "label": "Revenue",
--                         "color": "#8b5cf6",
--                         "format": "currency"
--                     }
--                 ],
--                 "size": "xlarge",
--                 "position": {"row": 4, "col": 3, "colspan": 1, "rowspan": 2}
--             },
--             {
--                 "id": "payment-methods-chart",
--                 "type": "chart",
--                 "title": "Collections by Payment Method",
--                 "chartType": "pie",
--                 "dataSource": "/api/reports/payment-collection/:orgId",
--                 "dataPath": "data",
--                 "labelField": "payment_method",
--                 "valueField": "total_collected",
--                 "format": "currency",
--                 "colors": ["#3b82f6", "#10b981", "#f59e0b", "#ef4444", "#8b5cf6"],
--                 "size": "large",
--                 "position": {"row": 5, "col": 1}
--             },
--             {
--                 "id": "top-products-chart",
--                 "type": "chart",
--                 "title": "Top 10 Products",
--                 "chartType": "bar",
--                 "dataSource": "/api/reports/dashboard-summary/:orgId",
--                 "dataPath": "data.top_products",
--                 "xAxis": {
--                     "dataPath": "product_name",
--                     "label": "Product"
--                 },
--                 "yAxis": [
--                     {
--                         "dataPath": "total_revenue",
--                         "label": "Revenue",
--                         "color": "#f59e0b",
--                         "format": "currency"
--                     }
--                 ],
--                 "size": "large",
--                 "position": {"row": 5, "col": 2}
--             },
--             {
--                 "id": "outstanding-invoices-list",
--                 "type": "list",
--                 "title": "Outstanding Invoices (Top 10)",
--                 "icon": "fa-exclamation-triangle",
--                 "dataSource": "/api/reports/outstanding-invoices/:orgId?limit=10",
--                 "dataPath": "data",
--                 "columns": [
--                     {
--                         "field": "customer_name",
--                         "label": "Customer",
--                         "width": "40%"
--                     },
--                     {
--                         "field": "total_outstanding",
--                         "label": "Outstanding",
--                         "format": "currency",
--                         "align": "right",
--                         "width": "30%"
--                     },
--                     {
--                         "field": "overdue_0_30",
--                         "label": "0-30 Days",
--                         "format": "currency",
--                         "align": "right",
--                         "width": "30%"
--                     }
--                 ],
--                 "actions": [
--                     {
--                         "label": "View All",
--                         "action": "reports:view-outstanding-invoices",
--                         "icon": "fa-arrow-right"
--                     }
--                 ],
--                 "size": "large",
--                 "position": {"row": 6, "col": 1}
--             },
--             {
--                 "id": "tax-summary-list",
--                 "type": "list",
--                 "title": "Sales Tax Summary",
--                 "icon": "fa-receipt",
--                 "dataSource": "/api/reports/sales-tax-summary/:orgId",
--                 "dataPath": "data",
--                 "columns": [
--                     {
--                         "field": "tax_rate",
--                         "label": "Tax Rate",
--                         "format": "percentage",
--                         "width": "30%"
--                     },
--                     {
--                         "field": "tax_collected_paid",
--                         "label": "Collected",
--                         "format": "currency",
--                         "align": "right",
--                         "width": "35%"
--                     },
--                     {
--                         "field": "tax_collected_pending",
--                         "label": "Pending",
--                         "format": "currency",
--                         "align": "right",
--                         "width": "35%"
--                     }
--                 ],
--                 "actions": [
--                     {
--                         "label": "View Details",
--                         "action": "reports:view-tax-summary",
--                         "icon": "fa-arrow-right"
--                     }
--                 ],
--                 "size": "large",
--                 "position": {"row": 6, "col": 2}
--             },
--             {
--                 "id": "collection-efficiency-list",
--                 "type": "table",
--                 "title": "Collection Efficiency Metrics",
--                 "icon": "fa-chart-line",
--                 "dataSource": "/api/reports/collection-efficiency/:orgId",
--                 "dataPath": "data",
--                 "columns": [
--                     {
--                         "field": "metric_name",
--                         "label": "Metric",
--                         "width": "50%"
--                     },
--                     {
--                         "field": "metric_value",
--                         "label": "Value",
--                         "align": "right",
--                         "width": "50%"
--                     }
--                 ],
--                 "transform": "efficiency_to_rows",
--                 "size": "large",
--                 "position": {"row": 6, "col": 3}
--             }
--         ],
--         "quickActions": [
--             {
--                 "label": "Export Dashboard",
--                 "action": "reports:export-dashboard-pdf",
--                 "icon": "fa-file-pdf",
--                 "color": "error"
--             },
--             {
--                 "label": "Email Report",
--                 "action": "reports:email-dashboard",
--                 "icon": "fa-envelope",
--                 "color": "primary"
--             },
--             {
--                 "label": "Schedule Report",
--                 "action": "reports:schedule-dashboard",
--                 "icon": "fa-calendar-plus",
--                 "color": "info"
--             }
--         ]
--     }',
--     true,
--     NOW()
-- ) ON CONFLICT (module_id) DO UPDATE SET
--     config = EXCLUDED.config,
--     updated_at = NOW();
-- 
-- -- ============================================================================
-- -- MODULE 2: CUSTOMER REVENUE REPORT
-- -- ============================================================================
-- -- Purpose: Detailed customer revenue analysis with drill-down
-- -- Type: list
-- -- Features:
-- --   - 10 columns showing revenue metrics by customer
-- --   - 6 filters (customer status, date range, min revenue)
-- --   - 5 row actions (view details, drill-down, send statement, export)
-- --   - 3 bulk actions (export selected, email reports, analyze trends)
-- --   - 4 summary widgets (total revenue, customer count, avg revenue, top customer)
-- --   - Auto-refresh every 120 seconds
-- -- ============================================================================
-- 
-- INSERT INTO modules (
--     module_id,
--     name,
--     title,
--     icon,
--     type,
--     category,
--     description,
--     config,
--     is_active,
--     created_at
-- ) VALUES (
--     'customer-revenue-report',
--     'CustomerRevenueReport',
--     'Customer Revenue Report',
--     'fa-users-rectangle',
--     'list',
--     'Finance',
--     'Detailed revenue analysis by customer with trends and status classification',
--     '{
--         "dataSource": "/api/reports/revenue-by-customer/:orgId",
--         "autoRefresh": 120000,
--         "pagination": {
--             "enabled": true,
--             "pageSize": 25,
--             "pageSizes": [10, 25, 50, 100]
--         },
--         "columns": [
--             {
--                 "field": "customer_name",
--                 "label": "Customer",
--                 "sortable": true,
--                 "searchable": true,
--                 "width": "20%",
--                 "render": "link",
--                 "linkAction": "reports:view-customer-details"
--             },
--             {
--                 "field": "customer_status",
--                 "label": "Status",
--                 "sortable": true,
--                 "width": "10%",
--                 "render": "badge",
--                 "badgeColors": {
--                     "active": "success",
--                     "recent": "info",
--                     "inactive": "warning",
--                     "dormant": "error"
--                 }
--             },
--             {
--                 "field": "total_revenue",
--                 "label": "Total Revenue",
--                 "sortable": true,
--                 "width": "12%",
--                 "format": "currency",
--                 "align": "right"
--             },
--             {
--                 "field": "revenue_ytd",
--                 "label": "Revenue YTD",
--                 "sortable": true,
--                 "width": "12%",
--                 "format": "currency",
--                 "align": "right"
--             },
--             {
--                 "field": "revenue_90_days",
--                 "label": "Last 90 Days",
--                 "sortable": true,
--                 "width": "12%",
--                 "format": "currency",
--                 "align": "right"
--             },
--             {
--                 "field": "revenue_30_days",
--                 "label": "Last 30 Days",
--                 "sortable": true,
--                 "width": "12%",
--                 "format": "currency",
--                 "align": "right"
--             },
--             {
--                 "field": "invoice_count",
--                 "label": "Invoices",
--                 "sortable": true,
--                 "width": "8%",
--                 "format": "count",
--                 "align": "center"
--             },
--             {
--                 "field": "avg_invoice_amount",
--                 "label": "Avg Invoice",
--                 "sortable": true,
--                 "width": "10%",
--                 "format": "currency",
--                 "align": "right"
--             },
--             {
--                 "field": "last_invoice_date",
--                 "label": "Last Invoice",
--                 "sortable": true,
--                 "width": "10%",
--                 "format": "date"
--             }
--         ],
--         "filters": [
--             {
--                 "field": "customer_status",
--                 "label": "Customer Status",
--                 "type": "select",
--                 "options": [
--                     {"value": "", "label": "All Statuses"},
--                     {"value": "active", "label": "Active"},
--                     {"value": "recent", "label": "Recent"},
--                     {"value": "inactive", "label": "Inactive"},
--                     {"value": "dormant", "label": "Dormant"}
--                 ],
--                 "default": ""
--             },
--             {
--                 "field": "min_revenue",
--                 "label": "Min Revenue",
--                 "type": "number",
--                 "placeholder": "0.00"
--             },
--             {
--                 "field": "date_from",
--                 "label": "Date From",
--                 "type": "date"
--             },
--             {
--                 "field": "date_to",
--                 "label": "Date To",
--                 "type": "date"
--             },
--             {
--                 "field": "search",
--                 "label": "Search",
--                 "type": "text",
--                 "placeholder": "Search customer name..."
--             }
--         ],
--         "rowActions": [
--             {
--                 "label": "View Details",
--                 "icon": "fa-eye",
--                 "action": "reports:view-customer-details",
--                 "color": "info"
--             },
--             {
--                 "label": "Invoice Drill-Down",
--                 "icon": "fa-list",
--                 "action": "reports:drill-down-invoices",
--                 "color": "primary"
--             },
--             {
--                 "label": "Send Statement",
--                 "icon": "fa-envelope",
--                 "action": "reports:send-customer-statement",
--                 "color": "accent",
--                 "confirm": "Send statement to this customer?"
--             },
--             {
--                 "label": "Export Customer Report",
--                 "icon": "fa-file-export",
--                 "action": "reports:export-customer-csv",
--                 "color": "secondary"
--             }
--         ],
--         "bulkActions": [
--             {
--                 "label": "Export Selected",
--                 "icon": "fa-file-csv",
--                 "action": "reports:export-selected-csv",
--                 "color": "secondary"
--             },
--             {
--                 "label": "Send Statements",
--                 "icon": "fa-paper-plane",
--                 "action": "reports:send-statements-bulk",
--                 "color": "primary",
--                 "confirm": "Send statements to {count} customers?"
--             },
--             {
--                 "label": "Analyze Trends",
--                 "icon": "fa-chart-line",
--                 "action": "reports:analyze-customer-trends",
--                 "color": "info"
--             }
--         ],
--         "summaryWidgets": [
--             {
--                 "id": "total-customer-revenue",
--                 "type": "stat",
--                 "title": "Total Revenue",
--                 "icon": "fa-dollar-sign",
--                 "color": "success",
--                 "dataPath": "totals.total_revenue",
--                 "format": "currency"
--             },
--             {
--                 "id": "customer-count",
--                 "type": "stat",
--                 "title": "Total Customers",
--                 "icon": "fa-users",
--                 "color": "info",
--                 "dataPath": "totals.customer_count",
--                 "format": "count"
--             },
--             {
--                 "id": "avg-customer-revenue",
--                 "type": "stat",
--                 "title": "Avg Revenue per Customer",
--                 "icon": "fa-chart-bar",
--                 "color": "primary",
--                 "dataPath": "totals.avg_revenue",
--                 "format": "currency"
--             },
--             {
--                 "id": "top-customer",
--                 "type": "stat",
--                 "title": "Top Customer",
--                 "icon": "fa-trophy",
--                 "color": "warning",
--                 "dataPath": "totals.top_customer_name",
--                 "subtitle": {
--                     "dataPath": "totals.top_customer_revenue",
--                     "format": "currency"
--                 }
--             }
--         ],
--         "exportOptions": [
--             {
--                 "label": "Export to CSV",
--                 "action": "reports:export-csv",
--                 "icon": "fa-file-csv",
--                 "params": {"reportType": "revenue-by-customer"}
--             },
--             {
--                 "label": "Export to PDF",
--                 "action": "reports:export-pdf",
--                 "icon": "fa-file-pdf",
--                 "params": {"reportType": "revenue-by-customer"}
--             }
--         ]
--     }',
--     true,
--     NOW()
-- ) ON CONFLICT (module_id) DO UPDATE SET
--     config = EXCLUDED.config,
--     updated_at = NOW();
-- 
-- -- ============================================================================
-- -- MODULE 3: PRODUCT REVENUE REPORT
-- -- ============================================================================
-- -- Purpose: Product/service performance analysis
-- -- Type: list
-- -- Features:
-- --   - 10 columns showing product metrics
-- --   - 5 filters (category, active status, min revenue)
-- --   - 4 row actions (view details, drill-down, analyze)
-- --   - 3 bulk actions (export, compare, categorize)
-- --   - 4 summary widgets
-- --   - Auto-refresh every 120 seconds
-- -- ============================================================================
-- 
-- INSERT INTO modules (
--     module_id,
--     name,
--     title,
--     icon,
--     type,
--     category,
--     description,
--     config,
--     is_active,
--     created_at
-- ) VALUES (
--     'product-revenue-report',
--     'ProductRevenueReport',
--     'Product Revenue Report',
--     'fa-box',
--     'list',
--     'Finance',
--     'Product and service revenue analysis with sales metrics and trends',
--     '{
--         "dataSource": "/api/reports/revenue-by-product/:orgId",
--         "autoRefresh": 120000,
--         "pagination": {
--             "enabled": true,
--             "pageSize": 25,
--             "pageSizes": [10, 25, 50, 100]
--         },
--         "columns": [
--             {
--                 "field": "product_name",
--                 "label": "Product/Service",
--                 "sortable": true,
--                 "searchable": true,
--                 "width": "20%",
--                 "render": "link",
--                 "linkAction": "reports:view-product-details"
--             },
--             {
--                 "field": "category",
--                 "label": "Category",
--                 "sortable": true,
--                 "width": "12%",
--                 "render": "badge",
--                 "badgeColor": "info"
--             },
--             {
--                 "field": "total_revenue",
--                 "label": "Total Revenue",
--                 "sortable": true,
--                 "width": "12%",
--                 "format": "currency",
--                 "align": "right"
--             },
--             {
--                 "field": "revenue_ytd",
--                 "label": "Revenue YTD",
--                 "sortable": true,
--                 "width": "12%",
--                 "format": "currency",
--                 "align": "right"
--             },
--             {
--                 "field": "quantity_sold",
--                 "label": "Qty Sold",
--                 "sortable": true,
--                 "width": "8%",
--                 "format": "number",
--                 "align": "center"
--             },
--             {
--                 "field": "times_sold",
--                 "label": "Times Sold",
--                 "sortable": true,
--                 "width": "8%",
--                 "format": "count",
--                 "align": "center"
--             },
--             {
--                 "field": "avg_selling_price",
--                 "label": "Avg Price",
--                 "sortable": true,
--                 "width": "10%",
--                 "format": "currency",
--                 "align": "right"
--             },
--             {
--                 "field": "unique_customers",
--                 "label": "Customers",
--                 "sortable": true,
--                 "width": "8%",
--                 "format": "count",
--                 "align": "center"
--             },
--             {
--                 "field": "last_sale_date",
--                 "label": "Last Sale",
--                 "sortable": true,
--                 "width": "10%",
--                 "format": "date"
--             }
--         ],
--         "filters": [
--             {
--                 "field": "category",
--                 "label": "Category",
--                 "type": "select",
--                 "options": [
--                     {"value": "", "label": "All Categories"},
--                     {"value": "Product", "label": "Products"},
--                     {"value": "Service", "label": "Services"}
--                 ],
--                 "default": ""
--             },
--             {
--                 "field": "is_active",
--                 "label": "Status",
--                 "type": "select",
--                 "options": [
--                     {"value": "", "label": "All"},
--                     {"value": "true", "label": "Active"},
--                     {"value": "false", "label": "Inactive"}
--                 ],
--                 "default": ""
--             },
--             {
--                 "field": "min_revenue",
--                 "label": "Min Revenue",
--                 "type": "number",
--                 "placeholder": "0.00"
--             },
--             {
--                 "field": "search",
--                 "label": "Search",
--                 "type": "text",
--                 "placeholder": "Search product/service..."
--             }
--         ],
--         "rowActions": [
--             {
--                 "label": "View Details",
--                 "icon": "fa-eye",
--                 "action": "reports:view-product-details",
--                 "color": "info"
--             },
--             {
--                 "label": "Sales History",
--                 "icon": "fa-history",
--                 "action": "reports:drill-down-product-sales",
--                 "color": "primary"
--             },
--             {
--                 "label": "Customer Analysis",
--                 "icon": "fa-users",
--                 "action": "reports:analyze-product-customers",
--                 "color": "accent"
--             },
--             {
--                 "label": "Export Product Report",
--                 "icon": "fa-file-export",
--                 "action": "reports:export-product-csv",
--                 "color": "secondary"
--             }
--         ],
--         "bulkActions": [
--             {
--                 "label": "Export Selected",
--                 "icon": "fa-file-csv",
--                 "action": "reports:export-selected-csv",
--                 "color": "secondary"
--             },
--             {
--                 "label": "Compare Products",
--                 "icon": "fa-code-compare",
--                 "action": "reports:compare-products",
--                 "color": "info"
--             },
--             {
--                 "label": "Bulk Categorize",
--                 "icon": "fa-tags",
--                 "action": "reports:bulk-categorize",
--                 "color": "warning"
--             }
--         ],
--         "summaryWidgets": [
--             {
--                 "id": "total-product-revenue",
--                 "type": "stat",
--                 "title": "Total Revenue",
--                 "icon": "fa-dollar-sign",
--                 "color": "success",
--                 "dataPath": "totals.total_revenue",
--                 "format": "currency"
--             },
--             {
--                 "id": "product-count",
--                 "type": "stat",
--                 "title": "Products/Services",
--                 "icon": "fa-box",
--                 "color": "info",
--                 "dataPath": "totals.product_count",
--                 "format": "count"
--             },
--             {
--                 "id": "total-qty-sold",
--                 "type": "stat",
--                 "title": "Total Quantity Sold",
--                 "icon": "fa-shopping-cart",
--                 "color": "primary",
--                 "dataPath": "totals.total_quantity",
--                 "format": "number"
--             },
--             {
--                 "id": "best-seller",
--                 "type": "stat",
--                 "title": "Best Seller",
--                 "icon": "fa-star",
--                 "color": "warning",
--                 "dataPath": "totals.best_seller_name",
--                 "subtitle": {
--                     "dataPath": "totals.best_seller_revenue",
--                     "format": "currency"
--                 }
--             }
--         ],
--         "exportOptions": [
--             {
--                 "label": "Export to CSV",
--                 "action": "reports:export-csv",
--                 "icon": "fa-file-csv",
--                 "params": {"reportType": "revenue-by-product"}
--             },
--             {
--                 "label": "Export to PDF",
--                 "action": "reports:export-pdf",
--                 "icon": "fa-file-pdf",
--                 "params": {"reportType": "revenue-by-product"}
--             }
--         ]
--     }',
--     true,
--     NOW()
-- ) ON CONFLICT (module_id) DO UPDATE SET
--     config = EXCLUDED.config,
--     updated_at = NOW();
-- 
-- -- ============================================================================
-- -- MODULE 4: TAX REPORTS DASHBOARD
-- -- ============================================================================
-- -- Purpose: Sales tax collection and remittance tracking
-- -- Type: dashboard
-- -- Features:
-- --   - 5 summary widgets (tax stats)
-- --   - 2 tables (tax by rate, remittance schedule)
-- --   - 2 charts (tax breakdown, collection trends)
-- --   - Export for tax filing
-- --   - Auto-refresh every 300 seconds (5 minutes)
-- -- ============================================================================
-- 
-- INSERT INTO modules (
--     module_id,
--     name,
--     title,
--     icon,
--     type,
--     category,
--     description,
--     config,
--     is_active,
--     created_at
-- ) VALUES (
--     'tax-reports-dashboard',
--     'TaxReportsDashboard',
--     'Sales Tax Reports',
--     'fa-receipt',
--     'dashboard',
--     'Finance',
--     'Sales tax collection summary and remittance tracking',
--     '{
--         "layout": "grid",
--         "columns": 3,
--         "autoRefresh": 300000,
--         "widgets": [
--             {
--                 "id": "total-tax-collected-widget",
--                 "type": "stat",
--                 "title": "Total Tax Collected",
--                 "icon": "fa-dollar-sign",
--                 "color": "success",
--                 "dataSource": "/api/reports/sales-tax-summary/:orgId",
--                 "dataPath": "totals.total_tax_collected",
--                 "format": "currency",
--                 "size": "large",
--                 "position": {"row": 1, "col": 1}
--             },
--             {
--                 "id": "tax-paid-widget",
--                 "type": "stat",
--                 "title": "Tax Collected (Paid Invoices)",
--                 "icon": "fa-check-circle",
--                 "color": "primary",
--                 "dataSource": "/api/reports/sales-tax-summary/:orgId",
--                 "dataPath": "totals.tax_collected_paid",
--                 "format": "currency",
--                 "size": "large",
--                 "position": {"row": 1, "col": 2}
--             },
--             {
--                 "id": "tax-pending-widget",
--                 "type": "stat",
--                 "title": "Tax Pending (Unpaid Invoices)",
--                 "icon": "fa-clock",
--                 "color": "warning",
--                 "dataSource": "/api/reports/sales-tax-summary/:orgId",
--                 "dataPath": "totals.tax_collected_pending",
--                 "format": "currency",
--                 "size": "large",
--                 "position": {"row": 1, "col": 3}
--             },
--             {
--                 "id": "current-month-tax-widget",
--                 "type": "stat",
--                 "title": "Current Month Tax",
--                 "icon": "fa-calendar-day",
--                 "color": "info",
--                 "dataSource": "/api/reports/sales-tax-summary/:orgId",
--                 "dataPath": "totals.current_month_tax",
--                 "format": "currency",
--                 "size": "medium",
--                 "position": {"row": 2, "col": 1}
--             },
--             {
--                 "id": "current-quarter-tax-widget",
--                 "type": "stat",
--                 "title": "Current Quarter Tax",
--                 "icon": "fa-calendar",
--                 "color": "accent",
--                 "dataSource": "/api/reports/sales-tax-summary/:orgId",
--                 "dataPath": "totals.current_quarter_tax",
--                 "format": "currency",
--                 "size": "medium",
--                 "position": {"row": 2, "col": 2}
--             },
--             {
--                 "id": "ytd-tax-widget",
--                 "type": "stat",
--                 "title": "Year to Date Tax",
--                 "icon": "fa-calendar-check",
--                 "color": "secondary",
--                 "dataSource": "/api/reports/sales-tax-summary/:orgId",
--                 "dataPath": "totals.ytd_tax",
--                 "format": "currency",
--                 "size": "medium",
--                 "position": {"row": 2, "col": 3}
--             },
--             {
--                 "id": "tax-by-rate-table",
--                 "type": "table",
--                 "title": "Tax Collection by Rate",
--                 "icon": "fa-percent",
--                 "dataSource": "/api/reports/sales-tax-summary/:orgId",
--                 "dataPath": "data",
--                 "columns": [
--                     {
--                         "field": "tax_rate",
--                         "label": "Tax Rate",
--                         "format": "percentage",
--                         "width": "15%"
--                     },
--                     {
--                         "field": "taxable_amount",
--                         "label": "Taxable Amount",
--                         "format": "currency",
--                         "align": "right",
--                         "width": "20%"
--                     },
--                     {
--                         "field": "tax_collected_paid",
--                         "label": "Collected (Paid)",
--                         "format": "currency",
--                         "align": "right",
--                         "width": "20%"
--                     },
--                     {
--                         "field": "tax_collected_pending",
--                         "label": "Pending",
--                         "format": "currency",
--                         "align": "right",
--                         "width": "15%"
--                     },
--                     {
--                         "field": "invoice_count",
--                         "label": "Invoices",
--                         "format": "count",
--                         "align": "center",
--                         "width": "10%"
--                     },
--                     {
--                         "field": "total_with_tax",
--                         "label": "Total with Tax",
--                         "format": "currency",
--                         "align": "right",
--                         "width": "20%"
--                     }
--                 ],
--                 "size": "xlarge",
--                 "position": {"row": 3, "col": 1, "colspan": 2}
--             },
--             {
--                 "id": "tax-breakdown-chart",
--                 "type": "chart",
--                 "title": "Tax Breakdown by Rate",
--                 "chartType": "doughnut",
--                 "dataSource": "/api/reports/sales-tax-summary/:orgId",
--                 "dataPath": "data",
--                 "labelField": "tax_rate_label",
--                 "valueField": "tax_collected_paid",
--                 "format": "currency",
--                 "colors": ["#3b82f6", "#10b981", "#f59e0b", "#ef4444", "#8b5cf6", "#ec4899"],
--                 "size": "large",
--                 "position": {"row": 3, "col": 3}
--             },
--             {
--                 "id": "remittance-schedule-table",
--                 "type": "table",
--                 "title": "Remittance Schedule (Upcoming)",
--                 "icon": "fa-calendar-alt",
--                 "dataSource": "/api/reports/sales-tax-summary/:orgId",
--                 "dataPath": "remittance_schedule",
--                 "columns": [
--                     {
--                         "field": "due_date",
--                         "label": "Due Date",
--                         "format": "date",
--                         "width": "25%"
--                     },
--                     {
--                         "field": "period",
--                         "label": "Period",
--                         "width": "25%"
--                     },
--                     {
--                         "field": "amount_due",
--                         "label": "Amount Due",
--                         "format": "currency",
--                         "align": "right",
--                         "width": "25%"
--                     },
--                     {
--                         "field": "status",
--                         "label": "Status",
--                         "render": "badge",
--                         "badgeColors": {
--                             "pending": "warning",
--                             "paid": "success",
--                             "overdue": "error"
--                         },
--                         "width": "25%"
--                     }
--                 ],
--                 "size": "xlarge",
--                 "position": {"row": 4, "col": 1, "colspan": 3}
--             }
--         ],
--         "quickActions": [
--             {
--                 "label": "Export for Filing",
--                 "action": "reports:export-tax-filing-csv",
--                 "icon": "fa-file-export",
--                 "color": "primary"
--             },
--             {
--                 "label": "Generate Tax Report",
--                 "action": "reports:generate-tax-report-pdf",
--                 "icon": "fa-file-pdf",
--                 "color": "error"
--             },
--             {
--                 "label": "Email Tax Summary",
--                 "action": "reports:email-tax-summary",
--                 "icon": "fa-envelope",
--                 "color": "info"
--             },
--             {
--                 "label": "Schedule Remittance",
--                 "action": "reports:schedule-tax-remittance",
--                 "icon": "fa-calendar-plus",
--                 "color": "accent"
--             }
--         ]
--     }',
--     true,
--     NOW()
-- ) ON CONFLICT (module_id) DO UPDATE SET
--     config = EXCLUDED.config,
--     updated_at = NOW();
-- 
-- -- ============================================================================
-- -- MODULE 5: OUTSTANDING INVOICES REPORT
-- -- ============================================================================
-- -- Purpose: AR aging and outstanding invoices tracking
-- -- Type: list
-- -- Features:
-- --   - 8 columns showing AR details
-- --   - 4 filters (date range, aging bucket)
-- --   - 4 row actions (view, payment, reminder)
-- --   - 3 bulk actions
-- --   - 6 summary widgets (aging buckets)
-- -- ============================================================================
-- 
-- INSERT INTO modules (
--     module_id,
--     name,
--     title,
--     icon,
--     type,
--     category,
--     description,
--     config,
--     is_active,
--     created_at
-- ) VALUES (
--     'outstanding-invoices-report',
--     'OutstandingInvoicesReport',
--     'Outstanding Invoices Report',
--     'fa-file-invoice-dollar',
--     'list',
--     'Finance',
--     'Accounts receivable aging report with collection tracking',
--     '{
--         "dataSource": "/api/reports/outstanding-invoices/:orgId",
--         "autoRefresh": 120000,
--         "pagination": {
--             "enabled": true,
--             "pageSize": 25,
--             "pageSizes": [10, 25, 50, 100]
--         },
--         "columns": [
--             {
--                 "field": "customer_name",
--                 "label": "Customer",
--                 "sortable": true,
--                 "searchable": true,
--                 "width": "20%",
--                 "render": "link",
--                 "linkAction": "reports:view-customer-ar"
--             },
--             {
--                 "field": "total_outstanding",
--                 "label": "Total Outstanding",
--                 "sortable": true,
--                 "width": "12%",
--                 "format": "currency",
--                 "align": "right",
--                 "highlight": true
--             },
--             {
--                 "field": "current",
--                 "label": "Current",
--                 "sortable": true,
--                 "width": "10%",
--                 "format": "currency",
--                 "align": "right"
--             },
--             {
--                 "field": "overdue_0_30",
--                 "label": "0-30 Days",
--                 "sortable": true,
--                 "width": "10%",
--                 "format": "currency",
--                 "align": "right",
--                 "colorClass": "text-warning"
--             },
--             {
--                 "field": "overdue_30_60",
--                 "label": "30-60 Days",
--                 "sortable": true,
--                 "width": "10%",
--                 "format": "currency",
--                 "align": "right",
--                 "colorClass": "text-warning"
--             },
--             {
--                 "field": "overdue_60_90",
--                 "label": "60-90 Days",
--                 "sortable": true,
--                 "width": "10%",
--                 "format": "currency",
--                 "align": "right",
--                 "colorClass": "text-error"
--             },
--             {
--                 "field": "overdue_90_plus",
--                 "label": "90+ Days",
--                 "sortable": true,
--                 "width": "10%",
--                 "format": "currency",
--                 "align": "right",
--                 "colorClass": "text-error",
--                 "bold": true
--             },
--             {
--                 "field": "invoice_count",
--                 "label": "Invoices",
--                 "sortable": true,
--                 "width": "8%",
--                 "format": "count",
--                 "align": "center"
--             }
--         ],
--         "filters": [
--             {
--                 "field": "aging_bucket",
--                 "label": "Aging Bucket",
--                 "type": "select",
--                 "options": [
--                     {"value": "", "label": "All Buckets"},
--                     {"value": "current", "label": "Current"},
--                     {"value": "0-30", "label": "0-30 Days"},
--                     {"value": "30-60", "label": "30-60 Days"},
--                     {"value": "60-90", "label": "60-90 Days"},
--                     {"value": "90+", "label": "90+ Days"}
--                 ],
--                 "default": ""
--             },
--             {
--                 "field": "min_outstanding",
--                 "label": "Min Outstanding",
--                 "type": "number",
--                 "placeholder": "0.00"
--             },
--             {
--                 "field": "search",
--                 "label": "Search",
--                 "type": "text",
--                 "placeholder": "Search customer..."
--             }
--         ],
--         "rowActions": [
--             {
--                 "label": "View Details",
--                 "icon": "fa-eye",
--                 "action": "reports:view-ar-details",
--                 "color": "info"
--             },
--             {
--                 "label": "Invoice List",
--                 "icon": "fa-list",
--                 "action": "reports:view-customer-invoices",
--                 "color": "primary"
--             },
--             {
--                 "label": "Record Payment",
--                 "icon": "fa-money-bill",
--                 "action": "invoices:record-payment",
--                 "color": "success"
--             },
--             {
--                 "label": "Send Reminder",
--                 "icon": "fa-bell",
--                 "action": "invoices:send-reminder",
--                 "color": "warning",
--                 "confirm": "Send payment reminder to this customer?"
--             }
--         ],
--         "bulkActions": [
--             {
--                 "label": "Send Reminders",
--                 "icon": "fa-paper-plane",
--                 "action": "reports:send-reminders-bulk",
--                 "color": "warning",
--                 "confirm": "Send payment reminders to {count} customers?"
--             },
--             {
--                 "label": "Export Selected",
--                 "icon": "fa-file-csv",
--                 "action": "reports:export-selected-csv",
--                 "color": "secondary"
--             },
--             {
--                 "label": "Generate Statements",
--                 "icon": "fa-file-invoice",
--                 "action": "reports:generate-statements-bulk",
--                 "color": "primary"
--             }
--         ],
--         "summaryWidgets": [
--             {
--                 "id": "total-outstanding",
--                 "type": "stat",
--                 "title": "Total Outstanding",
--                 "icon": "fa-dollar-sign",
--                 "color": "error",
--                 "dataPath": "totals.total_outstanding",
--                 "format": "currency"
--             },
--             {
--                 "id": "current-ar",
--                 "type": "stat",
--                 "title": "Current",
--                 "icon": "fa-check-circle",
--                 "color": "success",
--                 "dataPath": "totals.current",
--                 "format": "currency"
--             },
--             {
--                 "id": "overdue-0-30",
--                 "type": "stat",
--                 "title": "0-30 Days",
--                 "icon": "fa-clock",
--                 "color": "warning",
--                 "dataPath": "totals.overdue_0_30",
--                 "format": "currency"
--             },
--             {
--                 "id": "overdue-30-60",
--                 "type": "stat",
--                 "title": "30-60 Days",
--                 "icon": "fa-exclamation-circle",
--                 "color": "warning",
--                 "dataPath": "totals.overdue_30_60",
--                 "format": "currency"
--             },
--             {
--                 "id": "overdue-60-90",
--                 "type": "stat",
--                 "title": "60-90 Days",
--                 "icon": "fa-exclamation-triangle",
--                 "color": "error",
--                 "dataPath": "totals.overdue_60_90",
--                 "format": "currency"
--             },
--             {
--                 "id": "overdue-90-plus",
--                 "type": "stat",
--                 "title": "90+ Days",
--                 "icon": "fa-ban",
--                 "color": "error",
--                 "dataPath": "totals.overdue_90_plus",
--                 "format": "currency"
--             }
--         ],
--         "exportOptions": [
--             {
--                 "label": "Export to CSV",
--                 "action": "reports:export-csv",
--                 "icon": "fa-file-csv",
--                 "params": {"reportType": "outstanding-invoices"}
--             },
--             {
--                 "label": "Export to PDF",
--                 "action": "reports:export-pdf",
--                 "icon": "fa-file-pdf",
--                 "params": {"reportType": "outstanding-invoices"}
--             }
--         ]
--     }',
--     true,
--     NOW()
-- ) ON CONFLICT (module_id) DO UPDATE SET
--     config = EXCLUDED.config,
--     updated_at = NOW();
-- 
-- -- ============================================================================
-- -- VERIFICATION QUERIES
-- -- ============================================================================
-- 
-- -- Check all modules were created successfully
-- SELECT 
--     module_id,
--     name,
--     title,
--     type,
--     category,
--     is_active,
--     created_at
-- FROM modules
-- WHERE module_id IN (
--     'financial-reports-dashboard',
--     'customer-revenue-report',
--     'product-revenue-report',
--     'tax-reports-dashboard',
--     'outstanding-invoices-report'
-- )
-- ORDER BY module_id;
-- 
-- -- Count widgets per module
-- SELECT 
--     module_id,
--     jsonb_array_length(config->'widgets') as widget_count,
--     jsonb_array_length(config->'columns') as column_count,
--     jsonb_array_length(config->'filters') as filter_count,
--     jsonb_array_length(config->'rowActions') as row_action_count
-- FROM modules
-- WHERE module_id IN (
--     'financial-reports-dashboard',
--     'customer-revenue-report',
--     'product-revenue-report',
--     'tax-reports-dashboard',
--     'outstanding-invoices-report'
-- );
-- 
-- -- ============================================================================
-- -- ROLLBACK SCRIPT (if needed)
-- -- ============================================================================
-- /*
-- DELETE FROM modules WHERE module_id IN (
--     'financial-reports-dashboard',
--     'customer-revenue-report',
--     'product-revenue-report',
--     'tax-reports-dashboard',
--     'outstanding-invoices-report'
-- );
-- */
-- 
-- -- ============================================================================
-- -- END OF MIGRATION
-- -- ============================================================================
-- -- ============================================================================
-- -- Phase 7 Task 1: Aging Report Modules
-- -- ============================================================================
-- -- Creates declarative modules for invoice aging reports
-- --
-- -- Modules:
-- --   1. AgingReportDashboard - Main aging dashboard with charts
-- --   2. AgingReportDetail - Detailed list view with filters
-- --   3. AgingReportByCustomer - Customer-focused aging view
-- --
-- -- Created: October 17, 2025
-- -- Status: Production Ready
-- -- ============================================================================
-- 
-- -- Prerequisites check
-- DO $$
-- BEGIN
--     IF NOT EXISTS (SELECT FROM pg_tables WHERE tablename = 'modules') THEN
--         RAISE EXCEPTION 'modules table does not exist.';
--     END IF;
--     
--     IF NOT EXISTS (SELECT FROM pg_views WHERE viewname = 'invoice_aging') THEN
--         RAISE EXCEPTION 'invoice_aging view does not exist. Run phase7_task1_aging_reports.sql first.';
--     END IF;
-- END $$;
-- 
-- -- Delete existing aging modules (for idempotency)
-- DELETE FROM modules WHERE name IN (
--     'AgingReportDashboard',
--     'AgingReportDetail',
--     'AgingReportByCustomer'
-- );
-- 
-- -- ============================================================================
-- -- Module 1: AgingReportDashboard
-- -- ============================================================================
-- 
-- INSERT INTO modules (
--     module_id,
--     name,
--     icon,
--     description,
--     config
-- ) VALUES (
--     uuid_generate_v7(),
--     'AgingReportDashboard',
--     'fa-chart-pie',
--     'Invoice aging analysis dashboard with visualizations',
--     '{
--         "type": "dashboard",
--         "refreshInterval": 60000,
--         "layout": "grid",
--         "widgets": [
--             {
--                 "id": "aging_summary_stats",
--                 "type": "stats",
--                 "title": "Aging Overview",
--                 "col": 1,
--                 "row": 1,
--                 "width": 4,
--                 "height": 1,
--                 "dataSource": "/api/aging-report/summary/{org_id}",
--                 "stats": [
--                     {
--                         "key": "totals.total_invoices",
--                         "label": "Outstanding Invoices",
--                         "icon": "fa-file-invoice",
--                         "color": "primary"
--                     },
--                     {
--                         "key": "totals.total_balance",
--                         "label": "Total Outstanding",
--                         "icon": "fa-dollar-sign",
--                         "color": "warning",
--                         "format": "currency"
--                     },
--                     {
--                         "key": "totals.avg_days_overdue",
--                         "label": "Avg Days Overdue",
--                         "icon": "fa-calendar-alt",
--                         "color": "error",
--                         "format": "number",
--                         "decimals": 1
--                     }
--                 ]
--             },
--             {
--                 "id": "aging_buckets_chart",
--                 "type": "chart",
--                 "title": "Aging by Bucket",
--                 "col": 1,
--                 "row": 2,
--                 "width": 2,
--                 "height": 2,
--                 "dataSource": "/api/aging-report/summary/{org_id}",
--                 "chartType": "pie",
--                 "dataKey": "summary",
--                 "labels": "age_bucket",
--                 "values": "total_balance",
--                 "colors": ["#10b981", "#f59e0b", "#f97316", "#dc2626", "#7c2d12"],
--                 "legend": true,
--                 "tooltips": true
--             },
--             {
--                 "id": "aging_buckets_bar",
--                 "type": "chart",
--                 "title": "Invoice Count by Age",
--                 "col": 3,
--                 "row": 2,
--                 "width": 2,
--                 "height": 2,
--                 "dataSource": "/api/aging-report/summary/{org_id}",
--                 "chartType": "bar",
--                 "dataKey": "summary",
--                 "xAxis": "age_bucket",
--                 "yAxis": ["invoice_count"],
--                 "colors": {
--                     "invoice_count": "#3b82f6"
--                 }
--             },
--             {
--                 "id": "top_overdue_customers",
--                 "type": "list",
--                 "title": "Top Overdue Customers",
--                 "col": 1,
--                 "row": 4,
--                 "width": 4,
--                 "height": 2,
--                 "dataSource": "/api/aging-report/top-overdue/{org_id}?limit=10",
--                 "columns": [
--                     {
--                         "key": "customer_name",
--                         "label": "Customer",
--                         "type": "text"
--                     },
--                     {
--                         "key": "overdue_count",
--                         "label": "Overdue Invoices",
--                         "type": "number"
--                     },
--                     {
--                         "key": "total_overdue",
--                         "label": "Total Overdue",
--                         "type": "currency"
--                     },
--                     {
--                         "key": "max_days_overdue",
--                         "label": "Max Days",
--                         "type": "number"
--                     },
--                     {
--                         "key": "severely_overdue_amount",
--                         "label": "90+ Days",
--                         "type": "currency",
--                         "badge": true,
--                         "badgeColor": "error"
--                     }
--                 ],
--                 "actions": [
--                     {
--                         "label": "View All",
--                         "link": "/aging-report/detail"
--                     }
--                 ]
--             }
--         ]
--     }'::jsonb
-- );
-- 
-- -- ============================================================================
-- -- Module 2: AgingReportDetail
-- -- ============================================================================
-- 
-- INSERT INTO modules (
--     module_id,
--     name,
--     icon,
--     description,
--     config
-- ) VALUES (
--     uuid_generate_v7(),
--     'AgingReportDetail',
--     'fa-list-alt',
--     'Detailed invoice aging report with filters and export',
--     '{
--         "type": "list",
--         "dataSource": "/api/aging-report/detail/{org_id}",
--         "refreshInterval": 60000,
--         "pagination": true,
--         "pageSize": 50,
--         "exportable": true,
--         "filters": [
--             {
--                 "key": "age_bucket",
--                 "label": "Age Bucket",
--                 "type": "select",
--                 "options": [
--                     {"value": "Current", "label": "Current"},
--                     {"value": "1-30 days", "label": "1-30 Days"},
--                     {"value": "31-60 days", "label": "31-60 Days"},
--                     {"value": "61-90 days", "label": "61-90 Days"},
--                     {"value": "90+ days", "label": "90+ Days"}
--                 ]
--             },
--             {
--                 "key": "customer_id",
--                 "label": "Customer",
--                 "type": "select",
--                 "dataSource": "/api/customers/list/{org_id}",
--                 "valueKey": "customer_id",
--                 "labelKey": "customer_name"
--             },
--             {
--                 "key": "status",
--                 "label": "Status",
--                 "type": "select",
--                 "options": [
--                     {"value": "finalized", "label": "Finalized"},
--                     {"value": "overdue", "label": "Overdue"},
--                     {"value": "paid", "label": "Paid"}
--                 ]
--             },
--             {
--                 "key": "min_balance",
--                 "label": "Min Balance",
--                 "type": "number",
--                 "min": 0,
--                 "step": 100
--             }
--         ],
--         "columns": [
--             {
--                 "key": "invoice_number",
--                 "label": "Invoice #",
--                 "type": "text",
--                 "sortable": true,
--                 "link": "/invoices/{invoice_id}"
--             },
--             {
--                 "key": "customer_name",
--                 "label": "Customer",
--                 "type": "text",
--                 "sortable": true
--             },
--             {
--                 "key": "invoice_date",
--                 "label": "Invoice Date",
--                 "type": "date",
--                 "sortable": true
--             },
--             {
--                 "key": "due_date",
--                 "label": "Due Date",
--                 "type": "date",
--                 "sortable": true
--             },
--             {
--                 "key": "total_amount",
--                 "label": "Total",
--                 "type": "currency",
--                 "sortable": true
--             },
--             {
--                 "key": "amount_paid",
--                 "label": "Paid",
--                 "type": "currency",
--                 "sortable": true
--             },
--             {
--                 "key": "balance_due",
--                 "label": "Balance",
--                 "type": "currency",
--                 "sortable": true
--             },
--             {
--                 "key": "days_overdue",
--                 "label": "Days Overdue",
--                 "type": "number",
--                 "sortable": true,
--                 "badge": true,
--                 "badgeConditions": [
--                     {"condition": "value == 0", "class": "badge-success"},
--                     {"condition": "value <= 30", "class": "badge-warning"},
--                     {"condition": "value <= 60", "class": "badge-warning"},
--                     {"condition": "value <= 90", "class": "badge-error"},
--                     {"condition": "value > 90", "class": "badge-error"}
--                 ]
--             },
--             {
--                 "key": "age_bucket",
--                 "label": "Age Bucket",
--                 "type": "badge",
--                 "sortable": true,
--                 "badges": {
--                     "Current": {"class": "badge-success"},
--                     "1-30 days": {"class": "badge-info"},
--                     "31-60 days": {"class": "badge-warning"},
--                     "61-90 days": {"class": "badge-warning"},
--                     "90+ days": {"class": "badge-error"}
--                 }
--             }
--         ],
--         "rowActions": [
--             {
--                 "label": "View Invoice",
--                 "icon": "fa-eye",
--                 "action": "invoice:view",
--                 "link": "/invoices/{invoice_id}"
--             },
--             {
--                 "label": "Send Reminder",
--                 "icon": "fa-envelope",
--                 "action": "invoice:send-reminder",
--                 "condition": "is_overdue == true",
--                 "confirm": "Send payment reminder to {customer_name}?"
--             },
--             {
--                 "label": "Record Payment",
--                 "icon": "fa-dollar-sign",
--                 "action": "invoice:record-payment",
--                 "openModal": true
--             }
--         ],
--         "bulkActions": [
--             {
--                 "label": "Send Reminders",
--                 "icon": "fa-envelope",
--                 "action": "invoice:send-bulk-reminders",
--                 "confirm": "Send payment reminders for {count} selected invoice(s)?"
--             },
--             {
--                 "label": "Export to CSV",
--                 "icon": "fa-file-csv",
--                 "action": "export:csv",
--                 "url": "/api/aging-report/export/csv/{org_id}"
--             }
--         ]
--     }'::jsonb
-- );
-- 
-- -- ============================================================================
-- -- Module 3: AgingReportByCustomer
-- -- ============================================================================
-- 
-- INSERT INTO modules (
--     module_id,
--     name,
--     icon,
--     description,
--     config
-- ) VALUES (
--     uuid_generate_v7(),
--     'AgingReportByCustomer',
--     'fa-users',
--     'Invoice aging grouped by customer',
--     '{
--         "type": "list",
--         "dataSource": "/api/aging-report/by-customer/{org_id}",
--         "refreshInterval": 60000,
--         "pagination": true,
--         "pageSize": 50,
--         "exportable": true,
--         "columns": [
--             {
--                 "key": "customer_name",
--                 "label": "Customer",
--                 "type": "text",
--                 "sortable": true
--             },
--             {
--                 "key": "invoice_count",
--                 "label": "Invoices",
--                 "type": "number",
--                 "sortable": true
--             },
--             {
--                 "key": "total_balance",
--                 "label": "Total Outstanding",
--                 "type": "currency",
--                 "sortable": true
--             },
--             {
--                 "key": "current_balance",
--                 "label": "Current",
--                 "type": "currency",
--                 "sortable": true
--             },
--             {
--                 "key": "days_1_30",
--                 "label": "1-30 Days",
--                 "type": "currency",
--                 "sortable": true
--             },
--             {
--                 "key": "days_31_60",
--                 "label": "31-60 Days",
--                 "type": "currency",
--                 "sortable": true
--             },
--             {
--                 "key": "days_61_90",
--                 "label": "61-90 Days",
--                 "type": "currency",
--                 "sortable": true
--             },
--             {
--                 "key": "days_90_plus",
--                 "label": "90+ Days",
--                 "type": "currency",
--                 "sortable": true,
--                 "badge": true,
--                 "badgeConditions": [
--                     {"condition": "value == 0", "class": "badge-success"},
--                     {"condition": "value > 0", "class": "badge-error"}
--                 ]
--             },
--             {
--                 "key": "max_days_overdue",
--                 "label": "Max Days",
--                 "type": "number",
--                 "sortable": true
--             }
--         ],
--         "rowActions": [
--             {
--                 "label": "View Customer",
--                 "icon": "fa-user",
--                 "action": "customer:view",
--                 "link": "/customers/{customer_id}"
--             },
--             {
--                 "label": "View Invoices",
--                 "icon": "fa-file-invoice",
--                 "action": "customer:view-invoices",
--                 "link": "/aging-report/detail?customer_id={customer_id}"
--             },
--             {
--                 "label": "Send Statement",
--                 "icon": "fa-envelope",
--                 "action": "customer:send-statement",
--                 "confirm": "Send account statement to {customer_name}?"
--             }
--         ],
--         "bulkActions": [
--             {
--                 "label": "Send Statements",
--                 "icon": "fa-envelope",
--                 "action": "customer:send-bulk-statements",
--                 "confirm": "Send account statements to {count} selected customer(s)?"
--             }
--         ]
--     }'::jsonb
-- );
-- 
-- -- ============================================================================
-- -- VERIFICATION
-- -- ============================================================================
-- 
-- -- Verify modules
-- DO $$
-- DECLARE
--     module_count INTEGER;
-- BEGIN
--     SELECT COUNT(*) INTO module_count FROM modules WHERE name LIKE 'AgingReport%';
--     IF module_count <> 3 THEN
--         RAISE WARNING 'Expected 3 Aging Report modules, found %', module_count;
--     ELSE
--         RAISE NOTICE '✅ Successfully inserted 3 Aging Report modules';
--     END IF;
-- END $$;
-- 
-- -- Display results
-- SELECT 
--     LEFT(module_id::text, 8) as id,
--     name,
--     icon,
--     description
-- FROM modules 
-- WHERE name LIKE 'AgingReport%'
-- ORDER BY name;
-- 
-- -- ============================================================================
-- -- END OF PHASE 7 TASK 1 - AGING REPORT MODULES
-- ============================================================================

-- ============================================================================
-- MISSING MODULES FROM PHASE 4-5 MIGRATIONS
-- Added to ensure deployment consistency across all machines
-- ============================================================================

-- ----------------------------------------------------------------------------
-- Quotation Settings Module (from phase4_settings_modules.sql)
-- ----------------------------------------------------------------------------
INSERT INTO modules (
    name,
    config,
    icon,
    aria_label,
    description
) VALUES (
    'Quotation Settings',
    $json${
        "title": "Quotation Settings",
        "modulePath": "settings/quotations",
        "body": [
            {
                "type": "form",
                "id": "quotationSettingsForm",
                "formName": "Quotation Settings",
                "options": {
                    "loadRecord": {
                        "table": "quotation_settings",
                        "orgScope": true
                    }
                }
            }
        ],
        "footer": [
            {
                "type": "button",
                "label": "Cancel",
                "class": "btn btn-ghost",
                "action": "close"
            },
            {
                "type": "button",
                "label": "Save",
                "icon": "fa-save",
                "class": "btn btn-primary",
                "action": "save",
                "ariaLabel": "Save quotation settings"
            }
        ]
    }$json$::jsonb,
    'fa-cog',
    'Quotation Settings',
    'Configure quotation defaults, numbering, and templates'
) ON CONFLICT DO NOTHING;

-- ----------------------------------------------------------------------------
-- Invoice Settings Module (from phase4_settings_modules.sql)
-- ----------------------------------------------------------------------------
INSERT INTO modules (
    name,
    config,
    icon,
    aria_label,
    description
) VALUES (
    'Invoice Settings',
    $json${
        "title": "Invoice Settings",
        "modulePath": "settings/invoices",
        "body": [
            {
                "type": "tabs",
                "tabs": [
                    {
                        "label": "General",
                        "icon": "fa-cog",
                        "elements": [
                            {
                                "type": "form",
                                "id": "invoiceSettingsForm",
                                "formName": "Invoice Settings",
                                "options": {
                                    "loadRecord": {
                                        "table": "invoice_settings",
                                        "orgScope": true
                                    }
                                }
                            }
                        ]
                    },
                    {
                        "label": "TaxCore",
                        "icon": "fa-file-invoice-dollar",
                        "elements": [
                            {
                                "type": "alert",
                                "class": "alert alert-info",
                                "icon": "fa-info-circle",
                                "text": "Configure TaxCore integration for automated tax submissions."
                            },
                            {
                                "type": "form",
                                "id": "taxcoreSettingsForm",
                                "formName": "TaxCore Settings",
                                "options": {
                                    "loadRecord": {
                                        "table": "taxcore_settings",
                                        "orgScope": true
                                    }
                                }
                            },
                            {
                                "type": "divider"
                            },
                            {
                                "type": "button",
                                "label": "Test TaxCore Connection",
                                "icon": "fa-plug",
                                "class": "btn btn-secondary",
                                "action": "taxcore:test-connection",
                                "ariaLabel": "Test TaxCore API connection"
                            }
                        ]
                    },
                    {
                        "label": "Templates",
                        "icon": "fa-file-alt",
                        "elements": [
                            {
                                "type": "button",
                                "label": "Add Template",
                                "icon": "fa-plus",
                                "class": "btn btn-primary mb-4",
                                "action": {
                                    "handler": "openTemplateForm"
                                }
                            },
                            {
                                "type": "table",
                                "id": "invoiceTemplates",
                                "options": {
                                    "tableName": "invoice_templates",
                                    "showGlobalSearch": false,
                                    "addButton": false,
                                    "rowActions": [
                                        {
                                            "label": "Edit",
                                            "icon": "fa-edit",
                                            "action": {
                                                "handler": "openTemplateForm"
                                            }
                                        },
                                        {
                                            "label": "Preview",
                                            "icon": "fa-eye",
                                            "action": "templates:preview"
                                        },
                                        {
                                            "label": "Set Default",
                                            "icon": "fa-check",
                                            "action": "templates:set-default",
                                            "condition": "is_default != true"
                                        },
                                        {
                                            "label": "Delete",
                                            "icon": "fa-trash",
                                            "class": "btn btn-error btn-xs",
                                            "action": "records:delete",
                                            "condition": "is_default != true",
                                            "confirm": "Delete this template?"
                                        }
                                    ]
                                }
                            }
                        ]
                    }
                ]
            }
        ],
        "footer": [
            {
                "type": "button",
                "label": "Close",
                "class": "btn btn-ghost",
                "action": "close"
            },
            {
                "type": "button",
                "label": "Save All",
                "icon": "fa-save",
                "class": "btn btn-primary",
                "action": "save",
                "confirm": "Save all settings?",
                "ariaLabel": "Save all invoice settings"
            }
        ]
    }$json$::jsonb,
    'fa-cog',
    'Invoice Settings',
    'Configure invoice defaults, TaxCore integration, and templates'
) ON CONFLICT DO NOTHING;

-- ----------------------------------------------------------------------------
-- Payment Methods Module (from phase4_settings_modules.sql)
-- ----------------------------------------------------------------------------
INSERT INTO modules (
    name,
    config,
    icon,
    aria_label,
    description
) VALUES (
    'Payment Methods',
    $json${
        "title": "Payment Methods",
        "modulePath": "settings/payment-methods",
        "header": [
            {
                "type": "button",
                "label": "Add Payment Method",
                "icon": "fa-plus",
                "class": "btn btn-primary",
                "action": {
                    "handler": "openPaymentMethodForm"
                },
                "ariaLabel": "Add new payment method"
            }
        ],
        "body": [
            {
                "type": "table",
                "id": "paymentMethodsTable",
                "options": {
                    "tableName": "payment_methods",
                    "showGlobalSearch": false,
                    "columnsToShow": ["name", "type", "is_active", "display_order"],
                    "columnLabels": {
                        "name": "Name",
                        "type": "Type",
                        "is_active": "Active",
                        "display_order": "Order"
                    },
                    "rowActions": [
                        {
                            "label": "Edit",
                            "icon": "fa-edit",
                            "class": "btn btn-info btn-xs",
                            "action": {
                                "handler": "openPaymentMethodForm"
                            }
                        },
                        {
                            "label": "Activate",
                            "icon": "fa-check",
                            "class": "btn btn-success btn-xs",
                            "action": "payment-methods:activate",
                            "condition": "is_active == false"
                        },
                        {
                            "label": "Deactivate",
                            "icon": "fa-ban",
                            "class": "btn btn-warning btn-xs",
                            "action": "payment-methods:deactivate",
                            "condition": "is_active == true",
                            "confirm": "Deactivate this payment method?"
                        },
                        {
                            "label": "Delete",
                            "icon": "fa-trash",
                            "class": "btn btn-error btn-xs",
                            "action": "records:delete",
                            "confirm": "Delete this payment method?"
                        }
                    ]
                }
            }
        ],
        "footer": [
            {
                "type": "button",
                "label": "Close",
                "class": "btn btn-ghost",
                "action": "close"
            }
        ]
    }$json$::jsonb,
    'fa-credit-card',
    'Payment Methods',
    'Manage available payment methods for invoices and quotations'
) ON CONFLICT DO NOTHING;

-- ----------------------------------------------------------------------------
-- My Quotations Module (from phase5_client_portal_simple.sql)
-- Client portal module for viewing quotations
-- ----------------------------------------------------------------------------
INSERT INTO modules (name, icon, description, config)
VALUES (
    'My Quotations',
    'fa-file-invoice',
    'View and manage your quotations',
    $json${
        "type": "list-detail",
        "table": "quotations",
        "primaryKey": "quotation_id",
        "dataFilter": "client_id IN (SELECT client_id FROM clients WHERE user_id = {current_user_id})",
        "list": {
            "title": "My Quotations",
            "columns": [
                {"field": "quotation_number", "label": "Number", "sortable": true},
                {"field": "date", "label": "Date", "type": "date", "sortable": true},
                {"field": "expires_at", "label": "Valid Until", "type": "date", "sortable": true},
                {"field": "total_amount", "label": "Amount", "type": "currency", "sortable": true},
                {"field": "status", "label": "Status", "type": "badge", "sortable": true}
            ],
            "defaultSort": {"field": "date", "direction": "desc"},
            "rowActions": [
                {
                    "label": "View",
                    "icon": "fa-eye",
                    "action": "openModal",
                    "modalId": "quotation-detail"
                },
                {
                    "label": "Accept",
                    "icon": "fa-check",
                    "action": "quotations:accept",
                    "condition": "status == \"sent\"",
                    "confirm": "Accept this quotation?",
                    "class": "btn-success btn-sm"
                },
                {
                    "label": "Reject",
                    "icon": "fa-times",
                    "action": "quotations:reject",
                    "condition": "status == \"sent\"",
                    "class": "btn-error btn-sm"
                },
                {
                    "label": "Download PDF",
                    "icon": "fa-file-pdf",
                    "action": "quotations:pdf",
                    "class": "btn-ghost btn-sm"
                }
            ]
        },
        "detail": {
            "modalId": "quotation-detail",
            "title": "Quotation Details",
            "size": "large",
            "readonly": true,
            "sections": [
                {
                    "title": "Quotation Information",
                    "fields": [
                        {"name": "quotation_number", "label": "Quotation #", "type": "text", "readonly": true},
                        {"name": "date", "label": "Date", "type": "date", "readonly": true},
                        {"name": "expires_at", "label": "Valid Until", "type": "date", "readonly": true},
                        {"name": "status", "label": "Status", "type": "text", "readonly": true},
                        {"name": "note", "label": "Notes", "type": "textarea", "readonly": true}
                    ]
                },
                {
                    "title": "Amount",
                    "fields": [
                        {"name": "total_amount", "label": "Total Amount", "type": "currency", "readonly": true}
                    ]
                }
            ]
        }
    }$json$::jsonb
) ON CONFLICT DO NOTHING;

-- ----------------------------------------------------------------------------
-- My Invoices Module (from phase5_client_portal_simple.sql)
-- Client portal module for viewing and paying invoices
-- ----------------------------------------------------------------------------
INSERT INTO modules (name, icon, description, config)
VALUES (
    'My Invoices',
    'fa-file-invoice-dollar',
    'View and pay your invoices',
    $json${
        "type": "list-detail",
        "table": "invoices",
        "primaryKey": "invoice_id",
        "dataFilter": "client_id IN (SELECT client_id FROM clients WHERE user_id = {current_user_id})",
        "list": {
            "title": "My Invoices",
            "columns": [
                {"field": "invoice_number", "label": "Number", "sortable": true},
                {"field": "date", "label": "Date", "type": "date", "sortable": true},
                {"field": "due_date", "label": "Due Date", "type": "date", "sortable": true},
                {"field": "amount", "label": "Amount", "type": "currency", "sortable": true},
                {"field": "amount_paid", "label": "Paid", "type": "currency", "sortable": true},
                {"field": "status", "label": "Status", "type": "badge", "sortable": true}
            ],
            "defaultSort": {"field": "date", "direction": "desc"},
            "rowActions": [
                {
                    "label": "View",
                    "icon": "fa-eye",
                    "action": "openModal",
                    "modalId": "invoice-detail"
                },
                {
                    "label": "Pay Now",
                    "icon": "fa-credit-card",
                    "action": "payments:initiate",
                    "condition": "amount_paid < amount",
                    "class": "btn-primary btn-sm"
                },
                {
                    "label": "Download PDF",
                    "icon": "fa-file-pdf",
                    "action": "invoices:pdf",
                    "class": "btn-ghost btn-sm"
                }
            ]
        },
        "detail": {
            "modalId": "invoice-detail",
            "title": "Invoice Details",
            "size": "large",
            "readonly": true,
            "sections": [
                {
                    "title": "Invoice Information",
                    "fields": [
                        {"name": "invoice_number", "label": "Invoice #", "type": "text", "readonly": true},
                        {"name": "date", "label": "Date", "type": "date", "readonly": true},
                        {"name": "due_date", "label": "Due Date", "type": "date", "readonly": true},
                        {"name": "status", "label": "Status", "type": "text", "readonly": true}
                    ]
                },
                {
                    "title": "Payment Details",
                    "fields": [
                        {"name": "amount", "label": "Total Amount", "type": "currency", "readonly": true},
                        {"name": "amount_paid", "label": "Amount Paid", "type": "currency", "readonly": true}
                    ]
                }
            ]
        }
    }$json$::jsonb
) ON CONFLICT DO NOTHING;

-- ----------------------------------------------------------------------------
-- My Account Module (from phase5_client_portal_simple.sql)
-- Client portal module for managing account information
-- ----------------------------------------------------------------------------
INSERT INTO modules (name, icon, description, config)
VALUES (
    'My Account',
    'fa-user-circle',
    'View and update your account information',
    $json${
        "type": "form",
        "table": "clients",
        "primaryKey": "client_id",
        "dataFilter": "user_id = {current_user_id}",
        "sections": [
            {
                "title": "Contact Information",
                "fields": [
                    {"name": "name", "label": "Name", "type": "text", "required": true},
                    {"name": "email", "label": "Email", "type": "email", "required": true},
                    {"name": "phone", "label": "Phone", "type": "tel"},
                    {"name": "address", "label": "Address", "type": "textarea", "rows": 3},
                    {"name": "city", "label": "City", "type": "text"},
                    {"name": "country", "label": "Country", "type": "text"}
                ]
            }
        ],
        "actions": {
            "edit": [
                {"label": "Save", "action": "save", "class": "btn-primary"},
                {"label": "Cancel", "action": "cancel"}
            ]
        }
    }$json$::jsonb
) ON CONFLICT DO NOTHING;

-- ----------------------------------------------------------------------------
-- Messages Module (from phase5_generic_messages.sql)
-- Generic messaging system for all contexts
-- ----------------------------------------------------------------------------
INSERT INTO modules (name, icon, description, config)
VALUES (
    'Messages',
    'fa-comments',
    'Manage message threads across all contexts',
    $json${
        "type": "list",
        "table": "message_threads",
        "list": {
            "columns": [
                {"field": "subject", "label": "Subject"},
                {"field": "context", "label": "Context"},
                {"field": "status", "label": "Status"},
                {"field": "created_at", "label": "Created", "type": "datetime"}
            ],
            "rowActions": [
                {"label": "View", "action": "messages:view"},
                {"label": "Reply", "action": "messages:reply"},
                {"label": "Close", "action": "messages:close", "condition": "status == \"open\""}
            ]
        }
    }$json$::jsonb
) ON CONFLICT DO NOTHING;

-- ============================================================================
-- END OF MISSING MODULES FROM PHASE 4-5 MIGRATIONS
-- ============================================================================

-- ============================================================================
-- POS Sessions Management Module (Phase 4 Declarative)
-- ============================================================================
-- Description: Declarative module for managing POS cashier sessions
-- Features:
--   - View all sessions (active and closed)
--   - Filter by status, cashier, date range
--   - Row actions: View Details, Close Session, Reopen Session
--   - Detail modal with session info and financial summary
-- Author: AI Assistant
-- Date: October 24, 2025
-- ============================================================================

INSERT INTO modules (
    module_id,
    name,
    config,
    org_id,
    branch_id,
    icon,
    aria_label,
    description
) VALUES (
    '0194d8e0-7890-7abc-def0-123456789abc'::uuid,
    'POS Sessions Management',
    '{
        "title": "POS Sessions Management",
        "table": "pos_sessions",
        "primaryKey": "session_id",
        "header": [
            {
                "type": "button",
                "label": "Refresh",
                "onClick": "refreshData",
                "icon": "fa-refresh"
            },
            {
                "type": "filter-select",
                "label": "Status",
                "options": {
                    "data_column": "status",
                    "options": [
                        {"label": "All", "value": ""},
                        {"label": "Active", "value": "active"},
                        {"label": "Closed", "value": "closed"},
                        {"label": "Abandoned", "value": "abandoned"}
                    ]
                }
            },
            {
                "type": "filter-date-range",
                "label": "Session Date",
                "options": {
                    "data_column": "session_start"
                }
            }
        ],
        "body": [
            {
                "type": "table",
                "id": "posSessionsTable",
                "options": {
                    "tableName": "pos_sessions",
                    "dataSource": "/api/pos_sessions",
                    "showGlobalSearch": true,
                    "addButton": false,
                    "rowClick": "selectRecord",
                    "columnsToShow": [
                        "cashier_name",
                        "session_start",
                        "session_end",
                        "status",
                        "opening_float",
                        "closing_cash_expected",
                        "closing_cash_declared",
                        "variance"
                    ],
                    "columnLabels": {
                        "cashier_name": "Cashier",
                        "session_start": "Start Time",
                        "session_end": "End Time",
                        "status": "Status",
                        "opening_float": "Opening Float",
                        "closing_cash_expected": "Expected Cash",
                        "closing_cash_declared": "Declared Cash",
                        "variance": "Variance"
                    },
                    "rowActions": [
                        {
                            "label": "View Details",
                            "icon": "fa-eye",
                            "onClick": "openSelectedDetail"
                        },
                        {
                            "label": "Close Session",
                            "icon": "fa-lock",
                            "action": "pos:closeSession",
                            "condition": "status == \"active\"",
                            "confirm": "Are you sure you want to close this session?"
                        },
                        {
                            "label": "Reopen Session",
                            "icon": "fa-unlock",
                            "action": "pos:reopenSession",
                            "condition": "status == \"closed\"",
                            "confirm": "Are you sure you want to reopen this session?"
                        }
                    ],
                    "sortBy": "session_start",
                    "sortOrder": "desc"
                }
            }
        ],
        "detail": {
            "modalId": "posSessionDetail",
            "title": "Session Details",
            "sections": [
                {
                    "title": "Session Information",
                    "type": "form",
                    "fields": [
                        {
                            "name": "cashier_name",
                            "label": "Cashier",
                            "type": "text",
                            "readonly": true
                        },
                        {
                            "name": "session_start",
                            "label": "Session Start",
                            "type": "datetime-local",
                            "readonly": true
                        },
                        {
                            "name": "session_end",
                            "label": "Session End",
                            "type": "datetime-local",
                            "readonly": true
                        },
                        {
                            "name": "status",
                            "label": "Status",
                            "type": "select",
                            "options": [
                                {"value": "active", "label": "Active"},
                                {"value": "closed", "label": "Closed"},
                                {"value": "abandoned", "label": "Abandoned"}
                            ],
                            "readonly": true
                        },
                        {
                            "name": "branch_id",
                            "label": "Branch",
                            "type": "text",
                            "readonly": true
                        },
                        {
                            "name": "pos_number",
                            "label": "POS Number",
                            "type": "text",
                            "readonly": true
                        }
                    ]
                },
                {
                    "title": "Financial Summary",
                    "type": "form",
                    "fields": [
                        {
                            "name": "opening_float",
                            "label": "Opening Float",
                            "type": "number",
                            "readonly": true,
                            "prefix": "$"
                        },
                        {
                            "name": "closing_cash_expected",
                            "label": "Expected Cash",
                            "type": "number",
                            "readonly": true,
                            "prefix": "$"
                        },
                        {
                            "name": "closing_cash_declared",
                            "label": "Declared Cash",
                            "type": "number",
                            "readonly": true,
                            "prefix": "$"
                        },
                        {
                            "name": "variance",
                            "label": "Variance",
                            "type": "number",
                            "readonly": true,
                            "prefix": "$",
                            "className": "text-red-600 font-bold"
                        }
                    ]
                },
                {
                    "title": "Session Transactions",
                    "type": "table",
                    "options": {
                        "tableName": "sales_receipts",
                        "dataSource": "/api/sales_receipts",
                        "filterField": "session_id",
                        "filterValue": "{session_id}",
                        "columnsToShow": [
                            "sales_receipt_id",
                            "sdcdatetime",
                            "transactiontype",
                            "total"
                        ],
                        "columnLabels": {
                            "sales_receipt_id": "Receipt ID",
                            "sdcdatetime": "Date/Time",
                            "transactiontype": "Type",
                            "total": "Total"
                        },
                        "addButton": false,
                        "showGlobalSearch": false
                    }
                }
            ],
            "actions": [
                {
                    "label": "Close Session",
                    "action": "pos:closeSession",
                    "condition": "status == \"active\"",
                    "confirm": "Close this session?",
                    "className": "btn-error"
                },
                {
                    "label": "Print Summary",
                    "action": "pos:printSessionSummary",
                    "icon": "fa-print",
                    "className": "btn-secondary"
                },
                {
                    "label": "Close",
                    "onClick": "closeModal",
                    "className": "btn-ghost"
                }
            ]
        },
        "footer": [
            {
                "type": "button",
                "label": "Close",
                "onClick": "closeModal"
            }
        ]
    }'::jsonb,
    NULL,
    NULL,
    'fa-cash-register',
    'POS Sessions Management',
    'View and manage POS cashier sessions'
) ON CONFLICT (module_id) DO UPDATE SET
    config = EXCLUDED.config,
    icon = EXCLUDED.icon,
    aria_label = EXCLUDED.aria_label,
    description = EXCLUDED.description,
    updatedAt = NOW();

-- ============================================================================
-- REVENUE BY CUSTOMER MODULE (Phase 4 Declarative - Finance Reporting)
-- ============================================================================
-- Purpose: Customer revenue analysis with trends, graphs, and export
-- Created: 2025-10-24
-- Dependencies: revenue_by_customer view, graphs table, AggregateController
-- ============================================================================

INSERT INTO modules (
    module_id,
    name,
    icon,
    aria_label,
    description,
    config,
    org_id,
    branch_id,
    updatedAt,
    isDeleted
)
VALUES (
    '0194a8b2-9001-7123-8123-123456789abc'::uuid,
    'Revenue by Customer',
    'fa-chart-line',
    'Revenue by Customer Analysis',
    'Track customer revenue, trends, and status with interactive charts',
    '{
        "title": "Revenue by Customer Analysis",
        "header": [
            {
                "type": "button",
                "label": "Export CSV",
                "onClick": "exportTableToCSV",
                "icon": "fa-download"
            },
            {
                "type": "button",
                "label": "Refresh",
                "onClick": "refreshModule",
                "icon": "fa-sync"
            }
        ],
        "body": [
            {
                "type": "table",
                "options": {
                    "tableName": "revenue_by_customer",
                    "dataSource": "/api/aggregate?table=revenue_by_customer",
                    "columnsToShow": [
                        "customer_name",
                        "email",
                        "phone",
                        "total_invoices",
                        "paid_invoices",
                        "total_revenue",
                        "avg_invoice_amount",
                        "revenue_last_30_days",
                        "revenue_ytd",
                        "customer_status",
                        "customer_since"
                    ],
                    "columnLabels": {
                        "customer_name": "Customer Name",
                        "email": "Email",
                        "phone": "Phone",
                        "total_invoices": "Total Invoices",
                        "paid_invoices": "Paid Invoices",
                        "total_revenue": "Total Revenue",
                        "avg_invoice_amount": "Avg Invoice",
                        "revenue_last_30_days": "Last 30 Days",
                        "revenue_ytd": "YTD Revenue",
                        "customer_status": "Status",
                        "customer_since": "Customer Since"
                    },
                    "showGlobalSearch": true,
                    "addButton": false,
                    "sortColumn": "total_revenue",
                    "sortDirection": "DESC"
                }
            }
        ],
        "footer": [
            {
                "type": "button",
                "label": "Close",
                "onClick": "closeModal"
            }
        ]
    }'::jsonb,
    NULL,
    NULL,
    NOW(),
    false
) ON CONFLICT (module_id) DO UPDATE SET
    config = EXCLUDED.config,
    icon = EXCLUDED.icon,
    aria_label = EXCLUDED.aria_label,
    description = EXCLUDED.description,
    updatedAt = NOW();
-- ============================================================================
-- Phase 8: Inventory Analytics Modules Registration
-- Purpose: Register declarative modules for inventory analytics dashboards
-- Pattern: Follows procurement analytics module pattern with data-controller
-- ============================================================================


-- ============================================================================
-- Module 1: VAT Analytics Dashboard
-- Queries: Basic VAT Summary, Daily Cash Flow
-- Uses: AggregateRowsController GROUP BY
-- ============================================================================
INSERT INTO modules (module_id, name, config, org_id, branch_id, icon, aria_label, description) VALUES
  (
    '019a17e0-d2fa-79f8-b4e8-ff29f7041ef9'::uuid,
    'vat_analytics_dashboard',
    '{"title":"VAT Analytics Dashboard","body":[{"type":"html","html":"<div data-controller=\"VatAnalyticsDashboard\" class=\"space-y-6\">\n  <div class=\"flex flex-wrap items-center justify-between gap-3\">\n    <div class=\"flex flex-wrap gap-3\">\n      <label class=\"form-control w-48\">\n        <span class=\"label-text text-sm\">Date Range</span>\n        <input type=\"date\" class=\"input input-bordered input-sm\" data-filter=\"start_date\" />\n      </label>\n      <label class=\"form-control w-48\">\n        <span class=\"label-text text-sm\">To</span>\n        <input type=\"date\" class=\"input input-bordered input-sm\" data-filter=\"end_date\" />\n      </label>\n      <label class=\"form-control w-40\">\n        <span class=\"label-text text-sm\">Organization</span>\n        <select class=\"select select-bordered select-sm\" data-filter=\"org_id\">\n          <option value=\"\">All Orgs</option>\n        </select>\n      </label>\n    </div>\n    <button class=\"btn btn-sm btn-primary\" onclick=\"refreshVatAnalytics()\">Refresh</button>\n  </div>\n  <div class=\"hidden text-sm text-error\" data-role=\"error-container\"></div>\n  <div class=\"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-4\" data-role=\"metric-cards\"></div>\n  <div class=\"card bg-base-100 shadow-md shadow-slate-400/50\">\n    <div class=\"card-body\">\n      <h3 class=\"card-title\">VAT Summary by Code</h3>\n      <div class=\"overflow-x-auto\">\n        <table class=\"table table-sm\" data-role=\"vat-summary-table\">\n          <thead>\n            <tr><th>VAT Code</th><th>VAT Rate</th><th>Taxable Amount</th><th>VAT Amount</th><th>Total</th><th>Transactions</th></tr>\n          </thead>\n          <tbody></tbody>\n        </table>\n      </div>\n    </div>\n  </div>\n  <div class=\"grid grid-cols-1 lg:grid-cols-2 gap-6\">\n    <div class=\"card bg-base-100 shadow-md shadow-slate-400/50\">\n      <div class=\"card-body\">\n        <h3 class=\"card-title\">VAT Distribution</h3>\n        <div class=\"h-64\">\n          <canvas data-role=\"vat-chart\"></canvas>\n        </div>\n      </div>\n    </div>\n    <div class=\"card bg-base-100 shadow-md shadow-slate-400/50\">\n      <div class=\"card-body\">\n        <h3 class=\"card-title\">Daily VAT Trend</h3>\n        <div class=\"h-64\">\n          <canvas data-role=\"daily-vat-chart\"></canvas>\n        </div>\n      </div>\n    </div>\n  </div>\n</div>"}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}'::jsonb,
    NULL,
    NULL,
    'fa-percent',
    'VAT Analytics Dashboard',
    'VAT Analytics Dashboard'
  )
ON CONFLICT (module_id) DO UPDATE SET
    config = EXCLUDED.config,
    icon = EXCLUDED.icon,
    aria_label = EXCLUDED.aria_label,
    description = EXCLUDED.description;

-- ============================================================================
-- Module 2: Product Movement Analytics
-- Queries: Top 10 Best Sellers, Product Sales Trend
-- Uses: AggregateRowsController with filters
-- ============================================================================
INSERT INTO modules (module_id, name, config, org_id, branch_id, icon, aria_label, description) VALUES
  (
    '019a17e0-d2fa-7e1e-aa3c-f05811135cea'::uuid,
    'product_movement_analytics',
    '{"title":"Product Movement Analytics","body":[{"type":"html","html":"<div data-controller=\"ProductMovementAnalytics\" class=\"space-y-6\">\n  <div class=\"flex flex-wrap items-center justify-between gap-3\">\n    <div class=\"flex flex-wrap gap-3\">\n      <label class=\"form-control w-48\">\n        <span class=\"label-text text-sm\">Date Range</span>\n        <input type=\"date\" class=\"input input-bordered input-sm\" data-filter=\"start_date\" />\n      </label>\n      <label class=\"form-control w-48\">\n        <span class=\"label-text text-sm\">To</span>\n        <input type=\"date\" class=\"input input-bordered input-sm\" data-filter=\"end_date\" />\n      </label>\n      <label class=\"form-control w-40\">\n        <span class=\"label-text text-sm\">Category</span>\n        <select class=\"select select-bordered select-sm\" data-filter=\"category_id\">\n          <option value=\"\">All Categories</option>\n        </select>\n      </label>\n    </div>\n    <button class=\"btn btn-sm btn-primary\" onclick=\"refreshProductMovement()\">Refresh</button>\n  </div>\n  <div class=\"hidden text-sm text-error\" data-role=\"error-container\"></div>\n  <div class=\"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-4\" data-role=\"metric-cards\"></div>\n  <div class=\"grid grid-cols-1 lg:grid-cols-2 gap-6\">\n    <div class=\"card bg-base-100 shadow-md shadow-slate-400/50\">\n      <div class=\"card-body\">\n        <h3 class=\"card-title\">Top 10 Best Sellers</h3>\n        <div class=\"h-80\">\n          <canvas data-role=\"top-products-chart\"></canvas>\n        </div>\n      </div>\n    </div>\n    <div class=\"card bg-base-100 shadow-md shadow-slate-400/50\">\n      <div class=\"card-body\">\n        <h3 class=\"card-title\">Sales by Category</h3>\n        <div class=\"h-80\">\n          <canvas data-role=\"category-chart\"></canvas>\n        </div>\n      </div>\n    </div>\n  </div>\n  <div class=\"card bg-base-100 shadow-md shadow-slate-400/50\">\n    <div class=\"card-body\">\n      <h3 class=\"card-title\">Product Performance Table</h3>\n      <div class=\"overflow-x-auto\">\n        <table class=\"table table-sm\" data-role=\"product-table\">\n          <thead>\n            <tr><th>Product</th><th>Quantity Sold</th><th>Revenue</th><th>Avg Price</th><th>Transactions</th></tr>\n          </thead>\n          <tbody></tbody>\n        </table>\n      </div>\n    </div>\n  </div>\n</div>"}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}'::jsonb,
    NULL,
    NULL,
    'fa-boxes-stacked',
    'Product Movement Analytics',
    'Product Movement Analytics'
  )
ON CONFLICT (module_id) DO UPDATE SET
    config = EXCLUDED.config,
    icon = EXCLUDED.icon,
    aria_label = EXCLUDED.aria_label,
    description = EXCLUDED.description;

-- ============================================================================
-- Module 3: Payment Methods Analytics
-- Queries: Payment Method Summary, Daily Cash Flow
-- Uses: AggregateRowsController GROUP BY payment_method
-- ============================================================================
INSERT INTO modules (module_id, name, config, org_id, branch_id, icon, aria_label, description) VALUES
  (
    '019a17e0-d2fa-7895-958d-5695eef8bd22'::uuid,
    'payment_methods_analytics',
    '{"title":"Payment Methods Analytics","body":[{"type":"html","html":"<div data-controller=\"PaymentMethodsAnalytics\" class=\"space-y-6\">\n  <div class=\"flex flex-wrap items-center justify-between gap-3\">\n    <div class=\"flex flex-wrap gap-3\">\n      <label class=\"form-control w-48\">\n        <span class=\"label-text text-sm\">Date Range</span>\n        <input type=\"date\" class=\"input input-bordered input-sm\" data-filter=\"start_date\" />\n      </label>\n      <label class=\"form-control w-48\">\n        <span class=\"label-text text-sm\">To</span>\n        <input type=\"date\" class=\"input input-bordered input-sm\" data-filter=\"end_date\" />\n      </label>\n      <label class=\"form-control w-40\">\n        <span class=\"label-text text-sm\">Branch</span>\n        <select class=\"select select-bordered select-sm\" data-filter=\"branch_id\">\n          <option value=\"\">All Branches</option>\n        </select>\n      </label>\n    </div>\n    <button class=\"btn btn-sm btn-primary\" onclick=\"refreshPaymentMethods()\">Refresh</button>\n  </div>\n  <div class=\"hidden text-sm text-error\" data-role=\"error-container\"></div>\n  <div class=\"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-4\" data-role=\"metric-cards\"></div>\n  <div class=\"grid grid-cols-1 lg:grid-cols-2 gap-6\">\n    <div class=\"card bg-base-100 shadow-md shadow-slate-400/50\">\n      <div class=\"card-body\">\n        <h3 class=\"card-title\">Payment Method Breakdown</h3>\n        <div class=\"h-64\">\n          <canvas data-role=\"payment-breakdown-chart\"></canvas>\n        </div>\n      </div>\n    </div>\n    <div class=\"card bg-base-100 shadow-md shadow-slate-400/50\">\n      <div class=\"card-body\">\n        <h3 class=\"card-title\">Daily Cash Flow</h3>\n        <div class=\"h-64\">\n          <canvas data-role=\"cash-flow-chart\"></canvas>\n        </div>\n      </div>\n    </div>\n  </div>\n  <div class=\"card bg-base-100 shadow-md shadow-slate-400/50\">\n    <div class=\"card-body\">\n      <h3 class=\"card-title\">Payment Methods Summary</h3>\n      <div class=\"overflow-x-auto\">\n        <table class=\"table table-sm\" data-role=\"payment-summary-table\">\n          <thead>\n            <tr><th>Payment Method</th><th>Total Amount</th><th>Transactions</th><th>Avg Transaction</th><th>% of Total</th></tr>\n          </thead>\n          <tbody></tbody>\n        </table>\n      </div>\n    </div>\n  </div>\n  <div class=\"card bg-base-100 shadow-md shadow-slate-400/50\">\n    <div class=\"card-body\">\n      <h3 class=\"card-title\">Credit Outstanding</h3>\n      <div class=\"overflow-x-auto\">\n        <table class=\"table table-sm\" data-role=\"credit-table\">\n          <thead>\n            <tr><th>Customer</th><th>Amount Due</th><th>Due Date</th><th>Days Outstanding</th><th>Status</th></tr>\n          </thead>\n          <tbody></tbody>\n        </table>\n      </div>\n    </div>\n  </div>\n</div>"}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}'::jsonb,
    NULL,
    NULL,
    'fa-credit-card',
    'Payment Methods Analytics',
    'Payment Methods Analytics'
  )
ON CONFLICT (module_id) DO UPDATE SET
    config = EXCLUDED.config,
    icon = EXCLUDED.icon,
    aria_label = EXCLUDED.aria_label,
    description = EXCLUDED.description;

-- ============================================================================
-- Module 4: Customer Analytics Dashboard
-- Queries: Top Customers by Revenue, Purchase Frequency
-- Uses: AggregateRowsController GROUP BY customer_id
-- ============================================================================
INSERT INTO modules (module_id, name, config, org_id, branch_id, icon, aria_label, description) VALUES
  (
    '019a17e0-d2fa-7d7c-800b-8d3e6663cc21'::uuid,
    'customer_analytics_dashboard',
    '{"title":"Customer Analytics Dashboard","body":[{"type":"html","html":"<div data-controller=\"CustomerAnalyticsDashboard\" class=\"space-y-6\">\n  <div class=\"flex flex-wrap items-center justify-between gap-3\">\n    <div class=\"flex flex-wrap gap-3\">\n      <label class=\"form-control w-48\">\n        <span class=\"label-text text-sm\">Date Range</span>\n        <input type=\"date\" class=\"input input-bordered input-sm\" data-filter=\"start_date\" />\n      </label>\n      <label class=\"form-control w-48\">\n        <span class=\"label-text text-sm\">To</span>\n        <input type=\"date\" class=\"input input-bordered input-sm\" data-filter=\"end_date\" />\n      </label>\n    </div>\n    <button class=\"btn btn-sm btn-primary\" onclick=\"refreshCustomerAnalytics()\">Refresh</button>\n  </div>\n  <div class=\"hidden text-sm text-error\" data-role=\"error-container\"></div>\n  <div class=\"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-4\" data-role=\"metric-cards\"></div>\n  <div class=\"grid grid-cols-1 lg:grid-cols-2 gap-6\">\n    <div class=\"card bg-base-100 shadow-md shadow-slate-400/50\">\n      <div class=\"card-body\">\n        <h3 class=\"card-title\">Top 10 Customers by Revenue</h3>\n        <div class=\"h-80\">\n          <canvas data-role=\"top-customers-chart\"></canvas>\n        </div>\n      </div>\n    </div>\n    <div class=\"card bg-base-100 shadow-md shadow-slate-400/50\">\n      <div class=\"card-body\">\n        <h3 class=\"card-title\">Purchase Frequency Distribution</h3>\n        <div class=\"h-80\">\n          <canvas data-role=\"frequency-chart\"></canvas>\n        </div>\n      </div>\n    </div>\n  </div>\n  <div class=\"card bg-base-100 shadow-md shadow-slate-400/50\">\n    <div class=\"card-body\">\n      <h3 class=\"card-title\">Customer Performance Table</h3>\n      <div class=\"overflow-x-auto\">\n        <table class=\"table table-sm\" data-role=\"customer-table\">\n          <thead>\n            <tr><th>Customer</th><th>Total Revenue</th><th>Transactions</th><th>Avg Transaction</th><th>Last Purchase</th></tr>\n          </thead>\n          <tbody></tbody>\n        </table>\n      </div>\n    </div>\n  </div>\n</div>"}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}'::jsonb,
    NULL,
    NULL,
    'fa-users',
    'Customer Analytics Dashboard',
    'Customer Analytics Dashboard'
  )
ON CONFLICT (module_id) DO UPDATE SET
    config = EXCLUDED.config,
    icon = EXCLUDED.icon,
    aria_label = EXCLUDED.aria_label,
    description = EXCLUDED.description;

-- ============================================================================
-- Module 5: Staff Performance Analytics
-- Queries: Cashier Sales Performance, Cashier Efficiency
-- Uses: AggregateRowsController GROUP BY cashier_id
-- ============================================================================
INSERT INTO modules (module_id, name, config, org_id, branch_id, icon, aria_label, description) VALUES
  (
    '019a17e0-d2fa-7297-9f71-caad9591440f'::uuid,
    'staff_performance_analytics',
    '{"title":"Staff Performance Analytics","body":[{"type":"html","html":"<div data-controller=\"StaffPerformanceAnalytics\" class=\"space-y-6\">\n  <div class=\"flex flex-wrap items-center justify-between gap-3\">\n    <div class=\"flex flex-wrap gap-3\">\n      <label class=\"form-control w-48\">\n        <span class=\"label-text text-sm\">Date Range</span>\n        <input type=\"date\" class=\"input input-bordered input-sm\" data-filter=\"start_date\" />\n      </label>\n      <label class=\"form-control w-48\">\n        <span class=\"label-text text-sm\">To</span>\n        <input type=\"date\" class=\"input input-bordered input-sm\" data-filter=\"end_date\" />\n      </label>\n      <label class=\"form-control w-40\">\n        <span class=\"label-text text-sm\">Branch</span>\n        <select class=\"select select-bordered select-sm\" data-filter=\"branch_id\">\n          <option value=\"\">All Branches</option>\n        </select>\n      </label>\n    </div>\n    <button class=\"btn btn-sm btn-primary\" onclick=\"refreshStaffPerformance()\">Refresh</button>\n  </div>\n  <div class=\"hidden text-sm text-error\" data-role=\"error-container\"></div>\n  <div class=\"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-4\" data-role=\"metric-cards\"></div>\n  <div class=\"grid grid-cols-1 lg:grid-cols-2 gap-6\">\n    <div class=\"card bg-base-100 shadow-md shadow-slate-400/50\">\n      <div class=\"card-body\">\n        <h3 class=\"card-title\">Top Performers by Sales</h3>\n        <div class=\"h-80\">\n          <canvas data-role=\"top-staff-chart\"></canvas>\n        </div>\n      </div>\n    </div>\n    <div class=\"card bg-base-100 shadow-md shadow-slate-400/50\">\n      <div class=\"card-body\">\n        <h3 class=\"card-title\">Sales vs Transactions</h3>\n        <div class=\"h-80\">\n          <canvas data-role=\"efficiency-chart\"></canvas>\n        </div>\n      </div>\n    </div>\n  </div>\n  <div class=\"card bg-base-100 shadow-md shadow-slate-400/50\">\n    <div class=\"card-body\">\n      <h3 class=\"card-title\">Staff Performance Table</h3>\n      <div class=\"overflow-x-auto\">\n        <table class=\"table table-sm\" data-role=\"staff-table\">\n          <thead>\n            <tr><th>Cashier</th><th>Total Sales</th><th>Transactions</th><th>Avg Transaction</th><th>Items/Transaction</th><th>Efficiency Score</th></tr>\n          </thead>\n          <tbody></tbody>\n        </table>\n      </div>\n    </div>\n  </div>\n</div>"}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}'::jsonb,
    NULL,
    NULL,
    'fa-user-tie',
    'Staff Performance Analytics',
    'Staff Performance Analytics'
  )
ON CONFLICT (module_id) DO UPDATE SET
    config = EXCLUDED.config,
    icon = EXCLUDED.icon,
    aria_label = EXCLUDED.aria_label,
    description = EXCLUDED.description;

-- ============================================================================
-- Module 6: Branch Performance Dashboard
-- Queries: Branch Sales Comparison
-- Uses: AggregateRowsController GROUP BY branch_id
-- ============================================================================
INSERT INTO modules (module_id, name, config, org_id, branch_id, icon, aria_label, description) VALUES
  (
    '019a17e0-d2fa-71fa-b181-1b8f63938f8c'::uuid,
    'branch_performance_dashboard',
    '{"title":"Branch Performance Dashboard","body":[{"type":"html","html":"<div data-controller=\"BranchPerformanceDashboard\" class=\"space-y-6\">\n  <div class=\"flex flex-wrap items-center justify-between gap-3\">\n    <div class=\"flex flex-wrap gap-3\">\n      <label class=\"form-control w-48\">\n        <span class=\"label-text text-sm\">Date Range</span>\n        <input type=\"date\" class=\"input input-bordered input-sm\" data-filter=\"start_date\" />\n      </label>\n      <label class=\"form-control w-48\">\n        <span class=\"label-text text-sm\">To</span>\n        <input type=\"date\" class=\"input input-bordered input-sm\" data-filter=\"end_date\" />\n      </label>\n    </div>\n    <button class=\"btn btn-sm btn-primary\" onclick=\"refreshBranchPerformance()\">Refresh</button>\n  </div>\n  <div class=\"hidden text-sm text-error\" data-role=\"error-container\"></div>\n  <div class=\"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-4\" data-role=\"metric-cards\"></div>\n  <div class=\"grid grid-cols-1 lg:grid-cols-2 gap-6\">\n    <div class=\"card bg-base-100 shadow-md shadow-slate-400/50\">\n      <div class=\"card-body\">\n        <h3 class=\"card-title\">Branch Sales Comparison</h3>\n        <div class=\"h-80\">\n          <canvas data-role=\"branch-comparison-chart\"></canvas>\n        </div>\n      </div>\n    </div>\n    <div class=\"card bg-base-100 shadow-md shadow-slate-400/50\">\n      <div class=\"card-body\">\n        <h3 class=\"card-title\">Branch Performance Trend</h3>\n        <div class=\"h-80\">\n          <canvas data-role=\"branch-trend-chart\"></canvas>\n        </div>\n      </div>\n    </div>\n  </div>\n  <div class=\"card bg-base-100 shadow-md shadow-slate-400/50\">\n    <div class=\"card-body\">\n      <h3 class=\"card-title\">Branch Performance Table</h3>\n      <div class=\"overflow-x-auto\">\n        <table class=\"table table-sm\" data-role=\"branch-table\">\n          <thead>\n            <tr><th>Branch</th><th>Total Sales</th><th>Transactions</th><th>Avg Transaction</th><th>Top Product</th><th>Growth %</th></tr>\n          </thead>\n          <tbody></tbody>\n        </table>\n      </div>\n    </div>\n  </div>\n</div>"}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}'::jsonb,
    NULL,
    NULL,
    'fa-store',
    'Branch Performance Dashboard',
    'Branch Performance Dashboard'
  )
ON CONFLICT (module_id) DO UPDATE SET
    config = EXCLUDED.config,
    icon = EXCLUDED.icon,
    aria_label = EXCLUDED.aria_label,
    description = EXCLUDED.description;

-- ============================================================================
-- Module 7: Sales Time-Series Analytics
-- Queries: Daily Sales Summary, Hourly Sales Pattern
-- Uses: AggregateRowsController with date grouping
-- ============================================================================
INSERT INTO modules (module_id, name, config, org_id, branch_id, icon, aria_label, description) VALUES
  (
    '019a17e0-d2fa-7b4b-80ea-e5a1c19a1547'::uuid,
    'sales_timeseries_analytics',
    '{"title":"Sales Time-Series Analytics","body":[{"type":"html","html":"<div data-controller=\"SalesTimeseriesAnalytics\" class=\"space-y-6\">\n  <div class=\"flex flex-wrap items-center justify-between gap-3\">\n    <div class=\"flex flex-wrap gap-3\">\n      <label class=\"form-control w-48\">\n        <span class=\"label-text text-sm\">Date Range</span>\n        <input type=\"date\" class=\"input input-bordered input-sm\" data-filter=\"start_date\" />\n      </label>\n      <label class=\"form-control w-48\">\n        <span class=\"label-text text-sm\">To</span>\n        <input type=\"date\" class=\"input input-bordered input-sm\" data-filter=\"end_date\" />\n      </label>\n      <label class=\"form-control w-32\">\n        <span class=\"label-text text-sm\">Group By</span>\n        <select class=\"select select-bordered select-sm\" data-filter=\"group_by\">\n          <option value=\"day\">Daily</option>\n          <option value=\"week\">Weekly</option>\n          <option value=\"month\">Monthly</option>\n        </select>\n      </label>\n    </div>\n    <button class=\"btn btn-sm btn-primary\" onclick=\"refreshSalesTimeseries()\">Refresh</button>\n  </div>\n  <div class=\"hidden text-sm text-error\" data-role=\"error-container\"></div>\n  <div class=\"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-4\" data-role=\"metric-cards\"></div>\n  <div class=\"card bg-base-100 shadow-md shadow-slate-400/50\">\n    <div class=\"card-body\">\n      <h3 class=\"card-title\">Sales Trend Over Time</h3>\n      <div class=\"h-80\">\n        <canvas data-role=\"trend-chart\"></canvas>\n      </div>\n    </div>\n  </div>\n  <div class=\"grid grid-cols-1 lg:grid-cols-2 gap-6\">\n    <div class=\"card bg-base-100 shadow-md shadow-slate-400/50\">\n      <div class=\"card-body\">\n        <h3 class=\"card-title\">Hourly Sales Pattern</h3>\n        <div class=\"h-64\">\n          <canvas data-role=\"hourly-chart\"></canvas>\n        </div>\n      </div>\n    </div>\n    <div class=\"card bg-base-100 shadow-md shadow-slate-400/50\">\n      <div class=\"card-body\">\n        <h3 class=\"card-title\">Day of Week Pattern</h3>\n        <div class=\"h-64\">\n          <canvas data-role=\"dow-chart\"></canvas>\n        </div>\n      </div>\n    </div>\n  </div>\n</div>"}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}'::jsonb,
    NULL,
    NULL,
    'fa-chart-line',
    'Sales Time-Series Analytics',
    'Sales Time-Series Analytics'
  )
ON CONFLICT (module_id) DO UPDATE SET
    config = EXCLUDED.config,
    icon = EXCLUDED.icon,
    aria_label = EXCLUDED.aria_label,
    description = EXCLUDED.description;

-- ============================================================================
-- Module 8: Profit & Margin Analytics
-- Queries: Product Profitability, Discount Impact
-- Uses: GenericController with profit_margin column
-- ============================================================================
INSERT INTO modules (module_id, name, config, org_id, branch_id, icon, aria_label, description) VALUES
  (
    '019a17e0-d2fa-784e-9c46-c11673302dad'::uuid,
    'profit_margin_analytics',
    '{"title":"Profit & Margin Analytics","body":[{"type":"html","html":"<div data-controller=\"ProfitMarginAnalytics\" class=\"space-y-6\">\n  <div class=\"flex flex-wrap items-center justify-between gap-3\">\n    <div class=\"flex flex-wrap gap-3\">\n      <label class=\"form-control w-48\">\n        <span class=\"label-text text-sm\">Date Range</span>\n        <input type=\"date\" class=\"input input-bordered input-sm\" data-filter=\"start_date\" />\n      </label>\n      <label class=\"form-control w-48\">\n        <span class=\"label-text text-sm\">To</span>\n        <input type=\"date\" class=\"input input-bordered input-sm\" data-filter=\"end_date\" />\n      </label>\n    </div>\n    <button class=\"btn btn-sm btn-primary\" onclick=\"refreshProfitMargin()\">Refresh</button>\n  </div>\n  <div class=\"hidden text-sm text-error\" data-role=\"error-container\"></div>\n  <div class=\"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-4\" data-role=\"metric-cards\"></div>\n  <div class=\"grid grid-cols-1 lg:grid-cols-2 gap-6\">\n    <div class=\"card bg-base-100 shadow-md shadow-slate-400/50\">\n      <div class=\"card-body\">\n        <h3 class=\"card-title\">Top Products by Profit</h3>\n        <div class=\"h-80\">\n          <canvas data-role=\"top-profit-chart\"></canvas>\n        </div>\n      </div>\n    </div>\n    <div class=\"card bg-base-100 shadow-md shadow-slate-400/50\">\n      <div class=\"card-body\">\n        <h3 class=\"card-title\">Discount Impact Analysis</h3>\n        <div class=\"h-80\">\n          <canvas data-role=\"discount-chart\"></canvas>\n        </div>\n      </div>\n    </div>\n  </div>\n  <div class=\"card bg-base-100 shadow-md shadow-slate-400/50\">\n    <div class=\"card-body\">\n      <h3 class=\"card-title\">Product Profitability Table</h3>\n      <div class=\"overflow-x-auto\">\n        <table class=\"table table-sm\" data-role=\"profitability-table\">\n          <thead>\n            <tr><th>Product</th><th>Revenue</th><th>Cost</th><th>Gross Profit</th><th>Margin %</th><th>Discount Given</th><th>Discount %</th></tr>\n          </thead>\n          <tbody></tbody>\n        </table>\n      </div>\n    </div>\n  </div>\n</div>"}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}'::jsonb,
    NULL,
    NULL,
    'fa-chart-column',
    'Profit & Margin Analytics',
    'Profit & Margin Analytics'
  )
ON CONFLICT (module_id) DO UPDATE SET
    config = EXCLUDED.config,
    icon = EXCLUDED.icon,
    aria_label = EXCLUDED.aria_label,
    description = EXCLUDED.description;

-- ============================================================================
-- Module 9: Customer Segmentation (RFM) - Advanced
-- Note: This requires database view or custom endpoint for RFM calculation
-- ============================================================================
INSERT INTO modules (module_id, name, config, org_id, branch_id, icon, aria_label, description) VALUES
  (
    '019a17e0-d2fa-7683-9f53-e42fdc4ba7b5'::uuid,
    'customer_segmentation_rfm',
    '{"title":"Customer Segmentation (RFM)","body":[{"type":"html","html":"<div data-controller=\"CustomerSegmentationRfm\" class=\"space-y-6\">\n  <div class=\"flex flex-wrap items-center justify-between gap-3\">\n    <label class=\"form-control w-48\">\n      <span class=\"label-text text-sm\">Analysis Period (months)</span>\n      <input type=\"number\" class=\"input input-bordered input-sm\" data-filter=\"months\" value=\"12\" min=\"1\" max=\"36\" />\n    </label>\n    <button class=\"btn btn-sm btn-primary\" onclick=\"refreshCustomerRfm()\">Refresh</button>\n  </div>\n  <div class=\"hidden text-sm text-error\" data-role=\"error-container\"></div>\n  <div class=\"alert alert-info mb-4\">\n    <svg xmlns=\"http://www.w3.org/2000/svg\" fill=\"none\" viewBox=\"0 0 24 24\" class=\"stroke-current shrink-0 w-6 h-6\"><path stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"2\" d=\"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z\"></path></svg>\n    <span><strong>RFM Analysis:</strong> Recency (days since last purchase), Frequency (number of purchases), Monetary (total revenue)</span>\n  </div>\n  <div class=\"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-4\" data-role=\"metric-cards\"></div>\n  <div class=\"grid grid-cols-1 lg:grid-cols-2 gap-6\">\n    <div class=\"card bg-base-100 shadow-md shadow-slate-400/50\">\n      <div class=\"card-body\">\n        <h3 class=\"card-title\">Customer Segments</h3>\n        <div class=\"h-64\">\n          <canvas data-role=\"segment-chart\"></canvas>\n        </div>\n      </div>\n    </div>\n    <div class=\"card bg-base-100 shadow-md shadow-slate-400/50\">\n      <div class=\"card-body\">\n        <h3 class=\"card-title\">RFM Score Distribution</h3>\n        <div class=\"h-64\">\n          <canvas data-role=\"rfm-distribution-chart\"></canvas>\n        </div>\n      </div>\n    </div>\n  </div>\n  <div class=\"card bg-base-100 shadow-md shadow-slate-400/50\">\n    <div class=\"card-body\">\n      <h3 class=\"card-title\">Customer Segmentation Table</h3>\n      <div class=\"overflow-x-auto\">\n        <table class=\"table table-sm\" data-role=\"rfm-table\">\n          <thead>\n            <tr><th>Customer</th><th>Segment</th><th>Recency (days)</th><th>Frequency</th><th>Monetary</th><th>RFM Score</th><th>Action</th></tr>\n          </thead>\n          <tbody></tbody>\n        </table>\n      </div>\n    </div>\n  </div>\n</div>"}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}'::jsonb,
    NULL,
    NULL,
    'fa-diagram-project',
    'Customer Segmentation (RFM)',
    'Customer Segmentation (RFM)'
  )
ON CONFLICT (module_id) DO UPDATE SET
    config = EXCLUDED.config,
    icon = EXCLUDED.icon,
    aria_label = EXCLUDED.aria_label,
    description = EXCLUDED.description;

-- ============================================================================
-- Module 10: Transaction Export Dashboard
-- Queries: Full transaction export
-- Uses: GenericController with large dataset handling
-- ============================================================================
INSERT INTO modules (module_id, name, config, org_id, branch_id, icon, aria_label, description) VALUES
  (
    '019a17e0-d2fa-7646-86e4-54a8fd912321'::uuid,
    'transaction_export_dashboard',
    '{"title":"Transaction Export Dashboard","body":[{"type":"html","html":"<div data-controller=\"TransactionExportDashboard\" class=\"space-y-6\">\n  <div class=\"flex flex-wrap items-center justify-between gap-3\">\n    <div class=\"flex flex-wrap gap-3\">\n      <label class=\"form-control w-48\">\n        <span class=\"label-text text-sm\">Date Range</span>\n        <input type=\"date\" class=\"input input-bordered input-sm\" data-filter=\"start_date\" />\n      </label>\n      <label class=\"form-control w-48\">\n        <span class=\"label-text text-sm\">To</span>\n        <input type=\"date\" class=\"input input-bordered input-sm\" data-filter=\"end_date\" />\n      </label>\n      <label class=\"form-control w-32\">\n        <span class=\"label-text text-sm\">Format</span>\n        <select class=\"select select-bordered select-sm\" data-filter=\"format\">\n          <option value=\"csv\">CSV</option>\n          <option value=\"excel\">Excel</option>\n          <option value=\"json\">JSON</option>\n        </select>\n      </label>\n    </div>\n    <div class=\"flex gap-2\">\n      <button class=\"btn btn-sm btn-outline\" onclick=\"previewTransactionExport()\">Preview</button>\n      <button class=\"btn btn-sm btn-primary\" onclick=\"downloadTransactionExport()\">Export</button>\n    </div>\n  </div>\n  <div class=\"hidden text-sm text-error\" data-role=\"error-container\"></div>\n  <div class=\"alert alert-warning\">\n    <svg xmlns=\"http://www.w3.org/2000/svg\" class=\"stroke-current shrink-0 h-6 w-6\" fill=\"none\" viewBox=\"0 0 24 24\"><path stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"2\" d=\"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z\" /></svg>\n    <span><strong>Note:</strong> Large exports may take several minutes. Export includes all transaction details, customer information, and product data.</span>\n  </div>\n  <div class=\"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-4\" data-role=\"metric-cards\"></div>\n  <div class=\"card bg-base-100 shadow-md shadow-slate-400/50\">\n    <div class=\"card-body\">\n      <h3 class=\"card-title\">Export Preview (First 100 rows)</h3>\n      <div class=\"overflow-x-auto\" style=\"max-height: 400px;\">\n        <table class=\"table table-xs table-pin-rows\" data-role=\"preview-table\">\n          <thead>\n            <tr><th>Date</th><th>Transaction #</th><th>Product</th><th>Customer</th><th>Qty</th><th>Price</th><th>Discount</th><th>VAT</th><th>Total</th><th>Payment</th><th>Cashier</th></tr>\n          </thead>\n          <tbody></tbody>\n        </table>\n      </div>\n    </div>\n  </div>\n</div>"}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}'::jsonb,
    NULL,
    NULL,
    'fa-file-export',
    'Transaction Export Dashboard',
    'Transaction Export Dashboard'
  )
ON CONFLICT (module_id) DO UPDATE SET
    config = EXCLUDED.config,
    icon = EXCLUDED.icon,
    aria_label = EXCLUDED.aria_label,
    description = EXCLUDED.description;

-- ============================================================================
-- Phase 8: End Module Registration
-- Next Step: Create FrontEnd/js/modules/Inventory/Analytics.js
-- ============================================================================

COMMENT ON TABLE modules IS 'Module registry - Phase 8 adds 10 inventory analytics dashboard modules';
-- ============================================================================
-- Phase 8: Additional Simple Inventory Reports
-- Purpose: 3 focused reports (Top 10 Best Sellers, Slow Moving, VAT Report)
-- ============================================================================

-- ============================================================================
-- Module 11: Top 10 Best Sellers Report
-- Query: Product Movement - Top 10 by quantity sold
-- Uses: AggregateRowsController GROUP BY product_id
-- ============================================================================
INSERT INTO modules (module_id, name, config, org_id, branch_id, icon, aria_label, description) VALUES
  (
    '019a17e0-d2fa-71d6-8d0e-0ac55529dd2f'::uuid,
    'top_10_best_sellers',
    '{"title":"Top 10 Best Sellers","body":[{"type":"html","html":"<div data-controller=\"Top10BestSellers\" class=\"space-y-6\">\n  <div class=\"flex flex-wrap items-center justify-between gap-3\">\n    <div class=\"flex flex-wrap gap-3\">\n      <label class=\"form-control w-48\">\n        <span class=\"label-text text-sm\">Start Date</span>\n        <input type=\"date\" class=\"input input-bordered input-sm\" data-filter=\"start-date\" />\n      </label>\n      <label class=\"form-control w-48\">\n        <span class=\"label-text text-sm\">End Date</span>\n        <input type=\"date\" class=\"input input-bordered input-sm\" data-filter=\"end-date\" />\n      </label>\n      <label class=\"form-control w-40\">\n        <span class=\"label-text text-sm\">Branch</span>\n        <select class=\"select select-bordered select-sm\" data-filter=\"branch\">\n          <option value=\"\">All Branches</option>\n        </select>\n      </label>\n    </div>\n    <button class=\"btn btn-sm btn-primary\" data-role=\"refresh-data\">Refresh</button>\n  </div>\n  <div class=\"hidden text-sm text-error\" data-role=\"error-container\"></div>\n  <div class=\"grid grid-cols-1 md:grid-cols-3 gap-4\" data-role=\"metric-cards\"></div>\n  <div class=\"card bg-base-100 shadow-md\">\n    <div class=\"card-body\">\n      <h3 class=\"card-title\">Top 10 Products by Sales Volume</h3>\n      <div class=\"h-96\">\n        <canvas data-role=\"top-products-chart\"></canvas>\n      </div>\n    </div>\n  </div>\n  <div class=\"card bg-base-100 shadow-md\">\n    <div class=\"card-body\">\n      <h3 class=\"card-title\">Best Sellers Table</h3>\n      <div class=\"overflow-x-auto\">\n        <table class=\"table table-sm table-zebra\">\n          <thead>\n            <tr>\n              <th>#</th>\n              <th>Product Name</th>\n              <th>Barcode</th>\n              <th>Category</th>\n              <th class=\"text-right\">Units Sold</th>\n              <th class=\"text-right\">Revenue</th>\n              <th class=\"text-right\">Transactions</th>\n              <th class=\"text-right\">Avg Price</th>\n            </tr>\n          </thead>\n          <tbody data-role=\"products-table-body\"></tbody>\n        </table>\n      </div>\n    </div>\n  </div>\n</div>"}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}'::jsonb,
    NULL,
    NULL,
    'fa-trophy',
    'Top 10 Best Sellers',
    'Top 10 best-selling products by volume'
  )
ON CONFLICT (module_id) DO UPDATE SET
    config = EXCLUDED.config,
    icon = EXCLUDED.icon,
    aria_label = EXCLUDED.aria_label,
    description = EXCLUDED.description;

-- ============================================================================
-- Module 12: Slow Moving Items Report
-- Query: Products with no/low sales in last 90 days
-- Uses: Custom query (requires JOIN with inventory)
-- ============================================================================
INSERT INTO modules (module_id, name, config, org_id, branch_id, icon, aria_label, description) VALUES
  (
    '019a17e0-d2fa-791e-a032-c0705df59671'::uuid,
    'slow_moving_items',
    '{"title":"Slow Moving Items","body":[{"type":"html","html":"<div data-controller=\"SlowMovingItems\" class=\"space-y-6\">\n  <div class=\"flex flex-wrap items-center justify-between gap-3\">\n    <div class=\"flex flex-wrap gap-3\">\n      <label class=\"form-control w-40\">\n        <span class=\"label-text text-sm\">Days Threshold</span>\n        <input type=\"number\" class=\"input input-bordered input-sm\" data-filter=\"days-threshold\" value=\"90\" min=\"30\" max=\"365\" />\n      </label>\n      <label class=\"form-control w-40\">\n        <span class=\"label-text text-sm\">Min Units Threshold</span>\n        <input type=\"number\" class=\"input input-bordered input-sm\" data-filter=\"min-units\" value=\"100\" min=\"1\" max=\"1000\" />\n      </label>\n      <label class=\"form-control w-40\">\n        <span class=\"label-text text-sm\">Branch</span>\n        <select class=\"select select-bordered select-sm\" data-filter=\"branch\">\n          <option value=\"\">All Branches</option>\n        </select>\n      </label>\n    </div>\n    <button class=\"btn btn-sm btn-primary\" data-role=\"refresh-data\">Refresh</button>\n  </div>\n  <div class=\"hidden text-sm text-error\" data-role=\"error-container\"></div>\n  <div class=\"alert alert-warning\">\n    <svg xmlns=\"http://www.w3.org/2000/svg\" class=\"stroke-current shrink-0 h-6 w-6\" fill=\"none\" viewBox=\"0 0 24 24\"><path stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"2\" d=\"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z\" /></svg>\n    <span>Products with low sales in the last <strong data-role=\"threshold-display\">90</strong> days. Products below <strong data-role=\"min-units-display\">100</strong> units require attention.</span>\n  </div>\n  <div class=\"grid grid-cols-1 md:grid-cols-3 gap-4\" data-role=\"metric-cards\"></div>\n  <div class=\"card bg-base-100 shadow-md\">\n    <div class=\"card-body\">\n      <h3 class=\"card-title\">Slow Moving Products</h3>\n      <div class=\"overflow-x-auto\">\n        <table class=\"table table-sm table-zebra\">\n          <thead>\n            <tr>\n              <th>Product Name</th>\n              <th>Barcode</th>\n              <th>Category</th>\n              <th class=\"text-right\">Last Sale Date</th>\n              <th class=\"text-right\">Days Since Sale</th>\n              <th class=\"text-right\">Units Sold</th>\n              <th class=\"text-right\">Value at Risk</th>\n            </tr>\n          </thead>\n          <tbody data-role=\"slow-items-table-body\"></tbody>\n        </table>\n      </div>\n    </div>\n  </div>\n</div>"}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}'::jsonb,
    NULL,
    NULL,
    'fa-turtle',
    'Slow Moving Items',
    'Products with low or no recent sales activity'
  )
ON CONFLICT (module_id) DO UPDATE SET
    config = EXCLUDED.config,
    icon = EXCLUDED.icon,
    aria_label = EXCLUDED.aria_label,
    description = EXCLUDED.description;

-- ============================================================================
-- Module 13: VAT Report (0% and 12.5%)
-- Query: Basic VAT Summary grouped by VAT code
-- Uses: AggregateRowsController GROUP BY vat_code
-- ============================================================================
INSERT INTO modules (module_id, name, config, org_id, branch_id, icon, aria_label, description) VALUES
  (
    '019a17e0-d2fa-714b-a09d-adc83def3745'::uuid,
    'vat_summary_report',
    '{"title":"VAT Summary Report","body":[{"type":"html","html":"<div data-controller=\"VatSummaryReport\" class=\"space-y-6\">\n  <div class=\"flex flex-wrap items-center justify-between gap-3\">\n    <div class=\"flex flex-wrap gap-3\">\n      <label class=\"form-control w-48\">\n        <span class=\"label-text text-sm\">Start Date</span>\n        <input type=\"date\" class=\"input input-bordered input-sm\" data-filter=\"start-date\" />\n      </label>\n      <label class=\"form-control w-48\">\n        <span class=\"label-text text-sm\">End Date</span>\n        <input type=\"date\" class=\"input input-bordered input-sm\" data-filter=\"end-date\" />\n      </label>\n      <label class=\"form-control w-40\">\n        <span class=\"label-text text-sm\">Branch</span>\n        <select class=\"select select-bordered select-sm\" data-filter=\"branch\">\n          <option value=\"\">All Branches</option>\n        </select>\n      </label>\n    </div>\n    <div class=\"flex gap-2\">\n      <button class=\"btn btn-sm btn-outline\" data-role=\"export-pdf\">Export PDF</button>\n      <button class=\"btn btn-sm btn-primary\" data-role=\"refresh-data\">Refresh</button>\n    </div>\n  </div>\n  <div class=\"hidden text-sm text-error\" data-role=\"error-container\"></div>\n  <div class=\"grid grid-cols-1 md:grid-cols-4 gap-4\" data-role=\"metric-cards\"></div>\n  <div class=\"card bg-base-100 shadow-md\">\n    <div class=\"card-body\">\n      <h3 class=\"card-title\">VAT Summary by Rate</h3>\n      <div class=\"overflow-x-auto\">\n        <table class=\"table table-sm\">\n          <thead>\n            <tr>\n              <th>VAT Code</th>\n              <th>VAT Rate</th>\n              <th class=\"text-right\">Transactions</th>\n              <th class=\"text-right\">Units Sold</th>\n              <th class=\"text-right\">Taxable Amount</th>\n              <th class=\"text-right\">VAT Amount</th>\n              <th class=\"text-right\">Total Revenue</th>\n            </tr>\n          </thead>\n          <tbody data-role=\"vat-table-body\"></tbody>\n          <tfoot>\n            <tr class=\"font-bold\">\n              <td colspan=\"2\">TOTAL</td>\n              <td class=\"text-right\" data-role=\"total-transactions\">0</td>\n              <td class=\"text-right\" data-role=\"total-units\">0</td>\n              <td class=\"text-right\" data-role=\"total-taxable\">$0.00</td>\n              <td class=\"text-right\" data-role=\"total-vat\">$0.00</td>\n              <td class=\"text-right\" data-role=\"total-revenue\">$0.00</td>\n            </tr>\n          </tfoot>\n        </table>\n      </div>\n    </div>\n  </div>\n  <div class=\"grid grid-cols-1 lg:grid-cols-2 gap-6\">\n    <div class=\"card bg-base-100 shadow-md\">\n      <div class=\"card-body\">\n        <h3 class=\"card-title\">VAT Distribution</h3>\n        <div class=\"h-64\">\n          <canvas data-role=\"vat-pie-chart\"></canvas>\n        </div>\n      </div>\n    </div>\n    <div class=\"card bg-base-100 shadow-md\">\n      <div class=\"card-body\">\n        <h3 class=\"card-title\">VAT Collection Breakdown</h3>\n        <div class=\"h-64\">\n          <canvas data-role=\"vat-bar-chart\"></canvas>\n        </div>\n      </div>\n    </div>\n  </div>\n  <div class=\"card bg-base-100 shadow-md\">\n    <div class=\"card-body\">\n      <h3 class=\"card-title\">VAT Summary Details</h3>\n      <div class=\"grid grid-cols-1 md:grid-cols-2 gap-4\">\n        <div>\n          <h4 class=\"font-semibold text-sm mb-2\">Zero-Rated (0%)</h4>\n          <ul class=\"text-sm space-y-1\">\n            <li>Transactions: <span class=\"font-mono\" data-role=\"zero-rated-count\">0</span></li>\n            <li>Taxable Amount: <span class=\"font-mono\" data-role=\"zero-rated-taxable\">$0.00</span></li>\n            <li>VAT Collected: <span class=\"font-mono\" data-role=\"zero-rated-vat\">$0.00</span></li>\n          </ul>\n        </div>\n        <div>\n          <h4 class=\"font-semibold text-sm mb-2\">Standard Rate (12.5%)</h4>\n          <ul class=\"text-sm space-y-1\">\n            <li>Transactions: <span class=\"font-mono\" data-role=\"standard-count\">0</span></li>\n            <li>Taxable Amount: <span class=\"font-mono\" data-role=\"standard-taxable\">$0.00</span></li>\n            <li>VAT Collected: <span class=\"font-mono\" data-role=\"standard-vat\">$0.00</span></li>\n          </ul>\n        </div>\n      </div>\n    </div>\n  </div>\n</div>"}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}'::jsonb,
    NULL,
    NULL,
    'fa-file-invoice-dollar',
    'VAT Summary Report',
    'Comprehensive VAT report showing 0% and 12.5% breakdown'
  )
ON CONFLICT (module_id) DO UPDATE SET
    config = EXCLUDED.config,
    icon = EXCLUDED.icon,
    aria_label = EXCLUDED.aria_label,
    description = EXCLUDED.description;

-- ============================================================================
-- Phase 8: End Additional Reports Registration
-- ============================================================================

COMMENT ON TABLE modules IS 'Module registry - Phase 8 now has 13 inventory analytics modules (10 comprehensive + 3 focused reports)';

-- ============================================================================
-- Employee Profile Module
-- ============================================================================

INSERT INTO modules (module_id, name, config, org_id, branch_id, icon, aria_label, description) VALUES (
  'e7741f61-a2c9-4b29-a741-ce90111ccfa5'::uuid,
  'employee_profile',
  '{
    "title": "Employee Profile",
    "modulePath": "modules/HR/EmployeeProfile",
    "header": [],
    "body": [
      {
        "type": "tabs",
        "tabs": [
          {
            "id": "salary",
            "label": "Salary",
            "icon": "fa-money-bill-wave",
            "content": {
              "type": "table",
              "options": {
                "tableName": "salaries",
                "columnLabels": {
                  "salary_type": "Type",
                  "rate": "Amount",
                  "currency": "Currency",
                  "effective_date": "Start Date",
                  "end_date": "End Date"
                },
                "showGlobalSearch": false,
                "filters": {}
              }
            }
          },
          {
            "id": "disciplinary",
            "label": "Disciplinary",
            "icon": "fa-gavel",
            "content": {
              "type": "html",
              "html": "<div class=\"alert alert-success\"><i class=\"fas fa-check-circle\"></i> No disciplinary records found. Employee has a clean record.</div>"
            }
          },
          {
            "id": "hours",
            "label": "Hours",
            "icon": "fa-clock",
            "content": {
              "type": "table",
              "options": {
                "tableName": "time_clocks",
                "columnLabels": {
                  "clock_type": "Type",
                  "clocked_at": "Time",
                  "location_name": "Location"
                },
                "showGlobalSearch": false,
                "filters": {}
              }
            }
          },
          {
            "id": "bonus",
            "label": "Bonus",
            "icon": "fa-gift",
            "content": {
              "type": "html",
              "html": "<div class=\"alert alert-info\"><i class=\"fas fa-gift\"></i> Bonus tracking feature - Shows how much bonus an employee should receive</div>"
            }
          },
          {
            "id": "leave",
            "label": "Leave",
            "icon": "fa-umbrella-beach",
            "content": {
              "type": "table",
              "options": {
                "tableName": "leave_requests",
                "columnLabels": {
                  "leavetype": "Type",
                  "startdate": "Start Date",
                  "enddate": "End Date",
                  "reason": "Reason",
                  "status": "Status"
                },
                "showGlobalSearch": false,
                "filters": {}
              }
            }
          }
        ]
      }
    ],
    "footer": [
      {
        "type": "button",
        "label": "Close",
        "onClick": "closeModal"
      }
    ]
  }'::jsonb,
  NULL,
  NULL,
  'fa-id-card',
  'Employee Profile',
  'View employee salary, hours, leave, bonus, and disciplinary records'
) ON CONFLICT (module_id) DO UPDATE SET
    config = EXCLUDED.config,
    icon = EXCLUDED.icon,
    aria_label = EXCLUDED.aria_label,
    description = EXCLUDED.description;


-- ============================================================================
-- AUTO-LAUNCH MODULES DEFAULT CONFIGURATIONS
-- ============================================================================
-- Description: Default auto-launch module configurations for common user groups
-- Date: November 10, 2025
-- ============================================================================

-- Insert sample auto-launch configurations
INSERT INTO auto_launch_modules (group_name, module_name, module_id, priority, enabled) VALUES
-- Cashiers automatically open POS
('cashiers', 'POS', '0194a8b2-0015-7123-8123-123456789abc'::uuid, 1, true),

-- Managers open System Settings
('managers', 'SystemSettings', '0194a8b2-0001-7123-8123-123456789abc'::uuid, 1, true),

-- Inventory staff open Inventory Management
('inventory_staff', 'InventoryManagement', '0194a8b2-0016-7123-8123-123456789abc'::uuid, 1, true),

-- Supervisors open Customer Management
('supervisors', 'Customer Management', '0194a8b2-0fff-7123-8123-123456789afe'::uuid, 1, true),

-- HR staff open Open Positions
('hr_staff', 'Open Positions', '6861955c-f882-44db-ab95-89c1a9b8e307'::uuid, 1, true)

ON CONFLICT (group_name, module_name) DO UPDATE SET
  module_id = EXCLUDED.module_id,
  priority = EXCLUDED.priority,
  enabled = EXCLUDED.enabled,
  updated_at = CURRENT_TIMESTAMP;

  -- ============================================================================
-- Biometric Devices Module Definition (Declarative)
-- Date: 2025-11-17
-- ============================================================================
-- This module provides management interface for biometric attendance devices.
-- Uses ActionRegistry, ModalBuilder, and DataLoader for declarative UI.
--
-- Features:
-- - Device registration and management
-- - Online/offline status monitoring
-- - Device approval/disable controls
-- - Connection logs and audit trail
-- - No custom JavaScript required!
-- ============================================================================

INSERT INTO modules (
    module_id,
    name,
    config,
    icon,
    aria_label,
    description
) VALUES (
    '019a8e0a-c0e5-7999-9d58-51fadd75895b'::uuid,
    'BiometricDevices',
    '{
        "title": "Biometric Devices",
        "modulePath": "biometric-devices",
        "dataSources": {
            "main": {
                "table": "biometric_devices",
                "orderBy": "createdAt DESC"
            },
            "logs": {
                "table": "biometric_device_logs",
                "orderBy": "createdAt DESC"
            },
            "branches": {
                "table": "branches",
                "displayField": "name",
                "valueField": "branch_id"
            }
        },
        "header": [
            {
                "type": "button",
                "label": "Register Device",
                "formId": 631
            },
            {
                "type": "filter-select",
                "options": {
                    "data_column": "device_type",
                    "label": "Device Type",
                    "options": [
                        {"label": "All Types", "value": ""},
                        {"label": "F500 (Fingerprint)", "value": "F500"},
                        {"label": "M50 (Face + Temp)", "value": "M50"},
                        {"label": "M91 (Multi-modal)", "value": "M91"}
                    ]
                }
            },
            {
                "type": "filter-select",
                "options": {
                    "data_column": "is_online",
                    "label": "Status",
                    "options": [
                        {"label": "All", "value": ""},
                        {"label": "Online", "value": "true"},
                        {"label": "Offline", "value": "false"}
                    ]
                }
            },
            {
                "type": "filter-select",
                "options": {
                    "data_column": "approved",
                    "label": "Approval",
                    "options": [
                        {"label": "All", "value": ""},
                        {"label": "Approved", "value": "true"},
                        {"label": "Disabled", "value": "false"}
                    ]
                }
            },
            {
                "type": "button",
                "label": "Refresh",
                "icon": "fa-sync",
                "class": "btn btn-ghost",
                "action": "refresh",
                "ariaLabel": "Refresh device list"
            }
        ],
        "body": [
            {
                "type": "table",
                "id": "biometricDevicesTable",
                "options": {
                    "tableName": "biometric_devices",
                    "primaryKeyField": "biometric_device_id",
                    "showGlobalSearch": true,
                    "columnsToShow": [
                        "device_sn",
                        "name",
                        "device_type",
                        "branch_id",
                        "is_online",
                        "last_seen",
                        "approved",
                        "createdAt"
                    ],
                    "columnLabels": {
                        "device_sn": "Serial Number",
                        "name": "Device Name",
                        "device_type": "Type",
                        "branch_id": "Branch",
                        "is_online": "Status",
                        "last_seen": "Last Seen",
                        "approved": "Approved",
                        "createdAt": "Registered"
                    },
                    "columnFormatters": {
                        "is_online": {
                            "type": "badge",
                            "true": {"label": "Online", "class": "badge-success"},
                            "false": {"label": "Offline", "class": "badge-error"}
                        },
                        "approved": {
                            "type": "badge",
                            "true": {"label": "Enabled", "class": "badge-success"},
                            "false": {"label": "Disabled", "class": "badge-warning"}
                        },
                        "branch_id": {
                            "type": "lookup",
                            "dataSource": "branches"
                        }
                    },
                    "rowClick": "selectRecord",
                    "rowActions": [
                        {
                            "label": "View Details",
                            "icon": "fa-eye",
                            "class": "btn btn-info btn-xs",
                            "action": "openSelectedDetail",
                            "ariaLabel": "View device details"
                        },
                        {
                            "label": "View Logs",
                            "icon": "fa-list",
                            "class": "btn btn-ghost btn-xs",
                            "action": "biometric:view-logs",
                            "ariaLabel": "View device connection logs"
                        },
                        {
                            "label": "Disable",
                            "icon": "fa-ban",
                            "class": "btn btn-warning btn-xs",
                            "action": "biometric:toggle-approval",
                            "condition": "approved == true",
                            "confirm": "Disable this device? It will not be able to connect.",
                            "ariaLabel": "Disable device"
                        },
                        {
                            "label": "Enable",
                            "icon": "fa-check",
                            "class": "btn btn-success btn-xs",
                            "action": "biometric:toggle-approval",
                            "condition": "approved == false",
                            "confirm": "Enable this device?",
                            "ariaLabel": "Enable device"
                        },
                        {
                            "label": "Delete",
                            "icon": "fa-trash",
                            "class": "btn btn-error btn-xs",
                            "action": "delete",
                            "confirm": "Delete this device? This cannot be undone.",
                            "ariaLabel": "Delete device"
                        }
                    ]
                }
            }
        ],
        "detailModal": {
            "title": "Device Details",
            "size": "large",
            "tabs": [
                {
                    "id": "info",
                    "label": "Device Information",
                    "icon": "fa-info-circle",
                    "sections": [
                        {
                            "title": "Basic Information",
                            "layout": "two-column",
                            "fields": [
                                {
                                    "name": "device_sn",
                                    "label": "Device Serial Number",
                                    "type": "text",
                                    "required": true,
                                    "placeholder": "Enter device serial number",
                                    "helpText": "Physical serial number from the device hardware"
                                },
                                {
                                    "name": "name",
                                    "label": "Device Name",
                                    "type": "text",
                                    "required": true,
                                    "placeholder": "e.g., Main Entrance Scanner"
                                },
                                {
                                    "name": "device_type",
                                    "label": "Device Model",
                                    "type": "select",
                                    "required": true,
                                    "options": [
                                        {"label": "F500 - Fingerprint Scanner", "value": "F500"},
                                        {"label": "M50 - Face Recognition + Temperature", "value": "M50"},
                                        {"label": "M91 - Multi-modal Biometric", "value": "M91"}
                                    ]
                                },
                                {
                                    "name": "branch_id",
                                    "label": "Branch Location",
                                    "type": "lookup",
                                    "required": true,
                                    "dataSource": "branches",
                                    "helpText": "Select the branch where this device is installed"
                                },
                                {
                                    "name": "cloud_id",
                                    "label": "Cloud ID",
                                    "type": "text",
                                    "placeholder": "Optional cloud service identifier"
                                },
                                {
                                    "name": "approved",
                                    "label": "Device Approved",
                                    "type": "checkbox",
                                    "default": true,
                                    "helpText": "Disabled devices cannot connect to the system"
                                }
                            ]
                        },
                        {
                            "title": "Description",
                            "layout": "single-column",
                            "fields": [
                                {
                                    "name": "description",
                                    "label": "Notes",
                                    "type": "textarea",
                                    "rows": 3,
                                    "placeholder": "Additional notes about this device..."
                                }
                            ]
                        }
                    ]
                },
                {
                    "id": "status",
                    "label": "Status & Activity",
                    "icon": "fa-chart-line",
                    "sections": [
                        {
                            "title": "Connection Status",
                            "layout": "two-column",
                            "fields": [
                                {
                                    "name": "is_online",
                                    "label": "Current Status",
                                    "type": "badge",
                                    "readonly": true,
                                    "formatter": {
                                        "type": "badge",
                                        "true": {"label": "Online", "class": "badge-success"},
                                        "false": {"label": "Offline", "class": "badge-error"}
                                    }
                                },
                                {
                                    "name": "last_seen",
                                    "label": "Last Seen",
                                    "type": "datetime",
                                    "readonly": true
                                },
                                {
                                    "name": "websocket_session",
                                    "label": "Session ID",
                                    "type": "text",
                                    "readonly": true,
                                    "helpText": "WebSocket connection identifier"
                                },
                                {
                                    "name": "createdAt",
                                    "label": "Registered On",
                                    "type": "datetime",
                                    "readonly": true
                                }
                            ]
                        },
                        {
                            "title": "Recent Activity Logs",
                            "component": "data-grid",
                            "dataSource": "logs",
                            "filters": {
                                "biometric_device_id": "{biometric_device_id}"
                            },
                            "limit": 10,
                            "columns": [
                                {
                                    "field": "event_type",
                                    "label": "Event",
                                    "width": "150px"
                                },
                                {
                                    "field": "createdAt",
                                    "label": "Time",
                                    "width": "180px",
                                    "formatter": "datetime"
                                },
                                {
                                    "field": "details",
                                    "label": "Details",
                                    "formatter": "json"
                                }
                            ]
                        }
                    ]
                },
                {
                    "id": "settings",
                    "label": "Device Settings",
                    "icon": "fa-cog",
                    "sections": [
                        {
                            "title": "Configuration",
                            "layout": "single-column",
                            "fields": [
                                {
                                    "name": "settings",
                                    "label": "Device Settings (JSON)",
                                    "type": "json-editor",
                                    "helpText": "Advanced device configuration in JSON format",
                                    "placeholder": "{}"
                                }
                            ]
                        }
                    ]
                }
            ],
            "actions": [
                {
                    "label": "Save",
                    "icon": "fa-save",
                    "class": "btn btn-primary",
                    "action": "save",
                    "closeOnSuccess": true
                },
                {
                    "label": "Cancel",
                    "class": "btn btn-ghost",
                    "action": "close"
                }
            ]
        },
        "footer": [
            {
                "type": "button",
                "label": "Close",
                "onClick": "closeModal"
            }
        ]
    }'::jsonb,
    'fa-fingerprint',
    'Biometric Devices',
    'Manage biometric attendance devices and monitor connection status'
);

-- ============================================================================
-- Biometric Device Logs Module Definition
-- ============================================================================
-- Dedicated module for viewing detailed device logs and audit trail
-- ============================================================================

INSERT INTO modules (
    module_id,
    name,
    config,
    icon,
    aria_label,
    description
) VALUES (
    '019a8e0a-c0f1-7690-a532-1d8575ae6252'::uuid,
    'BiometricDeviceLogs',
    '{
        "title": "Device Activity Logs",
        "modulePath": "biometric-device-logs",
        "dataSources": {
            "main": {
                "table": "biometric_device_logs",
                "orderBy": "createdAt DESC"
            },
            "devices": {
                "table": "biometric_devices",
                "displayField": "name",
                "valueField": "biometric_device_id"
            }
        },
        "header": [
            {
                "type": "filter-select",
                "options": {
                    "data_column": "biometric_device_id",
                    "label": "Device",
                    "dataSource": "devices",
                    "includeAll": true
                }
            },
            {
                "type": "filter-select",
                "options": {
                    "data_column": "event_type",
                    "label": "Event Type",
                    "options": [
                        {"label": "All Events", "value": ""},
                        {"label": "Login Success", "value": "login_success"},
                        {"label": "Login Rejected", "value": "login_rejected"},
                        {"label": "Register Rejected", "value": "register_rejected"},
                        {"label": "Device Created", "value": "device_created"},
                        {"label": "Device Updated", "value": "device_updated"},
                        {"label": "Device Deleted", "value": "device_deleted"},
                        {"label": "Attendance Recorded", "value": "attendance_recorded"},
                        {"label": "Attendance Rejected", "value": "attendance_rejected"}
                    ]
                }
            },
            {
                "type": "filter-date-range",
                "options": {
                    "data_column": "createdAt",
                    "label": "Date Range"
                }
            },
            {
                "type": "button",
                "label": "Refresh",
                "icon": "fa-sync",
                "class": "btn btn-ghost",
                "action": "refresh"
            }
        ],
        "body": [
            {
                "type": "table",
                "id": "deviceLogsTable",
                "options": {
                    "tableName": "biometric_device_logs",
                    "primaryKeyField": "biometric_device_log_id",
                    "showGlobalSearch": true,
                    "columnsToShow": [
                        "biometric_device_id",
                        "device_sn",
                        "event_type",
                        "createdAt",
                        "details"
                    ],
                    "columnLabels": {
                        "biometric_device_id": "Device",
                        "device_sn": "Serial Number",
                        "event_type": "Event Type",
                        "createdAt": "Timestamp",
                        "details": "Details"
                    },
                    "columnFormatters": {
                        "biometric_device_id": {
                            "type": "lookup",
                            "dataSource": "devices"
                        },
                        "details": {
                            "type": "json-preview"
                        },
                        "event_type": {
                            "type": "badge",
                            "mappings": {
                                "login_success": {"class": "badge-success"},
                                "login_rejected": {"class": "badge-error"},
                                "register_rejected": {"class": "badge-warning"},
                                "attendance_recorded": {"class": "badge-info"}
                            }
                        }
                    },
                    "rowClick": "selectRecord"
                }
            }
        ]
    }'::jsonb,
    'fa-list-check',
    'Device Activity Logs',
    'View biometric device connection logs and audit trail'
);
INSERT INTO modules (module_id, name, config, org_id, branch_id, icon, aria_label, description)
SELECT
  '0194a8b2-0032-7123-8123-123456789abc'::uuid,
  'Vendor Quote Detail',
  $json$
  {
    "title": "Vendor Quote Detail",
    "body": [
      { "type":"tabs","tabs":[
        { "label":"Summary","elements":[
          { "type":"detail-view", "tableName":"vendor_quotes", "filterField":"quote_id" },
          { "type":"html", "html":"<div class='divider my-2'>Line Items</div>" },
          { "type":"table", "options": { "tableName":"vendor_quote_items", "filterField":"quote_id", "columnsToShow":["item_description","is_alternate","alt_label","unit_price","tax","lead_time_days","notes"], "addButton": false } }
        ]},
        { "label":"Attachments","elements":[
          { "type":"html", "html":"<div id='quote-attachments'><div data-role='attachments-list' class='space-y-1'></div></div>" }
        ]}
      ]}
    ],
    "footer":[{"type":"button","label":"Close","onClick":"closeModal"}]
  }
  $json$::jsonb,
  NULL, NULL, 'fa-file-circle-check', 'Vendor Quote Detail', 'View-only summary of a vendor quote'
WHERE NOT EXISTS (
  SELECT 1 FROM modules WHERE module_id = '0194a8b2-0032-7123-8123-123456789abc'::uuid OR name = 'Vendor Quote Detail'
);