beepzone-schema-consolidated-backup.sql 84 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882
  1. -- BeepZone Database Schema v0.0.8 (Consolidated)
  2. -- MariaDB/MySQL Compatible
  3. -- Created: 2025-12-13
  4. -- Includes: Complete schema with triggers, asset change logging, printing, templates, zones
  5. --
  6. -- AUTO-POPULATION TRIGGERS:
  7. -- The following fields are auto-populated from @current_user_id if not provided:
  8. -- • assets.created_by (on INSERT)
  9. -- • assets.last_modified_by (on UPDATE)
  10. -- • borrowers.added_by (on INSERT)
  11. -- • borrowers.last_unban_by (on UPDATE when unbanning)
  12. -- • lending_history.checked_out_by (on INSERT)
  13. -- • lending_history.checked_in_by (on UPDATE when returning)
  14. -- • issue_tracker.reported_by (on INSERT)
  15. -- • physical_audit_logs.audited_by (on INSERT)
  16. -- Your API proxy should set @current_user_id before executing queries.
  17. -- Drop tables if they exist (in reverse order of dependencies)
  18. DROP TABLE IF EXISTS print_history;
  19. DROP TABLE IF EXISTS issue_tracker_change_log;
  20. DROP TABLE IF EXISTS asset_change_log;
  21. DROP TABLE IF EXISTS issue_tracker;
  22. DROP TABLE IF EXISTS physical_audit_logs;
  23. DROP TABLE IF EXISTS physical_audits;
  24. DROP TABLE IF EXISTS lending_history;
  25. DROP TABLE IF EXISTS templates;
  26. DROP TABLE IF EXISTS assets;
  27. DROP TABLE IF EXISTS borrowers;
  28. DROP TABLE IF EXISTS audit_tasks;
  29. DROP TABLE IF EXISTS suppliers;
  30. DROP TABLE IF EXISTS zones;
  31. DROP TABLE IF EXISTS categories;
  32. DROP TABLE IF EXISTS label_templates;
  33. DROP TABLE IF EXISTS printer_settings;
  34. DROP TABLE IF EXISTS users;
  35. DROP TABLE IF EXISTS roles;
  36. -- ============================================
  37. -- Roles Table
  38. -- ============================================
  39. CREATE TABLE roles (
  40. id INT AUTO_INCREMENT PRIMARY KEY,
  41. name VARCHAR(100) NOT NULL UNIQUE,
  42. power INT NOT NULL CHECK (power >= 1 AND power <= 100),
  43. created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
  44. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_uca1400_ai_ci;
  45. -- ============================================
  46. -- Users Table
  47. -- ============================================
  48. CREATE TABLE users (
  49. id INT AUTO_INCREMENT PRIMARY KEY,
  50. name VARCHAR(200) NOT NULL,
  51. username VARCHAR(100) NOT NULL UNIQUE,
  52. password VARCHAR(255) NOT NULL,
  53. pin_code VARCHAR(8) NULL,
  54. login_string VARCHAR(255) NULL,
  55. role_id INT NOT NULL,
  56. email VARCHAR(255) NULL,
  57. phone VARCHAR(50) NULL,
  58. notes TEXT NULL,
  59. active BOOLEAN DEFAULT TRUE,
  60. last_login_date DATETIME NULL,
  61. created_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  62. password_reset_token VARCHAR(255) NULL,
  63. password_reset_expiry DATETIME NULL,
  64. FOREIGN KEY (role_id) REFERENCES roles(id) ON DELETE RESTRICT,
  65. INDEX idx_username (username),
  66. INDEX idx_login_string (login_string)
  67. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_uca1400_ai_ci;
  68. -- ============================================
  69. -- Categories Table
  70. -- ============================================
  71. CREATE TABLE categories (
  72. id INT AUTO_INCREMENT PRIMARY KEY,
  73. category_name VARCHAR(200) NOT NULL,
  74. category_description TEXT NULL,
  75. parent_id INT NULL,
  76. category_code VARCHAR(50) NULL,
  77. FOREIGN KEY (parent_id) REFERENCES categories(id) ON DELETE RESTRICT,
  78. INDEX idx_parent (parent_id),
  79. INDEX idx_code (category_code)
  80. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_uca1400_ai_ci;
  81. -- ============================================
  82. -- Zones Table
  83. -- ============================================
  84. CREATE TABLE zones (
  85. id INT AUTO_INCREMENT PRIMARY KEY,
  86. zone_name VARCHAR(200) NOT NULL,
  87. zone_notes TEXT NULL,
  88. zone_type ENUM('Building', 'Floor', 'Room', 'Storage Area') NOT NULL,
  89. zone_code VARCHAR(50) NOT NULL COMMENT 'Full hierarchical code (e.g., PS52-1-108)',
  90. mini_code VARCHAR(50) NOT NULL COMMENT 'Local short code for this node (e.g., PS52, 1, 108)',
  91. parent_id INT NULL,
  92. include_in_parent BOOLEAN DEFAULT TRUE,
  93. audit_timeout_minutes INT DEFAULT 60 COMMENT 'Audit timeout in minutes for this zone',
  94. FOREIGN KEY (parent_id) REFERENCES zones(id) ON DELETE RESTRICT,
  95. INDEX idx_parent (parent_id),
  96. INDEX idx_type (zone_type),
  97. UNIQUE INDEX uq_zone_code (zone_code),
  98. INDEX idx_parent_type_mini (parent_id, zone_type, mini_code)
  99. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_uca1400_ai_ci;
  100. -- ============================================
  101. -- Suppliers Table
  102. -- ============================================
  103. CREATE TABLE suppliers (
  104. id INT AUTO_INCREMENT PRIMARY KEY,
  105. name VARCHAR(200) NOT NULL,
  106. contact VARCHAR(200) NULL,
  107. email VARCHAR(255) NULL,
  108. phone VARCHAR(50) NULL,
  109. website VARCHAR(255) NULL,
  110. notes TEXT NULL,
  111. created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
  112. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_uca1400_ai_ci;
  113. -- ============================================
  114. -- Audit Tasks Table
  115. -- ============================================
  116. CREATE TABLE audit_tasks (
  117. id INT AUTO_INCREMENT PRIMARY KEY,
  118. task_name VARCHAR(200) NOT NULL,
  119. json_sequence JSON NOT NULL,
  120. created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  121. updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
  122. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_uca1400_ai_ci;
  123. -- ============================================
  124. -- Borrowers Table
  125. -- ============================================
  126. CREATE TABLE borrowers (
  127. id INT AUTO_INCREMENT PRIMARY KEY,
  128. name VARCHAR(200) NOT NULL,
  129. email VARCHAR(255) NULL,
  130. phone_number VARCHAR(50) NULL,
  131. class_name VARCHAR(100) NULL,
  132. role VARCHAR(100) NULL,
  133. notes TEXT NULL,
  134. added_by INT NOT NULL,
  135. added_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  136. banned BOOLEAN DEFAULT FALSE,
  137. unban_fine DECIMAL(10, 2) DEFAULT 0.00,
  138. last_unban_by INT NULL,
  139. last_unban_date DATE NULL,
  140. FOREIGN KEY (added_by) REFERENCES users(id) ON DELETE RESTRICT,
  141. FOREIGN KEY (last_unban_by) REFERENCES users(id) ON DELETE SET NULL,
  142. INDEX idx_name (name),
  143. INDEX idx_banned (banned)
  144. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_uca1400_ai_ci;
  145. -- ============================================
  146. -- Assets Table (Sexy Edition v2)
  147. -- ============================================
  148. CREATE TABLE assets (
  149. id INT AUTO_INCREMENT PRIMARY KEY,
  150. asset_tag VARCHAR(200) NULL UNIQUE,
  151. asset_numeric_id INT NOT NULL UNIQUE CHECK (asset_numeric_id BETWEEN 10000000 AND 99999999),
  152. asset_type ENUM('N', 'B', 'L', 'C') NOT NULL,
  153. name VARCHAR(255) NULL,
  154. category_id INT NULL,
  155. manufacturer VARCHAR(200) NULL,
  156. model VARCHAR(200) NULL,
  157. serial_number VARCHAR(200) NULL,
  158. zone_id INT NULL,
  159. zone_plus ENUM('Floating Local', 'Floating Global', 'Clarify') NULL,
  160. zone_note TEXT NULL,
  161. status ENUM('Good', 'Attention', 'Faulty', 'Missing', 'Retired', 'In Repair', 'In Transit', 'Expired', 'Unmanaged') DEFAULT 'Good',
  162. last_audit DATE NULL,
  163. last_audit_status VARCHAR(100) NULL,
  164. price DECIMAL(12, 2) NULL CHECK (price IS NULL OR price >= 0),
  165. purchase_date DATE NULL,
  166. warranty_until DATE NULL,
  167. expiry_date DATE NULL,
  168. quantity_available INT NULL,
  169. quantity_total INT NULL,
  170. quantity_used INT DEFAULT 0,
  171. supplier_id INT NULL,
  172. lendable BOOLEAN DEFAULT FALSE,
  173. minimum_role_for_lending INT DEFAULT 1 CHECK (minimum_role_for_lending >= 1 AND minimum_role_for_lending <= 100),
  174. lending_status ENUM('Available', 'Deployed', 'Borrowed', 'Overdue', 'Illegally Handed Out', 'Stolen') NULL,
  175. current_borrower_id INT NULL,
  176. due_date DATE NULL,
  177. previous_borrower_id INT NULL,
  178. audit_task_id INT NULL,
  179. label_template_id INT NULL COMMENT 'Label template to use for this asset',
  180. no_scan ENUM('Yes', 'Ask', 'No') DEFAULT 'No',
  181. notes TEXT NULL,
  182. additional_fields JSON NULL,
  183. file_attachment MEDIUMBLOB NULL,
  184. created_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  185. created_by INT NULL,
  186. last_modified_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  187. last_modified_by INT NULL,
  188. FOREIGN KEY (category_id) REFERENCES categories(id) ON DELETE RESTRICT,
  189. FOREIGN KEY (zone_id) REFERENCES zones(id) ON DELETE RESTRICT,
  190. FOREIGN KEY (supplier_id) REFERENCES suppliers(id) ON DELETE SET NULL,
  191. FOREIGN KEY (current_borrower_id) REFERENCES borrowers(id) ON DELETE SET NULL,
  192. FOREIGN KEY (previous_borrower_id) REFERENCES borrowers(id) ON DELETE SET NULL,
  193. FOREIGN KEY (audit_task_id) REFERENCES audit_tasks(id) ON DELETE SET NULL,
  194. FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE SET NULL,
  195. FOREIGN KEY (last_modified_by) REFERENCES users(id) ON DELETE SET NULL,
  196. INDEX idx_asset_tag (asset_tag),
  197. INDEX idx_asset_numeric (asset_numeric_id),
  198. INDEX idx_type (asset_type),
  199. INDEX idx_status (status),
  200. INDEX idx_zone (zone_id),
  201. INDEX idx_category (category_id),
  202. INDEX idx_lendable (lendable),
  203. INDEX idx_lending_status (lending_status)
  204. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_uca1400_ai_ci;
  205. -- ============================================
  206. -- Templates Table (with new sexy columns)
  207. -- ============================================
  208. CREATE TABLE templates (
  209. id INT AUTO_INCREMENT PRIMARY KEY,
  210. template_code VARCHAR(50) NULL UNIQUE,
  211. asset_tag_generation_string VARCHAR(500) NULL,
  212. description TEXT NULL,
  213. active BOOLEAN DEFAULT TRUE,
  214. asset_type ENUM('N', 'B', 'L', 'C') NULL,
  215. name VARCHAR(255) NULL,
  216. category_id INT NULL,
  217. manufacturer VARCHAR(200) NULL,
  218. model VARCHAR(200) NULL,
  219. zone_id INT NULL,
  220. zone_plus ENUM('Floating Local', 'Floating Global', 'Clarify') NULL,
  221. zone_note TEXT NULL,
  222. status ENUM('Good', 'Attention', 'Faulty', 'Missing', 'Retired', 'In Repair', 'In Transit', 'Expired', 'Unmanaged') NULL,
  223. price DECIMAL(12, 2) NULL CHECK (price IS NULL OR price >= 0),
  224. purchase_date DATE NULL COMMENT 'Default purchase date for assets created from this template',
  225. purchase_date_now BOOLEAN DEFAULT FALSE COMMENT 'Auto-set purchase date to current date when creating assets',
  226. warranty_until DATE NULL,
  227. warranty_auto BOOLEAN DEFAULT FALSE COMMENT 'Auto-calculate warranty_until from purchase_date',
  228. warranty_auto_amount INT NULL COMMENT 'Number of days/years for warranty calculation',
  229. warranty_auto_unit ENUM('days', 'years') DEFAULT 'years' COMMENT 'Unit for warranty auto-calculation',
  230. expiry_date DATE NULL,
  231. expiry_auto BOOLEAN DEFAULT FALSE COMMENT 'Auto-calculate expiry_date from purchase_date',
  232. expiry_auto_amount INT NULL COMMENT 'Number of days/years for expiry calculation',
  233. expiry_auto_unit ENUM('days', 'years') DEFAULT 'years' COMMENT 'Unit for expiry auto-calculation',
  234. quantity_total INT NULL,
  235. quantity_used INT NULL,
  236. supplier_id INT NULL,
  237. lendable BOOLEAN NULL,
  238. lending_status ENUM('Available', 'Borrowed', 'Overdue', 'Deployed', 'Illegally Handed Out', 'Stolen') DEFAULT 'Available' COMMENT 'Default lending status for assets created from this template',
  239. minimum_role_for_lending INT NULL,
  240. audit_task_id INT NULL,
  241. label_template_id INT NULL COMMENT 'Default label template for assets created from this template',
  242. no_scan ENUM('Yes', 'Ask', 'No') NULL,
  243. notes TEXT NULL,
  244. additional_fields JSON NULL,
  245. created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  246. FOREIGN KEY (category_id) REFERENCES categories(id) ON DELETE SET NULL,
  247. FOREIGN KEY (zone_id) REFERENCES zones(id) ON DELETE SET NULL,
  248. FOREIGN KEY (supplier_id) REFERENCES suppliers(id) ON DELETE SET NULL,
  249. FOREIGN KEY (audit_task_id) REFERENCES audit_tasks(id) ON DELETE SET NULL,
  250. INDEX idx_template_code (template_code)
  251. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_uca1400_ai_ci;
  252. -- ============================================
  253. -- Lending History Table
  254. -- ============================================
  255. CREATE TABLE lending_history (
  256. id INT AUTO_INCREMENT PRIMARY KEY,
  257. asset_id INT NOT NULL,
  258. borrower_id INT NOT NULL,
  259. checkout_date DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  260. due_date DATE NULL,
  261. return_date DATETIME NULL,
  262. checked_out_by INT NULL,
  263. checked_in_by INT NULL,
  264. notes TEXT NULL,
  265. FOREIGN KEY (asset_id) REFERENCES assets(id) ON DELETE CASCADE,
  266. FOREIGN KEY (borrower_id) REFERENCES borrowers(id) ON DELETE RESTRICT,
  267. FOREIGN KEY (checked_out_by) REFERENCES users(id) ON DELETE RESTRICT,
  268. FOREIGN KEY (checked_in_by) REFERENCES users(id) ON DELETE SET NULL,
  269. INDEX idx_asset (asset_id),
  270. INDEX idx_borrower (borrower_id),
  271. INDEX idx_checkout_date (checkout_date),
  272. INDEX idx_return_date (return_date)
  273. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_uca1400_ai_ci;
  274. -- ============================================
  275. -- Physical Audits Table
  276. -- ============================================
  277. CREATE TABLE physical_audits (
  278. id INT AUTO_INCREMENT PRIMARY KEY,
  279. audit_type ENUM('full-zone', 'spot-check') NOT NULL,
  280. zone_id INT NULL COMMENT 'Zone being audited (NULL for spot-check audits)',
  281. audit_name VARCHAR(255) NULL COMMENT 'Custom name for the audit session',
  282. started_by INT NOT NULL,
  283. started_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  284. completed_at DATETIME NULL,
  285. status ENUM('in-progress', 'all-good', 'timeout', 'attention', 'cancelled') DEFAULT 'in-progress',
  286. timeout_minutes INT NULL COMMENT 'Timeout setting used for this audit',
  287. issues_found JSON NULL COMMENT 'Array of issues: missing_assets, moved_assets, damaged_assets, etc.',
  288. assets_expected INT NULL COMMENT 'Total assets expected to be found in zone',
  289. assets_found INT DEFAULT 0 COMMENT 'Total assets actually found and scanned',
  290. notes TEXT NULL,
  291. cancelled_reason TEXT NULL,
  292. FOREIGN KEY (zone_id) REFERENCES zones(id) ON DELETE RESTRICT,
  293. FOREIGN KEY (started_by) REFERENCES users(id) ON DELETE RESTRICT,
  294. INDEX idx_audit_type (audit_type),
  295. INDEX idx_zone (zone_id),
  296. INDEX idx_status (status),
  297. INDEX idx_started_at (started_at),
  298. INDEX idx_started_by (started_by)
  299. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_uca1400_ai_ci;
  300. -- ============================================
  301. -- Physical Audit Logs Table
  302. -- ============================================
  303. CREATE TABLE physical_audit_logs (
  304. id INT AUTO_INCREMENT PRIMARY KEY,
  305. physical_audit_id INT NOT NULL COMMENT 'Reference to the audit session',
  306. asset_id INT NOT NULL,
  307. audit_date DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  308. audited_by INT NOT NULL,
  309. status_found ENUM('Good', 'Attention', 'Faulty', 'Missing', 'Retired', 'In Repair', 'In Transit', 'Expired', 'Unmanaged') DEFAULT 'Good',
  310. audit_task_id INT NULL COMMENT 'Which audit task was run on this asset',
  311. audit_task_responses JSON NULL COMMENT 'User responses to the JSON sequence questions',
  312. exception_type ENUM('wrong-zone', 'unexpected-asset', 'damaged', 'missing-label', 'other') NULL,
  313. exception_details TEXT NULL COMMENT 'Details about the exception found',
  314. found_in_zone_id INT NULL COMMENT 'Which zone the asset was actually found in (if different from expected)',
  315. auditor_action ENUM('physical-move', 'virtual-update', 'no-action') NULL COMMENT 'What the auditor chose to do about wrong-zone assets',
  316. notes TEXT NULL,
  317. FOREIGN KEY (physical_audit_id) REFERENCES physical_audits(id) ON DELETE CASCADE,
  318. FOREIGN KEY (asset_id) REFERENCES assets(id) ON DELETE CASCADE,
  319. FOREIGN KEY (audited_by) REFERENCES users(id) ON DELETE RESTRICT,
  320. FOREIGN KEY (audit_task_id) REFERENCES audit_tasks(id) ON DELETE SET NULL,
  321. FOREIGN KEY (found_in_zone_id) REFERENCES zones(id) ON DELETE SET NULL,
  322. INDEX idx_physical_audit (physical_audit_id),
  323. INDEX idx_asset (asset_id),
  324. INDEX idx_audit_date (audit_date),
  325. INDEX idx_audited_by (audited_by),
  326. INDEX idx_status_found (status_found),
  327. INDEX idx_exception_type (exception_type)
  328. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_uca1400_ai_ci;
  329. -- ============================================
  330. -- Issue Tracker Table
  331. -- ============================================
  332. CREATE TABLE issue_tracker (
  333. id INT AUTO_INCREMENT PRIMARY KEY,
  334. issue_type ENUM('Asset Issue', 'Borrower Issue', 'System Issue', 'Maintenance', 'Other') NOT NULL,
  335. asset_id INT NULL,
  336. borrower_id INT NULL,
  337. title VARCHAR(255) NOT NULL,
  338. description TEXT NOT NULL,
  339. severity ENUM('Critical', 'High', 'Medium', 'Low') NULL,
  340. priority ENUM('Urgent', 'High', 'Normal', 'Low') DEFAULT 'Normal',
  341. status ENUM('Open', 'In Progress', 'Resolved', 'Closed', 'On Hold') DEFAULT 'Open',
  342. solution ENUM('Fixed', 'Replaced', 'Clarify', 'No Action Needed', 'Deferred', 'Items Returned', 'Automatically Fixed') NULL,
  343. solution_plus TEXT NULL,
  344. replacement_asset_id INT NULL,
  345. reported_by INT NOT NULL,
  346. assigned_to INT NULL,
  347. resolved_by INT NULL,
  348. cost DECIMAL(10, 2) NULL,
  349. created_date DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  350. updated_date DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  351. resolved_date DATETIME NULL,
  352. notes TEXT NULL,
  353. auto_detected BOOLEAN DEFAULT FALSE,
  354. detection_trigger VARCHAR(100) NULL,
  355. FOREIGN KEY (asset_id) REFERENCES assets(id) ON DELETE CASCADE,
  356. FOREIGN KEY (borrower_id) REFERENCES borrowers(id) ON DELETE CASCADE,
  357. FOREIGN KEY (replacement_asset_id) REFERENCES assets(id) ON DELETE SET NULL,
  358. FOREIGN KEY (reported_by) REFERENCES users(id) ON DELETE RESTRICT,
  359. FOREIGN KEY (assigned_to) REFERENCES users(id) ON DELETE SET NULL,
  360. FOREIGN KEY (resolved_by) REFERENCES users(id) ON DELETE SET NULL,
  361. INDEX idx_issue_type (issue_type),
  362. INDEX idx_asset (asset_id),
  363. INDEX idx_borrower (borrower_id),
  364. INDEX idx_severity (severity),
  365. INDEX idx_status (status),
  366. INDEX idx_created_date (created_date),
  367. INDEX idx_auto_detected (auto_detected)
  368. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_uca1400_ai_ci;
  369. -- ============================================
  370. -- Issue Tracker Change Log Table
  371. -- ============================================
  372. CREATE TABLE issue_tracker_change_log (
  373. id INT AUTO_INCREMENT PRIMARY KEY,
  374. issue_id INT NOT NULL,
  375. change_type ENUM('INSERT', 'UPDATE', 'DELETE') NOT NULL,
  376. changed_fields JSON NULL,
  377. old_values JSON NULL,
  378. new_values JSON NULL,
  379. changed_by INT NULL,
  380. change_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  381. FOREIGN KEY (issue_id) REFERENCES issue_tracker(id) ON DELETE CASCADE,
  382. FOREIGN KEY (changed_by) REFERENCES users(id) ON DELETE SET NULL,
  383. INDEX idx_issue (issue_id),
  384. INDEX idx_change_type (change_type),
  385. INDEX idx_change_date (change_date)
  386. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_uca1400_ai_ci;
  387. -- ============================================
  388. -- Asset Change Log Table
  389. -- ============================================
  390. CREATE TABLE asset_change_log (
  391. id INT AUTO_INCREMENT PRIMARY KEY,
  392. table_name VARCHAR(50) NOT NULL,
  393. action ENUM('INSERT', 'UPDATE', 'DELETE') NOT NULL,
  394. record_id INT NOT NULL,
  395. changed_fields JSON NULL COMMENT 'Only fields that actually changed',
  396. old_values JSON NULL,
  397. new_values JSON NULL,
  398. changed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  399. changed_by_id INT NULL,
  400. changed_by_username VARCHAR(100) NULL,
  401. FOREIGN KEY (changed_by_id) REFERENCES users(id) ON DELETE SET NULL,
  402. INDEX idx_table_action (table_name, action),
  403. INDEX idx_timestamp (changed_at),
  404. INDEX idx_record (record_id),
  405. INDEX idx_user (changed_by_id)
  406. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_uca1400_ai_ci;
  407. -- ============================================
  408. -- Label Templates Table
  409. -- ============================================
  410. CREATE TABLE label_templates (
  411. id INT AUTO_INCREMENT PRIMARY KEY,
  412. template_code VARCHAR(100) NOT NULL UNIQUE COMMENT 'Unique code like "CABLE"',
  413. template_name VARCHAR(200) NOT NULL COMMENT 'Human readable name',
  414. layout_json JSON NOT NULL COMMENT 'Universal label design: graphics, auto-populated field placeholders, styling with space dimensions',
  415. created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  416. created_by INT NULL,
  417. last_modified_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  418. last_modified_by INT NULL,
  419. FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE SET NULL,
  420. FOREIGN KEY (last_modified_by) REFERENCES users(id) ON DELETE SET NULL,
  421. INDEX idx_template_code (template_code),
  422. INDEX idx_template_name (template_name)
  423. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_uca1400_ai_ci;
  424. -- ============================================
  425. -- Printer Settings Table
  426. -- ============================================
  427. CREATE TABLE printer_settings (
  428. id INT AUTO_INCREMENT PRIMARY KEY,
  429. printer_name VARCHAR(200) NOT NULL,
  430. description TEXT NULL,
  431. log BOOLEAN DEFAULT TRUE COMMENT 'Log all print jobs to this printer',
  432. can_be_used_for_reports BOOLEAN DEFAULT FALSE COMMENT 'Can this printer be used for printing reports',
  433. min_powerlevel_to_use INT NOT NULL DEFAULT 75 COMMENT 'Minimum role power level required to use this printer',
  434. printer_plugin ENUM('Ptouch', 'Brother', 'Zebra', 'System', 'PDF', 'Network', 'Custom') NOT NULL COMMENT 'Which printer plugin the client should send printer_settings to',
  435. printer_settings JSON NOT NULL COMMENT 'Printer-specific settings: connection, paper size, DPI, margins, etc.',
  436. created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  437. created_by INT NULL,
  438. last_modified_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  439. last_modified_by INT NULL,
  440. FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE SET NULL,
  441. FOREIGN KEY (last_modified_by) REFERENCES users(id) ON DELETE SET NULL,
  442. INDEX idx_printer_name (printer_name),
  443. INDEX idx_printer_plugin (printer_plugin),
  444. INDEX idx_min_powerlevel (min_powerlevel_to_use),
  445. INDEX idx_can_reports (can_be_used_for_reports),
  446. CHECK (min_powerlevel_to_use >= 1 AND min_powerlevel_to_use <= 100)
  447. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_uca1400_ai_ci;
  448. -- ============================================
  449. -- Print History Table (Labels & Reports)
  450. -- ============================================
  451. CREATE TABLE print_history (
  452. id INT AUTO_INCREMENT PRIMARY KEY,
  453. entity_type ENUM('Asset', 'Template', 'Borrower', 'Zone', 'Report', 'Custom') NOT NULL,
  454. entity_id INT NULL COMMENT 'ID of the asset/template/borrower/zone (NULL for reports)',
  455. label_template_id INT NULL,
  456. printer_id INT NULL,
  457. quantity INT DEFAULT 1,
  458. print_status ENUM('Success', 'Failed', 'Cancelled', 'Queued') NOT NULL,
  459. error_message TEXT NULL,
  460. rendered_data JSON NULL COMMENT 'The actual data that was sent to printer (for debugging)',
  461. printed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  462. printed_by INT NULL,
  463. FOREIGN KEY (label_template_id) REFERENCES label_templates(id) ON DELETE SET NULL,
  464. FOREIGN KEY (printer_id) REFERENCES printer_settings(id) ON DELETE SET NULL,
  465. FOREIGN KEY (printed_by) REFERENCES users(id) ON DELETE SET NULL,
  466. INDEX idx_entity (entity_type, entity_id),
  467. INDEX idx_printed_at (printed_at),
  468. INDEX idx_printed_by (printed_by),
  469. INDEX idx_printer (printer_id),
  470. INDEX idx_status (print_status)
  471. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_uca1400_ai_ci;
  472. -- ============================================
  473. -- TRIGGERS FOR ASSETS TABLE
  474. -- ============================================
  475. DELIMITER //
  476. -- Trigger: Auto-populate created_by on INSERT
  477. DROP TRIGGER IF EXISTS assets_before_insert_meta//
  478. CREATE TRIGGER assets_before_insert_meta
  479. BEFORE INSERT ON assets
  480. FOR EACH ROW
  481. BEGIN
  482. IF NEW.created_by IS NULL AND @current_user_id IS NOT NULL THEN
  483. SET NEW.created_by = @current_user_id;
  484. END IF;
  485. END//
  486. -- Trigger: Auto-update last_modified_date and last_modified_by
  487. DROP TRIGGER IF EXISTS assets_before_update_meta//
  488. CREATE TRIGGER assets_before_update_meta
  489. BEFORE UPDATE ON assets
  490. FOR EACH ROW
  491. BEGIN
  492. SET NEW.last_modified_date = NOW();
  493. IF @current_user_id IS NOT NULL THEN
  494. SET NEW.last_modified_by = @current_user_id;
  495. END IF;
  496. END//
  497. -- Trigger: Log INSERT operations (only non-NULL fields for efficiency)
  498. DROP TRIGGER IF EXISTS assets_after_insert_log//
  499. CREATE TRIGGER assets_after_insert_log
  500. AFTER INSERT ON assets
  501. FOR EACH ROW
  502. BEGIN
  503. DECLARE username VARCHAR(100);
  504. DECLARE set_fields_array JSON;
  505. DECLARE new_vals JSON;
  506. IF @current_user_id IS NOT NULL THEN
  507. SELECT users.username INTO username FROM users WHERE id = @current_user_id;
  508. END IF;
  509. -- Build JSON objects only with non-NULL fields
  510. SET set_fields_array = JSON_ARRAY();
  511. SET new_vals = JSON_OBJECT();
  512. -- Always log these core fields
  513. IF NEW.asset_tag IS NOT NULL THEN
  514. SET set_fields_array = JSON_ARRAY_APPEND(set_fields_array, '$', 'asset_tag');
  515. SET new_vals = JSON_SET(new_vals, '$.asset_tag', NEW.asset_tag);
  516. END IF;
  517. IF NEW.asset_numeric_id IS NOT NULL THEN
  518. SET set_fields_array = JSON_ARRAY_APPEND(set_fields_array, '$', 'asset_numeric_id');
  519. SET new_vals = JSON_SET(new_vals, '$.asset_numeric_id', NEW.asset_numeric_id);
  520. END IF;
  521. IF NEW.asset_type IS NOT NULL THEN
  522. SET set_fields_array = JSON_ARRAY_APPEND(set_fields_array, '$', 'asset_type');
  523. SET new_vals = JSON_SET(new_vals, '$.asset_type', NEW.asset_type);
  524. END IF;
  525. IF NEW.name IS NOT NULL THEN
  526. SET set_fields_array = JSON_ARRAY_APPEND(set_fields_array, '$', 'name');
  527. SET new_vals = JSON_SET(new_vals, '$.name', NEW.name);
  528. END IF;
  529. IF NEW.category_id IS NOT NULL THEN
  530. SET set_fields_array = JSON_ARRAY_APPEND(set_fields_array, '$', 'category_id');
  531. SET new_vals = JSON_SET(new_vals, '$.category_id', NEW.category_id);
  532. END IF;
  533. IF NEW.manufacturer IS NOT NULL THEN
  534. SET set_fields_array = JSON_ARRAY_APPEND(set_fields_array, '$', 'manufacturer');
  535. SET new_vals = JSON_SET(new_vals, '$.manufacturer', NEW.manufacturer);
  536. END IF;
  537. IF NEW.model IS NOT NULL THEN
  538. SET set_fields_array = JSON_ARRAY_APPEND(set_fields_array, '$', 'model');
  539. SET new_vals = JSON_SET(new_vals, '$.model', NEW.model);
  540. END IF;
  541. IF NEW.serial_number IS NOT NULL THEN
  542. SET set_fields_array = JSON_ARRAY_APPEND(set_fields_array, '$', 'serial_number');
  543. SET new_vals = JSON_SET(new_vals, '$.serial_number', NEW.serial_number);
  544. END IF;
  545. IF NEW.zone_id IS NOT NULL THEN
  546. SET set_fields_array = JSON_ARRAY_APPEND(set_fields_array, '$', 'zone_id');
  547. SET new_vals = JSON_SET(new_vals, '$.zone_id', NEW.zone_id);
  548. END IF;
  549. IF NEW.zone_plus IS NOT NULL THEN
  550. SET set_fields_array = JSON_ARRAY_APPEND(set_fields_array, '$', 'zone_plus');
  551. SET new_vals = JSON_SET(new_vals, '$.zone_plus', NEW.zone_plus);
  552. END IF;
  553. IF NEW.zone_note IS NOT NULL THEN
  554. SET set_fields_array = JSON_ARRAY_APPEND(set_fields_array, '$', 'zone_note');
  555. SET new_vals = JSON_SET(new_vals, '$.zone_note', NEW.zone_note);
  556. END IF;
  557. IF NEW.status IS NOT NULL THEN
  558. SET set_fields_array = JSON_ARRAY_APPEND(set_fields_array, '$', 'status');
  559. SET new_vals = JSON_SET(new_vals, '$.status', NEW.status);
  560. END IF;
  561. IF NEW.last_audit IS NOT NULL THEN
  562. SET set_fields_array = JSON_ARRAY_APPEND(set_fields_array, '$', 'last_audit');
  563. SET new_vals = JSON_SET(new_vals, '$.last_audit', NEW.last_audit);
  564. END IF;
  565. IF NEW.last_audit_status IS NOT NULL THEN
  566. SET set_fields_array = JSON_ARRAY_APPEND(set_fields_array, '$', 'last_audit_status');
  567. SET new_vals = JSON_SET(new_vals, '$.last_audit_status', NEW.last_audit_status);
  568. END IF;
  569. IF NEW.price IS NOT NULL THEN
  570. SET set_fields_array = JSON_ARRAY_APPEND(set_fields_array, '$', 'price');
  571. SET new_vals = JSON_SET(new_vals, '$.price', NEW.price);
  572. END IF;
  573. IF NEW.purchase_date IS NOT NULL THEN
  574. SET set_fields_array = JSON_ARRAY_APPEND(set_fields_array, '$', 'purchase_date');
  575. SET new_vals = JSON_SET(new_vals, '$.purchase_date', NEW.purchase_date);
  576. END IF;
  577. IF NEW.warranty_until IS NOT NULL THEN
  578. SET set_fields_array = JSON_ARRAY_APPEND(set_fields_array, '$', 'warranty_until');
  579. SET new_vals = JSON_SET(new_vals, '$.warranty_until', NEW.warranty_until);
  580. END IF;
  581. IF NEW.expiry_date IS NOT NULL THEN
  582. SET set_fields_array = JSON_ARRAY_APPEND(set_fields_array, '$', 'expiry_date');
  583. SET new_vals = JSON_SET(new_vals, '$.expiry_date', NEW.expiry_date);
  584. END IF;
  585. IF NEW.quantity_available IS NOT NULL THEN
  586. SET set_fields_array = JSON_ARRAY_APPEND(set_fields_array, '$', 'quantity_available');
  587. SET new_vals = JSON_SET(new_vals, '$.quantity_available', NEW.quantity_available);
  588. END IF;
  589. IF NEW.quantity_total IS NOT NULL THEN
  590. SET set_fields_array = JSON_ARRAY_APPEND(set_fields_array, '$', 'quantity_total');
  591. SET new_vals = JSON_SET(new_vals, '$.quantity_total', NEW.quantity_total);
  592. END IF;
  593. IF NEW.quantity_used IS NOT NULL THEN
  594. SET set_fields_array = JSON_ARRAY_APPEND(set_fields_array, '$', 'quantity_used');
  595. SET new_vals = JSON_SET(new_vals, '$.quantity_used', NEW.quantity_used);
  596. END IF;
  597. IF NEW.supplier_id IS NOT NULL THEN
  598. SET set_fields_array = JSON_ARRAY_APPEND(set_fields_array, '$', 'supplier_id');
  599. SET new_vals = JSON_SET(new_vals, '$.supplier_id', NEW.supplier_id);
  600. END IF;
  601. IF NEW.lendable IS NOT NULL THEN
  602. SET set_fields_array = JSON_ARRAY_APPEND(set_fields_array, '$', 'lendable');
  603. SET new_vals = JSON_SET(new_vals, '$.lendable', NEW.lendable);
  604. END IF;
  605. IF NEW.minimum_role_for_lending IS NOT NULL THEN
  606. SET set_fields_array = JSON_ARRAY_APPEND(set_fields_array, '$', 'minimum_role_for_lending');
  607. SET new_vals = JSON_SET(new_vals, '$.minimum_role_for_lending', NEW.minimum_role_for_lending);
  608. END IF;
  609. IF NEW.lending_status IS NOT NULL THEN
  610. SET set_fields_array = JSON_ARRAY_APPEND(set_fields_array, '$', 'lending_status');
  611. SET new_vals = JSON_SET(new_vals, '$.lending_status', NEW.lending_status);
  612. END IF;
  613. IF NEW.current_borrower_id IS NOT NULL THEN
  614. SET set_fields_array = JSON_ARRAY_APPEND(set_fields_array, '$', 'current_borrower_id');
  615. SET new_vals = JSON_SET(new_vals, '$.current_borrower_id', NEW.current_borrower_id);
  616. END IF;
  617. IF NEW.due_date IS NOT NULL THEN
  618. SET set_fields_array = JSON_ARRAY_APPEND(set_fields_array, '$', 'due_date');
  619. SET new_vals = JSON_SET(new_vals, '$.due_date', NEW.due_date);
  620. END IF;
  621. IF NEW.previous_borrower_id IS NOT NULL THEN
  622. SET set_fields_array = JSON_ARRAY_APPEND(set_fields_array, '$', 'previous_borrower_id');
  623. SET new_vals = JSON_SET(new_vals, '$.previous_borrower_id', NEW.previous_borrower_id);
  624. END IF;
  625. IF NEW.audit_task_id IS NOT NULL THEN
  626. SET set_fields_array = JSON_ARRAY_APPEND(set_fields_array, '$', 'audit_task_id');
  627. SET new_vals = JSON_SET(new_vals, '$.audit_task_id', NEW.audit_task_id);
  628. END IF;
  629. IF NEW.no_scan IS NOT NULL THEN
  630. SET set_fields_array = JSON_ARRAY_APPEND(set_fields_array, '$', 'no_scan');
  631. SET new_vals = JSON_SET(new_vals, '$.no_scan', NEW.no_scan);
  632. END IF;
  633. IF NEW.notes IS NOT NULL THEN
  634. SET set_fields_array = JSON_ARRAY_APPEND(set_fields_array, '$', 'notes');
  635. SET new_vals = JSON_SET(new_vals, '$.notes', NEW.notes);
  636. END IF;
  637. IF NEW.additional_fields IS NOT NULL THEN
  638. SET set_fields_array = JSON_ARRAY_APPEND(set_fields_array, '$', 'additional_fields');
  639. SET new_vals = JSON_SET(new_vals, '$.additional_fields', NEW.additional_fields);
  640. END IF;
  641. IF NEW.created_by IS NOT NULL THEN
  642. SET set_fields_array = JSON_ARRAY_APPEND(set_fields_array, '$', 'created_by');
  643. SET new_vals = JSON_SET(new_vals, '$.created_by', NEW.created_by);
  644. END IF;
  645. -- Log the INSERT with only the fields that were set
  646. INSERT INTO asset_change_log (
  647. table_name, action, record_id, changed_fields, new_values,
  648. changed_by_id, changed_by_username
  649. )
  650. VALUES (
  651. 'assets',
  652. 'INSERT',
  653. NEW.id,
  654. set_fields_array,
  655. new_vals,
  656. @current_user_id,
  657. username
  658. );
  659. END//
  660. -- Trigger: Log UPDATE operations (only changed fields)
  661. DROP TRIGGER IF EXISTS assets_after_update_log//
  662. CREATE TRIGGER assets_after_update_log
  663. AFTER UPDATE ON assets
  664. FOR EACH ROW
  665. BEGIN
  666. DECLARE username VARCHAR(100);
  667. DECLARE changed_fields_array JSON;
  668. DECLARE old_vals JSON;
  669. DECLARE new_vals JSON;
  670. IF @current_user_id IS NOT NULL THEN
  671. SELECT users.username INTO username FROM users WHERE id = @current_user_id;
  672. END IF;
  673. -- Build JSON objects only with changed fields
  674. SET changed_fields_array = JSON_ARRAY();
  675. SET old_vals = JSON_OBJECT();
  676. SET new_vals = JSON_OBJECT();
  677. IF OLD.asset_tag <=> NEW.asset_tag IS FALSE THEN
  678. SET changed_fields_array = JSON_ARRAY_APPEND(changed_fields_array, '$', 'asset_tag');
  679. SET old_vals = JSON_SET(old_vals, '$.asset_tag', OLD.asset_tag);
  680. SET new_vals = JSON_SET(new_vals, '$.asset_tag', NEW.asset_tag);
  681. END IF;
  682. IF OLD.asset_numeric_id <=> NEW.asset_numeric_id IS FALSE THEN
  683. SET changed_fields_array = JSON_ARRAY_APPEND(changed_fields_array, '$', 'asset_numeric_id');
  684. SET old_vals = JSON_SET(old_vals, '$.asset_numeric_id', OLD.asset_numeric_id);
  685. SET new_vals = JSON_SET(new_vals, '$.asset_numeric_id', NEW.asset_numeric_id);
  686. END IF;
  687. IF OLD.asset_type <=> NEW.asset_type IS FALSE THEN
  688. SET changed_fields_array = JSON_ARRAY_APPEND(changed_fields_array, '$', 'asset_type');
  689. SET old_vals = JSON_SET(old_vals, '$.asset_type', OLD.asset_type);
  690. SET new_vals = JSON_SET(new_vals, '$.asset_type', NEW.asset_type);
  691. END IF;
  692. IF OLD.name <=> NEW.name IS FALSE THEN
  693. SET changed_fields_array = JSON_ARRAY_APPEND(changed_fields_array, '$', 'name');
  694. SET old_vals = JSON_SET(old_vals, '$.name', OLD.name);
  695. SET new_vals = JSON_SET(new_vals, '$.name', NEW.name);
  696. END IF;
  697. IF OLD.category_id <=> NEW.category_id IS FALSE THEN
  698. SET changed_fields_array = JSON_ARRAY_APPEND(changed_fields_array, '$', 'category_id');
  699. SET old_vals = JSON_SET(old_vals, '$.category_id', OLD.category_id);
  700. SET new_vals = JSON_SET(new_vals, '$.category_id', NEW.category_id);
  701. END IF;
  702. IF OLD.manufacturer <=> NEW.manufacturer IS FALSE THEN
  703. SET changed_fields_array = JSON_ARRAY_APPEND(changed_fields_array, '$', 'manufacturer');
  704. SET old_vals = JSON_SET(old_vals, '$.manufacturer', OLD.manufacturer);
  705. SET new_vals = JSON_SET(new_vals, '$.manufacturer', NEW.manufacturer);
  706. END IF;
  707. IF OLD.model <=> NEW.model IS FALSE THEN
  708. SET changed_fields_array = JSON_ARRAY_APPEND(changed_fields_array, '$', 'model');
  709. SET old_vals = JSON_SET(old_vals, '$.model', OLD.model);
  710. SET new_vals = JSON_SET(new_vals, '$.model', NEW.model);
  711. END IF;
  712. IF OLD.serial_number <=> NEW.serial_number IS FALSE THEN
  713. SET changed_fields_array = JSON_ARRAY_APPEND(changed_fields_array, '$', 'serial_number');
  714. SET old_vals = JSON_SET(old_vals, '$.serial_number', OLD.serial_number);
  715. SET new_vals = JSON_SET(new_vals, '$.serial_number', NEW.serial_number);
  716. END IF;
  717. IF OLD.zone_id <=> NEW.zone_id IS FALSE THEN
  718. SET changed_fields_array = JSON_ARRAY_APPEND(changed_fields_array, '$', 'zone_id');
  719. SET old_vals = JSON_SET(old_vals, '$.zone_id', OLD.zone_id);
  720. SET new_vals = JSON_SET(new_vals, '$.zone_id', NEW.zone_id);
  721. END IF;
  722. IF OLD.zone_plus <=> NEW.zone_plus IS FALSE THEN
  723. SET changed_fields_array = JSON_ARRAY_APPEND(changed_fields_array, '$', 'zone_plus');
  724. SET old_vals = JSON_SET(old_vals, '$.zone_plus', OLD.zone_plus);
  725. SET new_vals = JSON_SET(new_vals, '$.zone_plus', NEW.zone_plus);
  726. END IF;
  727. IF OLD.zone_note <=> NEW.zone_note IS FALSE THEN
  728. SET changed_fields_array = JSON_ARRAY_APPEND(changed_fields_array, '$', 'zone_note');
  729. SET old_vals = JSON_SET(old_vals, '$.zone_note', OLD.zone_note);
  730. SET new_vals = JSON_SET(new_vals, '$.zone_note', NEW.zone_note);
  731. END IF;
  732. IF OLD.status <=> NEW.status IS FALSE THEN
  733. SET changed_fields_array = JSON_ARRAY_APPEND(changed_fields_array, '$', 'status');
  734. SET old_vals = JSON_SET(old_vals, '$.status', OLD.status);
  735. SET new_vals = JSON_SET(new_vals, '$.status', NEW.status);
  736. END IF;
  737. IF OLD.last_audit <=> NEW.last_audit IS FALSE THEN
  738. SET changed_fields_array = JSON_ARRAY_APPEND(changed_fields_array, '$', 'last_audit');
  739. SET old_vals = JSON_SET(old_vals, '$.last_audit', OLD.last_audit);
  740. SET new_vals = JSON_SET(new_vals, '$.last_audit', NEW.last_audit);
  741. END IF;
  742. IF OLD.last_audit_status <=> NEW.last_audit_status IS FALSE THEN
  743. SET changed_fields_array = JSON_ARRAY_APPEND(changed_fields_array, '$', 'last_audit_status');
  744. SET old_vals = JSON_SET(old_vals, '$.last_audit_status', OLD.last_audit_status);
  745. SET new_vals = JSON_SET(new_vals, '$.last_audit_status', NEW.last_audit_status);
  746. END IF;
  747. IF OLD.price <=> NEW.price IS FALSE THEN
  748. SET changed_fields_array = JSON_ARRAY_APPEND(changed_fields_array, '$', 'price');
  749. SET old_vals = JSON_SET(old_vals, '$.price', OLD.price);
  750. SET new_vals = JSON_SET(new_vals, '$.price', NEW.price);
  751. END IF;
  752. IF OLD.purchase_date <=> NEW.purchase_date IS FALSE THEN
  753. SET changed_fields_array = JSON_ARRAY_APPEND(changed_fields_array, '$', 'purchase_date');
  754. SET old_vals = JSON_SET(old_vals, '$.purchase_date', OLD.purchase_date);
  755. SET new_vals = JSON_SET(new_vals, '$.purchase_date', NEW.purchase_date);
  756. END IF;
  757. IF OLD.warranty_until <=> NEW.warranty_until IS FALSE THEN
  758. SET changed_fields_array = JSON_ARRAY_APPEND(changed_fields_array, '$', 'warranty_until');
  759. SET old_vals = JSON_SET(old_vals, '$.warranty_until', OLD.warranty_until);
  760. SET new_vals = JSON_SET(new_vals, '$.warranty_until', NEW.warranty_until);
  761. END IF;
  762. IF OLD.expiry_date <=> NEW.expiry_date IS FALSE THEN
  763. SET changed_fields_array = JSON_ARRAY_APPEND(changed_fields_array, '$', 'expiry_date');
  764. SET old_vals = JSON_SET(old_vals, '$.expiry_date', OLD.expiry_date);
  765. SET new_vals = JSON_SET(new_vals, '$.expiry_date', NEW.expiry_date);
  766. END IF;
  767. IF OLD.quantity_available <=> NEW.quantity_available IS FALSE THEN
  768. SET changed_fields_array = JSON_ARRAY_APPEND(changed_fields_array, '$', 'quantity_available');
  769. SET old_vals = JSON_SET(old_vals, '$.quantity_available', OLD.quantity_available);
  770. SET new_vals = JSON_SET(new_vals, '$.quantity_available', NEW.quantity_available);
  771. END IF;
  772. IF OLD.quantity_total <=> NEW.quantity_total IS FALSE THEN
  773. SET changed_fields_array = JSON_ARRAY_APPEND(changed_fields_array, '$', 'quantity_total');
  774. SET old_vals = JSON_SET(old_vals, '$.quantity_total', OLD.quantity_total);
  775. SET new_vals = JSON_SET(new_vals, '$.quantity_total', NEW.quantity_total);
  776. END IF;
  777. IF OLD.quantity_used <=> NEW.quantity_used IS FALSE THEN
  778. SET changed_fields_array = JSON_ARRAY_APPEND(changed_fields_array, '$', 'quantity_used');
  779. SET old_vals = JSON_SET(old_vals, '$.quantity_used', OLD.quantity_used);
  780. SET new_vals = JSON_SET(new_vals, '$.quantity_used', NEW.quantity_used);
  781. END IF;
  782. IF OLD.supplier_id <=> NEW.supplier_id IS FALSE THEN
  783. SET changed_fields_array = JSON_ARRAY_APPEND(changed_fields_array, '$', 'supplier_id');
  784. SET old_vals = JSON_SET(old_vals, '$.supplier_id', OLD.supplier_id);
  785. SET new_vals = JSON_SET(new_vals, '$.supplier_id', NEW.supplier_id);
  786. END IF;
  787. IF OLD.lendable <=> NEW.lendable IS FALSE THEN
  788. SET changed_fields_array = JSON_ARRAY_APPEND(changed_fields_array, '$', 'lendable');
  789. SET old_vals = JSON_SET(old_vals, '$.lendable', OLD.lendable);
  790. SET new_vals = JSON_SET(new_vals, '$.lendable', NEW.lendable);
  791. END IF;
  792. IF OLD.minimum_role_for_lending <=> NEW.minimum_role_for_lending IS FALSE THEN
  793. SET changed_fields_array = JSON_ARRAY_APPEND(changed_fields_array, '$', 'minimum_role_for_lending');
  794. SET old_vals = JSON_SET(old_vals, '$.minimum_role_for_lending', OLD.minimum_role_for_lending);
  795. SET new_vals = JSON_SET(new_vals, '$.minimum_role_for_lending', NEW.minimum_role_for_lending);
  796. END IF;
  797. IF OLD.lending_status <=> NEW.lending_status IS FALSE THEN
  798. SET changed_fields_array = JSON_ARRAY_APPEND(changed_fields_array, '$', 'lending_status');
  799. SET old_vals = JSON_SET(old_vals, '$.lending_status', OLD.lending_status);
  800. SET new_vals = JSON_SET(new_vals, '$.lending_status', NEW.lending_status);
  801. END IF;
  802. IF OLD.current_borrower_id <=> NEW.current_borrower_id IS FALSE THEN
  803. SET changed_fields_array = JSON_ARRAY_APPEND(changed_fields_array, '$', 'current_borrower_id');
  804. SET old_vals = JSON_SET(old_vals, '$.current_borrower_id', OLD.current_borrower_id);
  805. SET new_vals = JSON_SET(new_vals, '$.current_borrower_id', NEW.current_borrower_id);
  806. END IF;
  807. IF OLD.due_date <=> NEW.due_date IS FALSE THEN
  808. SET changed_fields_array = JSON_ARRAY_APPEND(changed_fields_array, '$', 'due_date');
  809. SET old_vals = JSON_SET(old_vals, '$.due_date', OLD.due_date);
  810. SET new_vals = JSON_SET(new_vals, '$.due_date', NEW.due_date);
  811. END IF;
  812. IF OLD.previous_borrower_id <=> NEW.previous_borrower_id IS FALSE THEN
  813. SET changed_fields_array = JSON_ARRAY_APPEND(changed_fields_array, '$', 'previous_borrower_id');
  814. SET old_vals = JSON_SET(old_vals, '$.previous_borrower_id', OLD.previous_borrower_id);
  815. SET new_vals = JSON_SET(new_vals, '$.previous_borrower_id', NEW.previous_borrower_id);
  816. END IF;
  817. IF OLD.audit_task_id <=> NEW.audit_task_id IS FALSE THEN
  818. SET changed_fields_array = JSON_ARRAY_APPEND(changed_fields_array, '$', 'audit_task_id');
  819. SET old_vals = JSON_SET(old_vals, '$.audit_task_id', OLD.audit_task_id);
  820. SET new_vals = JSON_SET(new_vals, '$.audit_task_id', NEW.audit_task_id);
  821. END IF;
  822. IF OLD.no_scan <=> NEW.no_scan IS FALSE THEN
  823. SET changed_fields_array = JSON_ARRAY_APPEND(changed_fields_array, '$', 'no_scan');
  824. SET old_vals = JSON_SET(old_vals, '$.no_scan', OLD.no_scan);
  825. SET new_vals = JSON_SET(new_vals, '$.no_scan', NEW.no_scan);
  826. END IF;
  827. IF OLD.notes <=> NEW.notes IS FALSE THEN
  828. SET changed_fields_array = JSON_ARRAY_APPEND(changed_fields_array, '$', 'notes');
  829. SET old_vals = JSON_SET(old_vals, '$.notes', OLD.notes);
  830. SET new_vals = JSON_SET(new_vals, '$.notes', NEW.notes);
  831. END IF;
  832. IF OLD.additional_fields <=> NEW.additional_fields IS FALSE THEN
  833. SET changed_fields_array = JSON_ARRAY_APPEND(changed_fields_array, '$', 'additional_fields');
  834. SET old_vals = JSON_SET(old_vals, '$.additional_fields', OLD.additional_fields);
  835. SET new_vals = JSON_SET(new_vals, '$.additional_fields', NEW.additional_fields);
  836. END IF;
  837. -- Only log if there were actual changes (excluding auto-updated fields)
  838. IF JSON_LENGTH(changed_fields_array) > 0 THEN
  839. INSERT INTO asset_change_log (
  840. table_name, action, record_id, changed_fields, old_values, new_values,
  841. changed_by_id, changed_by_username
  842. )
  843. VALUES (
  844. 'assets',
  845. 'UPDATE',
  846. NEW.id,
  847. changed_fields_array,
  848. old_vals,
  849. new_vals,
  850. @current_user_id,
  851. username
  852. );
  853. END IF;
  854. END//
  855. -- Trigger: Log DELETE operations (only non-NULL fields for efficiency, but preserve all data for restore)
  856. DROP TRIGGER IF EXISTS assets_after_delete_log//
  857. CREATE TRIGGER assets_after_delete_log
  858. AFTER DELETE ON assets
  859. FOR EACH ROW
  860. BEGIN
  861. DECLARE username VARCHAR(100);
  862. DECLARE deleted_fields_array JSON;
  863. DECLARE old_vals JSON;
  864. IF @current_user_id IS NOT NULL THEN
  865. SELECT users.username INTO username FROM users WHERE id = @current_user_id;
  866. END IF;
  867. -- Build JSON objects only with non-NULL fields (for restore capability)
  868. SET deleted_fields_array = JSON_ARRAY();
  869. SET old_vals = JSON_OBJECT();
  870. IF OLD.asset_tag IS NOT NULL THEN
  871. SET deleted_fields_array = JSON_ARRAY_APPEND(deleted_fields_array, '$', 'asset_tag');
  872. SET old_vals = JSON_SET(old_vals, '$.asset_tag', OLD.asset_tag);
  873. END IF;
  874. IF OLD.asset_numeric_id IS NOT NULL THEN
  875. SET deleted_fields_array = JSON_ARRAY_APPEND(deleted_fields_array, '$', 'asset_numeric_id');
  876. SET old_vals = JSON_SET(old_vals, '$.asset_numeric_id', OLD.asset_numeric_id);
  877. END IF;
  878. IF OLD.asset_type IS NOT NULL THEN
  879. SET deleted_fields_array = JSON_ARRAY_APPEND(deleted_fields_array, '$', 'asset_type');
  880. SET old_vals = JSON_SET(old_vals, '$.asset_type', OLD.asset_type);
  881. END IF;
  882. IF OLD.name IS NOT NULL THEN
  883. SET deleted_fields_array = JSON_ARRAY_APPEND(deleted_fields_array, '$', 'name');
  884. SET old_vals = JSON_SET(old_vals, '$.name', OLD.name);
  885. END IF;
  886. IF OLD.category_id IS NOT NULL THEN
  887. SET deleted_fields_array = JSON_ARRAY_APPEND(deleted_fields_array, '$', 'category_id');
  888. SET old_vals = JSON_SET(old_vals, '$.category_id', OLD.category_id);
  889. END IF;
  890. IF OLD.manufacturer IS NOT NULL THEN
  891. SET deleted_fields_array = JSON_ARRAY_APPEND(deleted_fields_array, '$', 'manufacturer');
  892. SET old_vals = JSON_SET(old_vals, '$.manufacturer', OLD.manufacturer);
  893. END IF;
  894. IF OLD.model IS NOT NULL THEN
  895. SET deleted_fields_array = JSON_ARRAY_APPEND(deleted_fields_array, '$', 'model');
  896. SET old_vals = JSON_SET(old_vals, '$.model', OLD.model);
  897. END IF;
  898. IF OLD.serial_number IS NOT NULL THEN
  899. SET deleted_fields_array = JSON_ARRAY_APPEND(deleted_fields_array, '$', 'serial_number');
  900. SET old_vals = JSON_SET(old_vals, '$.serial_number', OLD.serial_number);
  901. END IF;
  902. IF OLD.zone_id IS NOT NULL THEN
  903. SET deleted_fields_array = JSON_ARRAY_APPEND(deleted_fields_array, '$', 'zone_id');
  904. SET old_vals = JSON_SET(old_vals, '$.zone_id', OLD.zone_id);
  905. END IF;
  906. IF OLD.zone_plus IS NOT NULL THEN
  907. SET deleted_fields_array = JSON_ARRAY_APPEND(deleted_fields_array, '$', 'zone_plus');
  908. SET old_vals = JSON_SET(old_vals, '$.zone_plus', OLD.zone_plus);
  909. END IF;
  910. IF OLD.zone_note IS NOT NULL THEN
  911. SET deleted_fields_array = JSON_ARRAY_APPEND(deleted_fields_array, '$', 'zone_note');
  912. SET old_vals = JSON_SET(old_vals, '$.zone_note', OLD.zone_note);
  913. END IF;
  914. IF OLD.status IS NOT NULL THEN
  915. SET deleted_fields_array = JSON_ARRAY_APPEND(deleted_fields_array, '$', 'status');
  916. SET old_vals = JSON_SET(old_vals, '$.status', OLD.status);
  917. END IF;
  918. IF OLD.last_audit IS NOT NULL THEN
  919. SET deleted_fields_array = JSON_ARRAY_APPEND(deleted_fields_array, '$', 'last_audit');
  920. SET old_vals = JSON_SET(old_vals, '$.last_audit', OLD.last_audit);
  921. END IF;
  922. IF OLD.last_audit_status IS NOT NULL THEN
  923. SET deleted_fields_array = JSON_ARRAY_APPEND(deleted_fields_array, '$', 'last_audit_status');
  924. SET old_vals = JSON_SET(old_vals, '$.last_audit_status', OLD.last_audit_status);
  925. END IF;
  926. IF OLD.price IS NOT NULL THEN
  927. SET deleted_fields_array = JSON_ARRAY_APPEND(deleted_fields_array, '$', 'price');
  928. SET old_vals = JSON_SET(old_vals, '$.price', OLD.price);
  929. END IF;
  930. IF OLD.purchase_date IS NOT NULL THEN
  931. SET deleted_fields_array = JSON_ARRAY_APPEND(deleted_fields_array, '$', 'purchase_date');
  932. SET old_vals = JSON_SET(old_vals, '$.purchase_date', OLD.purchase_date);
  933. END IF;
  934. IF OLD.warranty_until IS NOT NULL THEN
  935. SET deleted_fields_array = JSON_ARRAY_APPEND(deleted_fields_array, '$', 'warranty_until');
  936. SET old_vals = JSON_SET(old_vals, '$.warranty_until', OLD.warranty_until);
  937. END IF;
  938. IF OLD.expiry_date IS NOT NULL THEN
  939. SET deleted_fields_array = JSON_ARRAY_APPEND(deleted_fields_array, '$', 'expiry_date');
  940. SET old_vals = JSON_SET(old_vals, '$.expiry_date', OLD.expiry_date);
  941. END IF;
  942. IF OLD.quantity_available IS NOT NULL THEN
  943. SET deleted_fields_array = JSON_ARRAY_APPEND(deleted_fields_array, '$', 'quantity_available');
  944. SET old_vals = JSON_SET(old_vals, '$.quantity_available', OLD.quantity_available);
  945. END IF;
  946. IF OLD.quantity_total IS NOT NULL THEN
  947. SET deleted_fields_array = JSON_ARRAY_APPEND(deleted_fields_array, '$', 'quantity_total');
  948. SET old_vals = JSON_SET(old_vals, '$.quantity_total', OLD.quantity_total);
  949. END IF;
  950. IF OLD.quantity_used IS NOT NULL THEN
  951. SET deleted_fields_array = JSON_ARRAY_APPEND(deleted_fields_array, '$', 'quantity_used');
  952. SET old_vals = JSON_SET(old_vals, '$.quantity_used', OLD.quantity_used);
  953. END IF;
  954. IF OLD.supplier_id IS NOT NULL THEN
  955. SET deleted_fields_array = JSON_ARRAY_APPEND(deleted_fields_array, '$', 'supplier_id');
  956. SET old_vals = JSON_SET(old_vals, '$.supplier_id', OLD.supplier_id);
  957. END IF;
  958. IF OLD.lendable IS NOT NULL THEN
  959. SET deleted_fields_array = JSON_ARRAY_APPEND(deleted_fields_array, '$', 'lendable');
  960. SET old_vals = JSON_SET(old_vals, '$.lendable', OLD.lendable);
  961. END IF;
  962. IF OLD.minimum_role_for_lending IS NOT NULL THEN
  963. SET deleted_fields_array = JSON_ARRAY_APPEND(deleted_fields_array, '$', 'minimum_role_for_lending');
  964. SET old_vals = JSON_SET(old_vals, '$.minimum_role_for_lending', OLD.minimum_role_for_lending);
  965. END IF;
  966. IF OLD.lending_status IS NOT NULL THEN
  967. SET deleted_fields_array = JSON_ARRAY_APPEND(deleted_fields_array, '$', 'lending_status');
  968. SET old_vals = JSON_SET(old_vals, '$.lending_status', OLD.lending_status);
  969. END IF;
  970. IF OLD.current_borrower_id IS NOT NULL THEN
  971. SET deleted_fields_array = JSON_ARRAY_APPEND(deleted_fields_array, '$', 'current_borrower_id');
  972. SET old_vals = JSON_SET(old_vals, '$.current_borrower_id', OLD.current_borrower_id);
  973. END IF;
  974. IF OLD.due_date IS NOT NULL THEN
  975. SET deleted_fields_array = JSON_ARRAY_APPEND(deleted_fields_array, '$', 'due_date');
  976. SET old_vals = JSON_SET(old_vals, '$.due_date', OLD.due_date);
  977. END IF;
  978. IF OLD.previous_borrower_id IS NOT NULL THEN
  979. SET deleted_fields_array = JSON_ARRAY_APPEND(deleted_fields_array, '$', 'previous_borrower_id');
  980. SET old_vals = JSON_SET(old_vals, '$.previous_borrower_id', OLD.previous_borrower_id);
  981. END IF;
  982. IF OLD.audit_task_id IS NOT NULL THEN
  983. SET deleted_fields_array = JSON_ARRAY_APPEND(deleted_fields_array, '$', 'audit_task_id');
  984. SET old_vals = JSON_SET(old_vals, '$.audit_task_id', OLD.audit_task_id);
  985. END IF;
  986. IF OLD.no_scan IS NOT NULL THEN
  987. SET deleted_fields_array = JSON_ARRAY_APPEND(deleted_fields_array, '$', 'no_scan');
  988. SET old_vals = JSON_SET(old_vals, '$.no_scan', OLD.no_scan);
  989. END IF;
  990. IF OLD.notes IS NOT NULL THEN
  991. SET deleted_fields_array = JSON_ARRAY_APPEND(deleted_fields_array, '$', 'notes');
  992. SET old_vals = JSON_SET(old_vals, '$.notes', OLD.notes);
  993. END IF;
  994. IF OLD.additional_fields IS NOT NULL THEN
  995. SET deleted_fields_array = JSON_ARRAY_APPEND(deleted_fields_array, '$', 'additional_fields');
  996. SET old_vals = JSON_SET(old_vals, '$.additional_fields', OLD.additional_fields);
  997. END IF;
  998. -- Always capture metadata fields for restore
  999. IF OLD.created_date IS NOT NULL THEN
  1000. SET deleted_fields_array = JSON_ARRAY_APPEND(deleted_fields_array, '$', 'created_date');
  1001. SET old_vals = JSON_SET(old_vals, '$.created_date', OLD.created_date);
  1002. END IF;
  1003. IF OLD.created_by IS NOT NULL THEN
  1004. SET deleted_fields_array = JSON_ARRAY_APPEND(deleted_fields_array, '$', 'created_by');
  1005. SET old_vals = JSON_SET(old_vals, '$.created_by', OLD.created_by);
  1006. END IF;
  1007. IF OLD.last_modified_date IS NOT NULL THEN
  1008. SET deleted_fields_array = JSON_ARRAY_APPEND(deleted_fields_array, '$', 'last_modified_date');
  1009. SET old_vals = JSON_SET(old_vals, '$.last_modified_date', OLD.last_modified_date);
  1010. END IF;
  1011. IF OLD.last_modified_by IS NOT NULL THEN
  1012. SET deleted_fields_array = JSON_ARRAY_APPEND(deleted_fields_array, '$', 'last_modified_by');
  1013. SET old_vals = JSON_SET(old_vals, '$.last_modified_by', OLD.last_modified_by);
  1014. END IF;
  1015. -- Log the DELETE with only non-NULL fields
  1016. INSERT INTO asset_change_log (
  1017. table_name, action, record_id, changed_fields, old_values,
  1018. changed_by_id, changed_by_username
  1019. )
  1020. VALUES (
  1021. 'assets',
  1022. 'DELETE',
  1023. OLD.id,
  1024. deleted_fields_array,
  1025. old_vals,
  1026. @current_user_id,
  1027. username
  1028. );
  1029. END//
  1030. -- ============================================
  1031. -- BUSINESS LOGIC TRIGGERS
  1032. -- ============================================
  1033. -- Trigger: Prevent lending non-lendable assets
  1034. DROP TRIGGER IF EXISTS prevent_lend_non_lendable_assets//
  1035. CREATE TRIGGER prevent_lend_non_lendable_assets
  1036. BEFORE UPDATE ON assets
  1037. FOR EACH ROW
  1038. BEGIN
  1039. -- Check if trying to set lending_status to any borrowed state on a non-lendable asset
  1040. IF (NEW.lendable = FALSE OR NEW.lendable IS NULL) AND
  1041. NEW.lending_status IN ('Borrowed', 'Deployed', 'Overdue') AND
  1042. (OLD.lending_status NOT IN ('Borrowed', 'Deployed', 'Overdue') OR OLD.lending_status IS NULL) THEN
  1043. SIGNAL SQLSTATE '45000'
  1044. SET MESSAGE_TEXT = 'Cannot lend asset that is marked as non-lendable. Set lendable=TRUE first.';
  1045. END IF;
  1046. END//
  1047. -- Trigger: Prevent deleting borrowed items
  1048. DROP TRIGGER IF EXISTS prevent_delete_borrowed_assets//
  1049. CREATE TRIGGER prevent_delete_borrowed_assets
  1050. BEFORE DELETE ON assets
  1051. FOR EACH ROW
  1052. BEGIN
  1053. IF OLD.lending_status IN ('Borrowed', 'Deployed', 'Overdue') THEN
  1054. SIGNAL SQLSTATE '45000'
  1055. SET MESSAGE_TEXT = 'Cannot delete asset that is currently borrowed or deployed, maybe update to retired or unmanaged before';
  1056. END IF;
  1057. END//
  1058. -- Trigger: Validate zone_plus requires zone_note for 'Clarify'
  1059. DROP TRIGGER IF EXISTS validate_zone_plus_insert//
  1060. CREATE TRIGGER validate_zone_plus_insert
  1061. BEFORE INSERT ON assets
  1062. FOR EACH ROW
  1063. BEGIN
  1064. IF NEW.zone_plus = 'Clarify' AND (NEW.zone_note IS NULL OR NEW.zone_note = '') THEN
  1065. SIGNAL SQLSTATE '45000'
  1066. SET MESSAGE_TEXT = 'zone_note is required when zone_plus is set to Clarify';
  1067. END IF;
  1068. END//
  1069. DROP TRIGGER IF EXISTS validate_zone_plus_update//
  1070. CREATE TRIGGER validate_zone_plus_update
  1071. BEFORE UPDATE ON assets
  1072. FOR EACH ROW
  1073. BEGIN
  1074. IF NEW.zone_plus = 'Clarify' AND (NEW.zone_note IS NULL OR NEW.zone_note = '') THEN
  1075. SIGNAL SQLSTATE '45000'
  1076. SET MESSAGE_TEXT = 'zone_note is required when zone_plus is set to Clarify';
  1077. END IF;
  1078. END//
  1079. -- ============================================
  1080. -- BORROWERS TABLE TRIGGERS
  1081. -- ============================================
  1082. -- Trigger: Auto-populate added_by on INSERT
  1083. DROP TRIGGER IF EXISTS borrowers_before_insert_meta//
  1084. CREATE TRIGGER borrowers_before_insert_meta
  1085. BEFORE INSERT ON borrowers
  1086. FOR EACH ROW
  1087. BEGIN
  1088. IF NEW.added_by IS NULL AND @current_user_id IS NOT NULL THEN
  1089. SET NEW.added_by = @current_user_id;
  1090. END IF;
  1091. END//
  1092. -- Trigger: Auto-populate last_unban_by on UPDATE when unbanning
  1093. DROP TRIGGER IF EXISTS borrowers_before_update_meta//
  1094. CREATE TRIGGER borrowers_before_update_meta
  1095. BEFORE UPDATE ON borrowers
  1096. FOR EACH ROW
  1097. BEGIN
  1098. IF OLD.banned = TRUE AND NEW.banned = FALSE THEN
  1099. IF NEW.last_unban_by IS NULL AND @current_user_id IS NOT NULL THEN
  1100. SET NEW.last_unban_by = @current_user_id;
  1101. END IF;
  1102. IF NEW.last_unban_date IS NULL THEN
  1103. SET NEW.last_unban_date = CURDATE();
  1104. END IF;
  1105. END IF;
  1106. END//
  1107. -- ============================================
  1108. -- LENDING HISTORY TRIGGERS
  1109. -- ============================================
  1110. -- Trigger: Auto-populate checked_out_by on INSERT
  1111. DROP TRIGGER IF EXISTS lending_history_before_insert_meta//
  1112. CREATE TRIGGER lending_history_before_insert_meta
  1113. BEFORE INSERT ON lending_history
  1114. FOR EACH ROW
  1115. BEGIN
  1116. IF NEW.checked_out_by IS NULL AND @current_user_id IS NOT NULL THEN
  1117. SET NEW.checked_out_by = @current_user_id;
  1118. END IF;
  1119. END//
  1120. -- Trigger: Auto-populate checked_in_by on UPDATE when returning
  1121. DROP TRIGGER IF EXISTS lending_history_before_update_meta//
  1122. CREATE TRIGGER lending_history_before_update_meta
  1123. BEFORE UPDATE ON lending_history
  1124. FOR EACH ROW
  1125. BEGIN
  1126. IF OLD.return_date IS NULL AND NEW.return_date IS NOT NULL THEN
  1127. IF NEW.checked_in_by IS NULL AND @current_user_id IS NOT NULL THEN
  1128. SET NEW.checked_in_by = @current_user_id;
  1129. END IF;
  1130. END IF;
  1131. END//
  1132. -- ============================================
  1133. -- ISSUE TRACKER TRIGGERS
  1134. -- ============================================
  1135. -- Trigger: Auto-populate reported_by on INSERT
  1136. DROP TRIGGER IF EXISTS issue_tracker_before_insert_meta//
  1137. CREATE TRIGGER issue_tracker_before_insert_meta
  1138. BEFORE INSERT ON issue_tracker
  1139. FOR EACH ROW
  1140. BEGIN
  1141. IF NEW.reported_by IS NULL AND @current_user_id IS NOT NULL THEN
  1142. SET NEW.reported_by = @current_user_id;
  1143. END IF;
  1144. END//
  1145. -- Trigger: Validate issue_tracker business rules on INSERT
  1146. DROP TRIGGER IF EXISTS validate_issue_tracker_insert//
  1147. CREATE TRIGGER validate_issue_tracker_insert
  1148. BEFORE INSERT ON issue_tracker
  1149. FOR EACH ROW
  1150. BEGIN
  1151. -- Clarify solution requires solution_plus
  1152. IF NEW.solution = 'Clarify' AND (NEW.solution_plus IS NULL OR NEW.solution_plus = '') THEN
  1153. SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'solution_plus is required when solution is set to Clarify';
  1154. END IF;
  1155. -- Replacement solution requires replacement_asset_id
  1156. IF NEW.solution = 'Replaced' AND NEW.replacement_asset_id IS NULL THEN
  1157. SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'replacement_asset_id is required when solution is set to Replaced';
  1158. END IF;
  1159. -- Asset Issue requires asset_id
  1160. IF NEW.issue_type = 'Asset Issue' AND NEW.asset_id IS NULL THEN
  1161. SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'asset_id is required for Asset Issue type';
  1162. END IF;
  1163. -- Borrower Issue requires borrower_id
  1164. IF NEW.issue_type = 'Borrower Issue' AND NEW.borrower_id IS NULL THEN
  1165. SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'borrower_id is required for Borrower Issue type';
  1166. END IF;
  1167. -- Auto-set resolved_date when status becomes Resolved or Closed
  1168. IF NEW.status IN ('Resolved', 'Closed') AND NEW.resolved_date IS NULL THEN
  1169. SET NEW.resolved_date = NOW();
  1170. END IF;
  1171. -- Auto-set resolved_by when status becomes Resolved or Closed
  1172. IF NEW.status IN ('Resolved', 'Closed') AND NEW.resolved_by IS NULL AND @current_user_id IS NOT NULL THEN
  1173. SET NEW.resolved_by = @current_user_id;
  1174. END IF;
  1175. END//
  1176. -- Trigger: Validate issue_tracker business rules on UPDATE
  1177. DROP TRIGGER IF EXISTS validate_issue_tracker_update//
  1178. CREATE TRIGGER validate_issue_tracker_update
  1179. BEFORE UPDATE ON issue_tracker
  1180. FOR EACH ROW
  1181. BEGIN
  1182. -- Clarify solution requires solution_plus
  1183. IF NEW.solution = 'Clarify' AND (NEW.solution_plus IS NULL OR NEW.solution_plus = '') THEN
  1184. SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'solution_plus is required when solution is set to Clarify';
  1185. END IF;
  1186. -- Replacement solution requires replacement_asset_id
  1187. IF NEW.solution = 'Replaced' AND NEW.replacement_asset_id IS NULL THEN
  1188. SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'replacement_asset_id is required when solution is set to Replaced';
  1189. END IF;
  1190. -- Auto-set resolved_date when status changes to Resolved or Closed
  1191. IF OLD.status NOT IN ('Resolved', 'Closed') AND NEW.status IN ('Resolved', 'Closed') THEN
  1192. SET NEW.resolved_date = NOW();
  1193. IF @current_user_id IS NOT NULL THEN
  1194. SET NEW.resolved_by = @current_user_id;
  1195. END IF;
  1196. END IF;
  1197. -- Clear resolved_date when status changes away from Resolved/Closed
  1198. IF OLD.status IN ('Resolved', 'Closed') AND NEW.status NOT IN ('Resolved', 'Closed') THEN
  1199. SET NEW.resolved_date = NULL;
  1200. SET NEW.resolved_by = NULL;
  1201. END IF;
  1202. END//
  1203. -- Trigger: Auto-resolve issue before DELETE
  1204. DROP TRIGGER IF EXISTS issue_tracker_before_delete//
  1205. CREATE TRIGGER issue_tracker_before_delete
  1206. BEFORE DELETE ON issue_tracker
  1207. FOR EACH ROW
  1208. BEGIN
  1209. -- If issue is not already resolved/closed, update it before deletion
  1210. IF OLD.status NOT IN ('Resolved', 'Closed') THEN
  1211. -- Can't UPDATE in a BEFORE DELETE trigger, so we just ensure it was marked resolved
  1212. -- This will prevent accidental deletion of open issues
  1213. SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Cannot delete open issues. Please close or resolve the issue first.';
  1214. END IF;
  1215. END//
  1216. -- Trigger: Log issue_tracker INSERT operations
  1217. DROP TRIGGER IF EXISTS issue_tracker_after_insert_log//
  1218. CREATE TRIGGER issue_tracker_after_insert_log
  1219. AFTER INSERT ON issue_tracker
  1220. FOR EACH ROW
  1221. BEGIN
  1222. DECLARE set_fields JSON DEFAULT JSON_ARRAY();
  1223. DECLARE new_vals JSON DEFAULT JSON_OBJECT();
  1224. -- Build JSON of non-NULL inserted fields
  1225. IF NEW.issue_type IS NOT NULL THEN
  1226. SET set_fields = JSON_ARRAY_APPEND(set_fields, '$', 'issue_type');
  1227. SET new_vals = JSON_SET(new_vals, '$.issue_type', NEW.issue_type);
  1228. END IF;
  1229. IF NEW.asset_id IS NOT NULL THEN
  1230. SET set_fields = JSON_ARRAY_APPEND(set_fields, '$', 'asset_id');
  1231. SET new_vals = JSON_SET(new_vals, '$.asset_id', NEW.asset_id);
  1232. END IF;
  1233. IF NEW.borrower_id IS NOT NULL THEN
  1234. SET set_fields = JSON_ARRAY_APPEND(set_fields, '$', 'borrower_id');
  1235. SET new_vals = JSON_SET(new_vals, '$.borrower_id', NEW.borrower_id);
  1236. END IF;
  1237. IF NEW.title IS NOT NULL THEN
  1238. SET set_fields = JSON_ARRAY_APPEND(set_fields, '$', 'title');
  1239. SET new_vals = JSON_SET(new_vals, '$.title', NEW.title);
  1240. END IF;
  1241. IF NEW.severity IS NOT NULL THEN
  1242. SET set_fields = JSON_ARRAY_APPEND(set_fields, '$', 'severity');
  1243. SET new_vals = JSON_SET(new_vals, '$.severity', NEW.severity);
  1244. END IF;
  1245. IF NEW.status IS NOT NULL THEN
  1246. SET set_fields = JSON_ARRAY_APPEND(set_fields, '$', 'status');
  1247. SET new_vals = JSON_SET(new_vals, '$.status', NEW.status);
  1248. END IF;
  1249. INSERT INTO issue_tracker_change_log (issue_id, change_type, changed_fields, new_values, changed_by)
  1250. VALUES (NEW.id, 'INSERT', set_fields, new_vals, COALESCE(@current_user_id, NEW.reported_by));
  1251. END//
  1252. -- Trigger: Log issue_tracker UPDATE operations
  1253. DROP TRIGGER IF EXISTS issue_tracker_after_update_log//
  1254. CREATE TRIGGER issue_tracker_after_update_log
  1255. AFTER UPDATE ON issue_tracker
  1256. FOR EACH ROW
  1257. BEGIN
  1258. DECLARE changed_fields JSON DEFAULT JSON_ARRAY();
  1259. DECLARE old_vals JSON DEFAULT JSON_OBJECT();
  1260. DECLARE new_vals JSON DEFAULT JSON_OBJECT();
  1261. -- Track all changed fields
  1262. IF OLD.status <=> NEW.status IS FALSE THEN
  1263. SET changed_fields = JSON_ARRAY_APPEND(changed_fields, '$', 'status');
  1264. SET old_vals = JSON_SET(old_vals, '$.status', OLD.status);
  1265. SET new_vals = JSON_SET(new_vals, '$.status', NEW.status);
  1266. END IF;
  1267. IF OLD.severity <=> NEW.severity IS FALSE THEN
  1268. SET changed_fields = JSON_ARRAY_APPEND(changed_fields, '$', 'severity');
  1269. SET old_vals = JSON_SET(old_vals, '$.severity', OLD.severity);
  1270. SET new_vals = JSON_SET(new_vals, '$.severity', NEW.severity);
  1271. END IF;
  1272. IF OLD.priority <=> NEW.priority IS FALSE THEN
  1273. SET changed_fields = JSON_ARRAY_APPEND(changed_fields, '$', 'priority');
  1274. SET old_vals = JSON_SET(old_vals, '$.priority', OLD.priority);
  1275. SET new_vals = JSON_SET(new_vals, '$.priority', NEW.priority);
  1276. END IF;
  1277. IF OLD.solution <=> NEW.solution IS FALSE THEN
  1278. SET changed_fields = JSON_ARRAY_APPEND(changed_fields, '$', 'solution');
  1279. SET old_vals = JSON_SET(old_vals, '$.solution', OLD.solution);
  1280. SET new_vals = JSON_SET(new_vals, '$.solution', NEW.solution);
  1281. END IF;
  1282. IF OLD.assigned_to <=> NEW.assigned_to IS FALSE THEN
  1283. SET changed_fields = JSON_ARRAY_APPEND(changed_fields, '$', 'assigned_to');
  1284. SET old_vals = JSON_SET(old_vals, '$.assigned_to', OLD.assigned_to);
  1285. SET new_vals = JSON_SET(new_vals, '$.assigned_to', NEW.assigned_to);
  1286. END IF;
  1287. IF OLD.resolved_by <=> NEW.resolved_by IS FALSE THEN
  1288. SET changed_fields = JSON_ARRAY_APPEND(changed_fields, '$', 'resolved_by');
  1289. SET old_vals = JSON_SET(old_vals, '$.resolved_by', OLD.resolved_by);
  1290. SET new_vals = JSON_SET(new_vals, '$.resolved_by', NEW.resolved_by);
  1291. END IF;
  1292. -- Only log if something actually changed
  1293. IF JSON_LENGTH(changed_fields) > 0 THEN
  1294. INSERT INTO issue_tracker_change_log (issue_id, change_type, changed_fields, old_values, new_values, changed_by)
  1295. VALUES (NEW.id, 'UPDATE', changed_fields, old_vals, new_vals, COALESCE(@current_user_id, OLD.reported_by));
  1296. END IF;
  1297. END//
  1298. -- Trigger: Log issue_tracker DELETE operations
  1299. DROP TRIGGER IF EXISTS issue_tracker_after_delete_log//
  1300. CREATE TRIGGER issue_tracker_after_delete_log
  1301. AFTER DELETE ON issue_tracker
  1302. FOR EACH ROW
  1303. BEGIN
  1304. DECLARE deleted_fields JSON DEFAULT JSON_ARRAY();
  1305. DECLARE old_vals JSON DEFAULT JSON_OBJECT();
  1306. -- Log all fields from deleted issue
  1307. IF OLD.issue_type IS NOT NULL THEN
  1308. SET deleted_fields = JSON_ARRAY_APPEND(deleted_fields, '$', 'issue_type');
  1309. SET old_vals = JSON_SET(old_vals, '$.issue_type', OLD.issue_type);
  1310. END IF;
  1311. IF OLD.asset_id IS NOT NULL THEN
  1312. SET deleted_fields = JSON_ARRAY_APPEND(deleted_fields, '$', 'asset_id');
  1313. SET old_vals = JSON_SET(old_vals, '$.asset_id', OLD.asset_id);
  1314. END IF;
  1315. IF OLD.title IS NOT NULL THEN
  1316. SET deleted_fields = JSON_ARRAY_APPEND(deleted_fields, '$', 'title');
  1317. SET old_vals = JSON_SET(old_vals, '$.title', OLD.title);
  1318. END IF;
  1319. IF OLD.status IS NOT NULL THEN
  1320. SET deleted_fields = JSON_ARRAY_APPEND(deleted_fields, '$', 'status');
  1321. SET old_vals = JSON_SET(old_vals, '$.status', OLD.status);
  1322. END IF;
  1323. IF OLD.solution IS NOT NULL THEN
  1324. SET deleted_fields = JSON_ARRAY_APPEND(deleted_fields, '$', 'solution');
  1325. SET old_vals = JSON_SET(old_vals, '$.solution', OLD.solution);
  1326. END IF;
  1327. INSERT INTO issue_tracker_change_log (issue_id, change_type, changed_fields, old_values, changed_by)
  1328. VALUES (OLD.id, 'DELETE', deleted_fields, old_vals, COALESCE(@current_user_id, OLD.reported_by));
  1329. END//
  1330. -- Trigger: Auto-detect asset issues when status becomes problematic
  1331. DROP TRIGGER IF EXISTS auto_detect_asset_issues//
  1332. CREATE TRIGGER auto_detect_asset_issues
  1333. AFTER UPDATE ON assets
  1334. FOR EACH ROW
  1335. BEGIN
  1336. DECLARE issue_title VARCHAR(255);
  1337. DECLARE issue_description TEXT;
  1338. DECLARE issue_severity ENUM('Critical', 'High', 'Medium', 'Low');
  1339. DECLARE detection_trigger_name VARCHAR(100);
  1340. -- Check for lending_status changes to problematic states
  1341. IF (OLD.lending_status IS NULL OR OLD.lending_status != NEW.lending_status)
  1342. AND NEW.lending_status IN ('Overdue', 'Illegally Handed Out', 'Stolen') THEN
  1343. -- Determine issue details based on lending_status
  1344. CASE NEW.lending_status
  1345. WHEN 'Overdue' THEN
  1346. SET issue_title = CONCAT('Asset Overdue: ', COALESCE(NEW.name, NEW.asset_tag, CAST(NEW.asset_numeric_id AS CHAR)));
  1347. SET issue_description = CONCAT('Asset lending status changed to Overdue. Asset: ', NEW.asset_tag,
  1348. CASE WHEN NEW.name IS NOT NULL THEN CONCAT(' (', NEW.name, ')') ELSE '' END);
  1349. SET issue_severity = 'High';
  1350. SET detection_trigger_name = 'LENDING_OVERDUE';
  1351. WHEN 'Illegally Handed Out' THEN
  1352. SET issue_title = CONCAT('Asset Illegally Handed Out: ', COALESCE(NEW.name, NEW.asset_tag, CAST(NEW.asset_numeric_id AS CHAR)));
  1353. SET issue_description = CONCAT('Asset lending status changed to Illegally Handed Out. Asset: ', NEW.asset_tag,
  1354. CASE WHEN NEW.name IS NOT NULL THEN CONCAT(' (', NEW.name, ')') ELSE '' END);
  1355. SET issue_severity = 'Critical';
  1356. SET detection_trigger_name = 'LENDING_ILLEGAL';
  1357. WHEN 'Stolen' THEN
  1358. SET issue_title = CONCAT('Asset Stolen: ', COALESCE(NEW.name, NEW.asset_tag, CAST(NEW.asset_numeric_id AS CHAR)));
  1359. SET issue_description = CONCAT('Asset lending status changed to Stolen (14+ days overdue). Asset: ', NEW.asset_tag,
  1360. CASE WHEN NEW.name IS NOT NULL THEN CONCAT(' (', NEW.name, ')') ELSE '' END);
  1361. SET issue_severity = 'Critical';
  1362. SET detection_trigger_name = 'LENDING_STOLEN';
  1363. END CASE;
  1364. -- Insert the auto-detected issue
  1365. INSERT INTO issue_tracker (
  1366. issue_type, asset_id, title, description, severity, priority, status,
  1367. reported_by, auto_detected, detection_trigger, created_date
  1368. )
  1369. VALUES (
  1370. 'Asset Issue', NEW.id, issue_title, issue_description, issue_severity, 'Urgent', 'Open',
  1371. COALESCE(@current_user_id, 1), TRUE, detection_trigger_name, NOW()
  1372. );
  1373. END IF;
  1374. -- Check for status changes to problematic states
  1375. IF OLD.status != NEW.status AND NEW.status IN ('Attention', 'Faulty', 'Missing', 'Retired', 'In Repair', 'Expired') THEN
  1376. -- Determine issue details based on status
  1377. CASE NEW.status
  1378. WHEN 'Attention' THEN
  1379. SET issue_title = CONCAT('Asset Needs Attention: ', COALESCE(NEW.name, NEW.asset_tag, NEW.asset_numeric_id));
  1380. SET issue_description = CONCAT('Asset status changed to Attention. Asset: ', NEW.asset_numeric_id, CASE WHEN NEW.name IS NOT NULL THEN CONCAT(' (', NEW.name, ')') ELSE '' END);
  1381. SET issue_severity = 'Medium';
  1382. SET detection_trigger_name = 'STATUS_ATTENTION';
  1383. WHEN 'Faulty' THEN
  1384. SET issue_title = CONCAT('Asset Faulty: ', COALESCE(NEW.name, NEW.asset_tag, NEW.asset_numeric_id));
  1385. SET issue_description = CONCAT('Asset status changed to Faulty. Asset: ', NEW.asset_numeric_id, CASE WHEN NEW.name IS NOT NULL THEN CONCAT(' (', NEW.name, ')') ELSE '' END);
  1386. SET issue_severity = 'High';
  1387. SET detection_trigger_name = 'STATUS_FAULTY';
  1388. WHEN 'Missing' THEN
  1389. SET issue_title = CONCAT('Asset Missing: ', COALESCE(NEW.name, NEW.asset_tag, NEW.asset_numeric_id));
  1390. SET issue_description = CONCAT('Asset status changed to Missing. Asset: ', NEW.asset_numeric_id, CASE WHEN NEW.name IS NOT NULL THEN CONCAT(' (', NEW.name, ')') ELSE '' END);
  1391. SET issue_severity = 'Critical';
  1392. SET detection_trigger_name = 'STATUS_MISSING';
  1393. WHEN 'Retired' THEN
  1394. SET issue_title = CONCAT('Asset Retired: ', COALESCE(NEW.name, NEW.asset_tag, NEW.asset_numeric_id));
  1395. SET issue_description = CONCAT('Asset status changed to Retired. Asset: ', NEW.asset_numeric_id, CASE WHEN NEW.name IS NOT NULL THEN CONCAT(' (', NEW.name, ')') ELSE '' END);
  1396. SET issue_severity = 'Low';
  1397. SET detection_trigger_name = 'STATUS_RETIRED';
  1398. WHEN 'In Repair' THEN
  1399. SET issue_title = CONCAT('Asset In Repair: ', COALESCE(NEW.name, NEW.asset_tag, NEW.asset_numeric_id));
  1400. SET issue_description = CONCAT('Asset status changed to In Repair. Asset: ', NEW.asset_numeric_id, CASE WHEN NEW.name IS NOT NULL THEN CONCAT(' (', NEW.name, ')') ELSE '' END);
  1401. SET issue_severity = 'Medium';
  1402. SET detection_trigger_name = 'STATUS_IN_REPAIR';
  1403. WHEN 'Expired' THEN
  1404. SET issue_title = CONCAT('Asset Expired: ', COALESCE(NEW.name, NEW.asset_tag, NEW.asset_numeric_id));
  1405. SET issue_description = CONCAT('Asset status changed to Expired. Asset: ', NEW.asset_numeric_id, CASE WHEN NEW.name IS NOT NULL THEN CONCAT(' (', NEW.name, ')') ELSE '' END);
  1406. SET issue_severity = 'Medium';
  1407. SET detection_trigger_name = 'STATUS_EXPIRED';
  1408. END CASE;
  1409. -- Insert the auto-detected issue
  1410. INSERT INTO issue_tracker (
  1411. issue_type, asset_id, title, description, severity, priority, status,
  1412. reported_by, auto_detected, detection_trigger, created_date
  1413. )
  1414. VALUES (
  1415. 'Asset Issue', NEW.id, issue_title, issue_description, issue_severity, 'Normal', 'Open',
  1416. COALESCE(@current_user_id, 1), TRUE, detection_trigger_name, NOW()
  1417. );
  1418. END IF;
  1419. -- Auto-resolve issues when status becomes Good again
  1420. IF OLD.status != NEW.status AND NEW.status = 'Good' AND OLD.status IN ('Faulty', 'Missing', 'In Repair', 'Expired') THEN
  1421. UPDATE issue_tracker
  1422. SET status = 'Resolved',
  1423. solution = 'Automatically Fixed',
  1424. solution_plus = CONCAT('Asset status automatically changed from ', OLD.status, ' to Good'),
  1425. resolved_date = NOW(),
  1426. resolved_by = COALESCE(@current_user_id, 1)
  1427. WHERE asset_id = NEW.id
  1428. AND status IN ('Open', 'In Progress')
  1429. AND auto_detected = TRUE
  1430. AND detection_trigger IN ('STATUS_FAULTY', 'STATUS_MISSING', 'STATUS_IN_REPAIR', 'STATUS_EXPIRED');
  1431. END IF;
  1432. -- Auto-resolve overdue/stolen/illegal issues when item is returned (lending_status becomes Available)
  1433. IF (OLD.lending_status IS NULL OR OLD.lending_status != NEW.lending_status)
  1434. AND NEW.lending_status = 'Available'
  1435. AND OLD.lending_status IN ('Overdue', 'Illegally Handed Out', 'Stolen') THEN
  1436. UPDATE issue_tracker
  1437. SET status = 'Resolved',
  1438. solution = 'Items Returned',
  1439. solution_plus = CONCAT('Asset was returned - lending status changed from ', OLD.lending_status, ' to Available'),
  1440. resolved_date = NOW(),
  1441. resolved_by = COALESCE(@current_user_id, 1)
  1442. WHERE asset_id = NEW.id
  1443. AND status IN ('Open', 'In Progress')
  1444. AND auto_detected = TRUE
  1445. AND detection_trigger IN ('LENDING_OVERDUE', 'LENDING_ILLEGAL', 'LENDING_STOLEN');
  1446. END IF;
  1447. END//
  1448. -- Trigger: Auto-detect borrower issues when borrower is banned
  1449. DROP TRIGGER IF EXISTS auto_detect_borrower_issues//
  1450. CREATE TRIGGER auto_detect_borrower_issues
  1451. AFTER UPDATE ON borrowers
  1452. FOR EACH ROW
  1453. BEGIN
  1454. DECLARE issue_title VARCHAR(255);
  1455. DECLARE issue_description TEXT;
  1456. -- Auto-detect when borrower gets banned
  1457. IF OLD.banned = FALSE AND NEW.banned = TRUE THEN
  1458. SET issue_title = CONCAT('Borrower Banned: ', NEW.name);
  1459. SET issue_description = CONCAT('Borrower has been banned. Name: ', NEW.name, CASE WHEN NEW.unban_fine > 0 THEN CONCAT(', Unban Fine: $', NEW.unban_fine) ELSE '' END);
  1460. INSERT INTO issue_tracker (
  1461. issue_type, borrower_id, title, description, severity, priority, status,
  1462. reported_by, auto_detected, detection_trigger, created_date
  1463. )
  1464. VALUES (
  1465. 'Borrower Issue', NEW.id, issue_title, issue_description, 'High', 'Normal', 'Open',
  1466. COALESCE(@current_user_id, 1), TRUE, 'BORROWER_BANNED', NOW()
  1467. );
  1468. END IF;
  1469. -- Auto-resolve when borrower gets unbanned
  1470. IF OLD.banned = TRUE AND NEW.banned = FALSE THEN
  1471. UPDATE issue_tracker
  1472. SET status = 'Resolved',
  1473. solution = 'Items Returned',
  1474. solution_plus = CONCAT('Borrower unbanned on ', COALESCE(NEW.last_unban_date, CURDATE()), CASE WHEN NEW.last_unban_by IS NOT NULL THEN CONCAT(' by user ID ', NEW.last_unban_by) ELSE '' END),
  1475. resolved_date = NOW(),
  1476. resolved_by = COALESCE(@current_user_id, NEW.last_unban_by, 1)
  1477. WHERE borrower_id = NEW.id
  1478. AND status IN ('Open', 'In Progress')
  1479. AND auto_detected = TRUE
  1480. AND detection_trigger = 'BORROWER_BANNED';
  1481. END IF;
  1482. END//
  1483. -- ============================================
  1484. -- PHYSICAL AUDIT TRIGGERS (Simplified)
  1485. -- ============================================
  1486. -- Trigger: Auto-calculate assets_expected when starting full-zone audit
  1487. DROP TRIGGER IF EXISTS calculate_assets_expected//
  1488. CREATE TRIGGER calculate_assets_expected
  1489. BEFORE INSERT ON physical_audits
  1490. FOR EACH ROW
  1491. BEGIN
  1492. DECLARE expected_count INT DEFAULT 0;
  1493. DECLARE v_timeout INT;
  1494. -- For full-zone audits, calculate expected assets in the zone
  1495. IF NEW.audit_type = 'full-zone' AND NEW.zone_id IS NOT NULL THEN
  1496. SELECT COUNT(*) INTO expected_count
  1497. FROM assets
  1498. WHERE zone_id = NEW.zone_id
  1499. AND status NOT IN ('Missing', 'Retired');
  1500. SET NEW.assets_expected = expected_count;
  1501. END IF;
  1502. -- Set timeout from zone settings if not specified
  1503. IF NEW.timeout_minutes IS NULL AND NEW.zone_id IS NOT NULL THEN
  1504. SELECT audit_timeout_minutes INTO v_timeout
  1505. FROM zones
  1506. WHERE id = NEW.zone_id
  1507. LIMIT 1;
  1508. IF v_timeout IS NOT NULL THEN
  1509. SET NEW.timeout_minutes = v_timeout;
  1510. END IF;
  1511. END IF;
  1512. END//
  1513. -- Trigger: Auto-populate audited_by from session user
  1514. DROP TRIGGER IF EXISTS physical_audit_logs_before_insert_meta//
  1515. CREATE TRIGGER physical_audit_logs_before_insert_meta
  1516. BEFORE INSERT ON physical_audit_logs
  1517. FOR EACH ROW
  1518. BEGIN
  1519. -- Auto-populate audited_by from session variable if not provided
  1520. IF NEW.audited_by IS NULL OR NEW.audited_by = 0 THEN
  1521. SET NEW.audited_by = COALESCE(@current_user_id, 1);
  1522. END IF;
  1523. END//
  1524. -- Trigger: Update assets_found counter when asset is audited
  1525. DROP TRIGGER IF EXISTS update_assets_found//
  1526. CREATE TRIGGER update_assets_found
  1527. AFTER INSERT ON physical_audit_logs
  1528. FOR EACH ROW
  1529. BEGIN
  1530. UPDATE physical_audits
  1531. SET assets_found = assets_found + 1
  1532. WHERE id = NEW.physical_audit_id;
  1533. END//
  1534. -- Trigger: Simple audit issue detection
  1535. DROP TRIGGER IF EXISTS auto_detect_audit_issues//
  1536. CREATE TRIGGER auto_detect_audit_issues
  1537. AFTER UPDATE ON physical_audits
  1538. FOR EACH ROW
  1539. BEGIN
  1540. DECLARE missing_count INT DEFAULT 0;
  1541. DECLARE zone_name VARCHAR(200);
  1542. -- Only process when audit status changes to completed states
  1543. IF OLD.status = 'in-progress' AND NEW.status IN ('all-good', 'attention', 'timeout') THEN
  1544. -- Get zone name for reporting
  1545. IF NEW.zone_id IS NOT NULL THEN
  1546. SELECT zone_name INTO zone_name FROM zones WHERE id = NEW.zone_id;
  1547. END IF;
  1548. -- For full-zone audits, check for missing assets
  1549. IF NEW.audit_type = 'full-zone' AND NEW.assets_expected IS NOT NULL THEN
  1550. SET missing_count = GREATEST(0, NEW.assets_expected - NEW.assets_found);
  1551. END IF;
  1552. -- Create issue for missing assets
  1553. IF missing_count > 0 THEN
  1554. INSERT INTO issue_tracker (
  1555. issue_type, title, description, severity, priority, status,
  1556. reported_by, auto_detected, detection_trigger, created_date, notes
  1557. )
  1558. VALUES (
  1559. 'System Issue',
  1560. CONCAT('Audit: Missing Assets in ', COALESCE(zone_name, 'Unknown Zone')),
  1561. CONCAT('Full zone audit completed with ', missing_count, ' missing assets. Expected: ', NEW.assets_expected, ', Found: ', NEW.assets_found, '. Audit ID: ', NEW.id),
  1562. CASE WHEN missing_count >= 5 THEN 'Critical' WHEN missing_count >= 2 THEN 'High' ELSE 'Medium' END,
  1563. 'High', 'Open',
  1564. NEW.started_by, TRUE, 'AUDIT_MISSING_ASSETS', NOW(),
  1565. CONCAT('Physical Audit ID: ', NEW.id, ' in zone: ', COALESCE(zone_name, NEW.zone_id))
  1566. );
  1567. END IF;
  1568. END IF;
  1569. END//
  1570. -- Trigger: Basic asset audit update
  1571. DROP TRIGGER IF EXISTS update_asset_from_audit//
  1572. CREATE TRIGGER update_asset_from_audit
  1573. AFTER INSERT ON physical_audit_logs
  1574. FOR EACH ROW
  1575. BEGIN
  1576. DECLARE current_status VARCHAR(100);
  1577. -- Update asset's last_audit date
  1578. UPDATE assets
  1579. SET last_audit = DATE(NEW.audit_date),
  1580. last_audit_status = NEW.status_found
  1581. WHERE id = NEW.asset_id;
  1582. -- Compare found status with current asset status
  1583. SELECT status INTO current_status FROM assets WHERE id = NEW.asset_id LIMIT 1;
  1584. IF NEW.status_found != current_status THEN
  1585. UPDATE assets
  1586. SET status = NEW.status_found
  1587. WHERE id = NEW.asset_id;
  1588. END IF;
  1589. END//
  1590. DELIMITER ;
  1591. -- End of clean triggers file
  1592. -- ============================================
  1593. -- USAGE NOTES
  1594. -- ============================================
  1595. /*
  1596. HOW TO USE FROM YOUR RUST PROXY:
  1597. Before any INSERT/UPDATE/DELETE operation, set the user context:
  1598. SET @current_user_id = 123;
  1599. Then execute your query normally. The triggers will automatically:
  1600. 1. Auto-populate user tracking fields (if not explicitly provided):
  1601. • assets.created_by (on INSERT)
  1602. • assets.last_modified_by (on UPDATE)
  1603. • borrowers.added_by (on INSERT)
  1604. • borrowers.last_unban_by (on UPDATE when unbanning)
  1605. • issue_tracker.reported_by (on INSERT)
  1606. 2. Log changes to asset_change_log EFFICIENTLY:
  1607. • INSERT: Only logs fields that were actually set (non-NULL)
  1608. • UPDATE: Only logs fields that actually changed
  1609. • DELETE: Only logs fields that had values (non-NULL) for restore capability
  1610. 3. Include user_id and username in logs
  1611. 4. Update last_modified_by and last_modified_date automatically
  1612. 5. Enforce business rules (prevent deleting borrowed items, validate zone_plus, etc.)
  1613. 6. Auto-calculate quantities for lendable items with quantity tracking
  1614. 7. Auto-detect and track issues in issue_tracker
  1615. 8. Manage physical audits with automatic issue detection
  1616. NOTE: You can still explicitly provide user tracking fields in your queries if needed.
  1617. The triggers only set them if they are NULL and @current_user_id is available.
  1618. EFFICIENCY: Change logging only captures non-NULL/changed fields, reducing storage by ~80%
  1619. for typical operations. The 'changed_fields' JSON array shows exactly what was
  1620. set/changed/deleted, making audit logs cleaner and more queryable.
  1621. PHYSICAL AUDIT WORKFLOW:
  1622. 1. Start audit: INSERT INTO physical_audits (audit_type, zone_id, started_by) VALUES ('full-zone', 1, 123);
  1623. 2. Scan assets: INSERT INTO physical_audit_logs (physical_audit_id, asset_id, audited_by, status_found, audit_task_id, audit_task_responses, exception_type, found_in_zone_id, auditor_action) VALUES (...);
  1624. 3. Complete audit: UPDATE physical_audits SET status = 'all-good' (or 'attention') WHERE id = audit_id;
  1625. 4. System automatically creates issues for missing/moved/damaged assets
  1626. WRONG-ZONE ASSET HANDLING:
  1627. When asset found in wrong zone (exception_type = 'wrong-zone'), auditor has 3 options:
  1628. - auditor_action = 'physical-move': Auditor will physically move item to correct zone (no issue created)
  1629. - auditor_action = 'virtual-update': Update asset's zone in system to where found (auto-detects label reprinting needs)
  1630. - auditor_action = NULL: Creates standard follow-up issue for later resolution
  1631. LABEL REPRINTING DETECTION:
  1632. System automatically detects if asset_tag contains location info when doing virtual-update:
  1633. - Checks if asset_tag contains old zone name or room codes
  1634. - Checks for common label patterns (e.g., "MB101-001", "RoomA-Device")
  1635. - Creates 'Maintenance' issue with 'Low' priority for label reprinting if needed
  1636. CROSS-AUDIT RECONCILIATION:
  1637. System automatically resolves "missing asset" issues from previous audits when assets are found:
  1638. - When asset is scanned in any audit, checks if it was missing from previous completed audits
  1639. - Auto-resolves related missing asset issues with solution 'Automatically Fixed'
  1640. - Logs reconciliation activity in asset_change_log for audit trail
  1641. - Prevents false "missing" reports when assets are just in different locations
  1642. ISSUE TRACKER FEATURES:
  1643. - Auto-creates issues for problematic asset status changes
  1644. - Auto-resolves issues when assets return to Good status
  1645. - Tracks borrower ban/unban cycles
  1646. - Comprehensive audit issue detection and tracking
  1647. - Intelligent cross-audit reconciliation to prevent false missing asset reports
  1648. Example queries in asset_change_log:
  1649. - changed_fields: ["status", "zone_id"] (array of field names that changed)
  1650. - old_values: {"status": "Good", "zone_id": 5}
  1651. - new_values: {"status": "Faulty", "zone_id": 7}
  1652. Example audit_task_responses JSON:
  1653. {"step_1_answer": "yes", "step_2_answer": "Good", "damage_notes": "Minor scratches on case"}
  1654. Example issues_found JSON in physical_audits:
  1655. {"missing_assets": 2, "moved_assets": 5, "damaged_assets": 1, "total_issues": 8}
  1656. */
  1657. -- ============================================
  1658. -- End of Schema
  1659. -- ============================================