
-- 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","columnLabels":{"leavetype":"Type","startdate":"Start Date","enddate":"End Date","reason":"Reason","status":"Status"},"showGlobalSearch":true,"rowActions":[{"label":"Apply","onClick":"leaveManagementApply"},{"label":"Approve","onClick":"leaveManagementApprove"}]}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}'::jsonb,
  NULL,
  NULL,
  'fa-calendar-check',
  'Leave Management',
  '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',
  $json$ {
    "title": "Time Clocks",
    "header": [
      {
        "type": "filter-select",
        "options": {
          "source_table": "users",
          "source_column": "user_id",
          "display_column": "full_name",
          "data_column": "name",
          "data_column_id": "user_id",
          "placeholder": "Search by employee name...",
          "search_fields": ["full_name"],
          "max_results": 25,
          "debounce_ms": 250,
          "populateMode": "immediate"
        }
      }
    ],
    "body": [
      {
        "type": "table",
        "options": {
          "tableName": "time_clocks",
          "showGlobalSearch": false,
          "addButton": false,
          "filterField": "name",
          "listenColumn": "name",
          "columnsToShow": ["name", "clock_type", "clocked_at"]
        }
      }
    ],
    "footer": [
      { "type": "button", "label": "Close", "onClick": "closeModal" }
    ]
  } $json$::jsonb,
  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'
);

-- 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": "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": "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',
    $json$ {
      "title": "Employee Management",
      "header": [
        {
          "type": "filter-select",
          "options": {
            "source_table": "users",
            "source_column": "user_id",
            "display_column": "full_name",
            "data_column": "full_name",
            "data_column_id": "selected_user_id",
            "placeholder": "Search employees by name...",
            "search_fields": ["full_name"],
            "max_results": 25,
            "debounce_ms": 250,
            "populateMode": "immediate"
          }
        },
        { "type": "button", "label": "Add Employee", "formName": "Employee Account" }
      ],
      "body": [
        {
          "type": "table",
          "options": {
            "tableName": "users",
            "showGlobalSearch": false,
            "addButton": false,
            "filterField": "full_name",
            "listenColumn": "full_name",
            "columnsToShow": ["full_name", "status", "emails", "phones"],
            "arrayFieldViews": {
              "emails": ["email"],
              "phones": ["phone_number"]
            },
            "columnLabels": {
              "emails": "Emails",
              "phones": "Phones"
            }
          }
        }
      ],
      "footer": [
        { "type": "button", "label": "Close", "onClick": "closeModal" }
      ]
    } $json$::jsonb,
    NULL,
    NULL,
    'fa-users',
    'Employees',
    'Manage employees, rates, and types'
  )
ON CONFLICT (module_id) DO UPDATE
  SET name = EXCLUDED.name,
      config = EXCLUDED.config,
      icon = EXCLUDED.icon,
      aria_label = EXCLUDED.aria_label,
      description = EXCLUDED.description;

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 (name, config, org_id, branch_id, icon, aria_label, description) VALUES (
'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'
);



-- 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 (name, config, org_id, branch_id, icon, aria_label, description)
VALUES (
  'Products',
  '{"title":"Products","header":[
    {"type":"button",
      "label":"Add Product",
      "formName":"Product"},
    {"type":"button",
      "label":"Auto Orders",
      "formName":"Auto Order"},
    {"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":false,
  "addButton":false,
  "editFormId":111,
  "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,
  "columnsToShow":[
  "product_name","minimum_stock_qty","order_qty"]
            }
          }
        ]
      }
      ,
      {"label":"Discount",
        "elements":[
          {"type":"table",
            "options":{
              "tableName":"discount_rules",
              "showGlobalSearch":false,
              "addButton":false,
              "editFormId":150,
              "columns":[
             {"field":"name","label":"Name"},
             {"field":"discount_type","label":"Discount Type"},
             {"field":"product_id","label":"Product"},
             {"field":"category_id","label":"Category"},
             {"field":"percentage_value","label":"% Value"},
             {"field":"amount_value","label":"Amount Value"},
             {"field":"buy_quantity","label":"Buy Qty"},
             {"field":"free_quantity","label":"Free Qty"},
             {"field":"bundle_quantity","label":"Bundle Qty"},
             {"field":"bundle_price","label":"Bundle Price"},
             {"field":"threshold_quantity","label":"Threshold Qty"},
             {"field":"start_date","label":"Start Date"},
             {"field":"end_date","label":"End Date"},
             {"field":"notes","label":"Notes"}
              ]
            }
          }
        ]
      }
    ]
  }
  ],
  
  "footer":[
  {"type":"button","label":"Close","onClick":"closeModal"}
    ]
  }',

  
  NULL,
  NULL,
  'fa-box',
  'Products',
  '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","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","body":[{"type":"html","html":"Inventory management content"}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}],"legacy":true}', NULL, NULL, 'fa-boxes', 'Inventory Management', 'Inventory 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';
