-- =====================================================================
-- 41_salesrebate.sql
-- Sales Rebate and Company Rebate
--
-- GENERATED by _gen/pack.py from ../step/. DO NOT EDIT -- edit the source
-- there and re-pack, or the sha256 in MANIFEST.md stops matching.
--
-- 7 table(s), 28 ledger step(s).
--
-- ⚠ IMPORT ORDER: 01_system.sql, then all seven 1x masters, then this file. Order among
--    transactions does not matter. Re-importing costs nothing.
--
-- ⚠ STOP ON THE FIRST ERROR. Do not use `mysql --force`, and do not tick any
--    "continue on error" box. Each step records itself in `_migration_ledger`
--    immediately after its statement runs, WITHOUT checking that the statement
--    succeeded -- that is inherited from step/, where run.sh guarantees a stop by
--    running mysql without --force. Continue past an error here and a step that
--    failed is marked applied: 99_finalize.sql will then seed `migrations`, and
--    `php artisan migrate` will skip the work still owed. Both default clients
--    stop on error; the danger is turning that off.
--
-- ⚠ phpMyAdmin: UNTICK "Allow the interruption of an import".
--    If it fires, the import resumes on a NEW CONNECTION: SQL_MODE reverts to the server
--    default and every @variable dies, mid-file. Two things then break. NO_ZERO_DATE is
--    back, so any ALTER that rebuilds a table holding '0000-00-00' fails with ERROR 1292.
--    And @step / @todo / @sql are NULL, so the guard around the next payload stops meaning
--    anything. The SET SQL_MODE before every unit below limits the damage when someone
--    forgets the checkbox; it does not replace unticking it.
--
--    (STRICT_TRANS_TABLES is forced for a third case -- a value too big for its new column
--    is CLAMPED silently rather than refused. Measured on the tree as it stands, no column
--    narrows: all 674 MODIFY COLUMNs widen or are no-ops. It stays forced because the next
--    regeneration is under no obligation to keep that true.)
--
-- ⚠ Take a full backup first. The `20_cleanup` steps change data and nothing here
--    reverses them. `../audit_bukanmain_before_migrate.sql` only reads.
-- =====================================================================

-- Menus this file serves (24 links):
--   /company-rebates/approval-ceo
--   /company-rebates/approval-sm
--   /company-rebates/cancel-approval-ceo
--   /company-rebates/cancel-approval-sm
--   /company-rebates/create
--   /company-rebates/create-others
--   /company-rebates/create-own
--   /company-rebates/create-sm
--   /company-rebates/view-all
--   /company-rebates/view-all-readonly
--   /company-rebates/view-request
--   /company-rebates/view-request-sm
--   /generate-company-rebates/approval-ceo
--   /generate-company-rebates/approval-finance
--   /generate-company-rebates/approval-sm
--   /generate-company-rebates/bill
--   /generate-company-rebates/generate
--   /generate-company-rebates/view-all
--   /generate-company-rebates/view-all-readonly
--   /generate-company-rebates/view-creator
--   /generate-company-rebates/view-request
--   /generate-company-rebates/view-sm
--   /sales-rebates
--   /sales-rebates/export-company-ex-sales

-- --------------------------------------------------------------- prologue
-- run.sh sources step/_lib/session.sql for you. phpMyAdmin will not, so it is inlined.
             AND @@SQL_MODE LIKE '%NO_AUTO_VALUE_ON_ZERO%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_DATE%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_IN_DATE%',
        @@SQL_MODE,
        CONCAT(REPLACE(REPLACE(@@SQL_MODE, 'NO_ZERO_IN_DATE', ''), 'NO_ZERO_DATE', ''),
               ',NO_AUTO_VALUE_ON_ZERO,STRICT_TRANS_TABLES'));
-- Assert all four, not just the first. STRICT_TRANS_TABLES missing means out-of-range
-- values are clamped silently; NO_ZERO_DATE still present means any ALTER that rebuilds a
-- legacy table re-validates its '0000-00-00' rows and dies with ERROR 1292. The second is
-- the one that actually stops the migration, and it was not being checked.
SELECT IF(@@SQL_MODE LIKE '%STRICT_TRANS_TABLES%'
      AND @@SQL_MODE LIKE '%NO_AUTO_VALUE_ON_ZERO%'
      AND @@SQL_MODE NOT LIKE '%NO_ZERO_DATE%'
      AND @@SQL_MODE NOT LIKE '%NO_ZERO_IN_DATE%',
          'sql_mode OK - proceeding',
          (SELECT 'ABORT: sql_mode is wrong. Wanted STRICT_TRANS_TABLES + NO_AUTO_VALUE_ON_ZERO,'
           UNION ALL
           SELECT 'and NO_ZERO_DATE / NO_ZERO_IN_DATE OFF. The SET above should have done it.')
       ) AS preflight_sql_mode;

SET SESSION lock_wait_timeout = 60;
SET SESSION innodb_lock_wait_timeout = 60;

-- The ledger, copied verbatim from step/_lib/ledger.sql -- not restated, so the two
-- paths cannot disagree about its definition.
-- ---------------------------------------------------------------------
-- _lib/ledger.sql  --  the only thing here that is not in the source file
-- One row per applied step. This is the record that decides what a re-run skips,
-- what --status reports, and -- through the app-side gate -- which modules the
-- application will serve. It lives in the database on purpose: a file on one
-- operator's laptop drifts the moment someone runs a step from another machine.
--
-- Deliberately NOT in the project's PascalCase convention. It is an ops table, never
-- touched by Eloquent, and it should be visibly not-an-app-table.
--
-- `checksum` is the SHA-256 of the step's SQL payload -- the verbatim statements,
-- not the file -- so it cannot change when a comment above them is reworded.
-- _lib/steps.tsv carries the whole-file hashes for tamper detection.
--
-- ⚠ `step` IS ascii, AND THAT IS LOAD-BEARING. Every guard compares it against a
-- user variable, and a user variable carries the CONNECTION collation. Give this
-- column utf8mb4_unicode_ci and the very first step dies with ERROR 1267,
-- "Illegal mix of collations (utf8mb4_unicode_ci,IMPLICIT) and
-- (utf8mb4_0900_ai_ci,IMPLICIT) for operation '='" -- measured, that is exactly
-- how the first end-to-end run failed. ascii is a repertoire subset of latin1 and
-- of utf8mb4, so the server coerces it to whatever the connection is using,
-- whatever that turns out to be on the day. Step names are [a-z0-9_/] by
-- construction, so nothing is lost.
-- ---------------------------------------------------------------------

CREATE TABLE IF NOT EXISTS `_migration_ledger` (
  `step`        varchar(191) CHARACTER SET ascii COLLATE ascii_general_ci NOT NULL,
  `applied_at`  datetime     NOT NULL,
  `checksum`    char(64)     NOT NULL,
  `duration_ms` int          NOT NULL,
  PRIMARY KEY (`step`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;


-- --------------------------------------------------------------- preflight
-- 00_system/01_system.sql MUST already be applied. Every doc says so; until now nothing
-- enforced it, and the violation was silent for most of the tree: only three files break
-- without it (30_quotation and 40_budgetandtarget hit ERROR 1146 on a table 01_system
-- creates, and 99_finalize needs `migrations`). The other twenty import cleanly, record
-- their ledger rows, and leave a database that is half-migrated with nothing to say so.
--
-- 13 steps: the ALTER DATABASE plus the 12 CREATE TABLEs.
SET @sys_done = (SELECT COUNT(*) FROM `_migration_ledger` WHERE `step` LIKE '\_system/%');
SET @pf_sys = IF(@sys_done >= 13,
    'SELECT ''preflight: 00_system is applied'' AS preflight_system',
    'SELECT `ABORT: import 00_system/01_system.sql first. It runs the ALTER DATABASE and creates the 12 new tables that everything here assumes exist.`');
PREPARE _pf FROM @pf_sys; EXECUTE _pf; DEALLOCATE PREPARE _pf;

-- --------------------------------------------------------------- preflight
-- WAS THIS DATABASE MIGRATED FROM A DIFFERENT VERSION OF THIS FILE?
--
-- `_migration_ledger.checksum` is the SHA-256 of each step's payload. It is written 632
-- times across the tree and, until this block existed, read never -- so a corrected payload
-- re-issued under the same step name was skipped forever on any database that had recorded
-- the old one, silently and permanently.
SELECT COUNT(*) INTO @ck_bad FROM `_migration_ledger`
 WHERE `step` IN ('salesrebate/10_alter', 'salesrebate/20_cleanup', 'salesrebate/30_assert', 'salesrebate/40_fk', 'salesrebateassignment/10_alter', 'salesrebateassignment/20_cleanup', 'salesrebateassignment/30_assert', 'salesrebateassignment/40_fk', 'salesrebatedetail/10_alter', 'salesrebatedetail/20_cleanup', 'salesrebatedetail/30_assert', 'salesrebatedetail/40_fk', 'salesrebateinvoice/10_alter', 'salesrebateinvoice/20_cleanup', 'salesrebateinvoice/30_assert', 'salesrebateinvoice/40_fk', 'salesrebateinvoiceassignment/10_alter', 'salesrebateinvoiceassignment/20_cleanup', 'salesrebateinvoiceassignment/30_assert', 'salesrebateinvoiceassignment/40_fk', 'salesrebateinvoicedetail/10_alter', 'salesrebateinvoicedetail/20_cleanup', 'salesrebateinvoicedetail/30_assert', 'salesrebateinvoicedetail/40_fk', 'salesrebateinvoicepaymentdetail/10_alter', 'salesrebateinvoicepaymentdetail/20_cleanup', 'salesrebateinvoicepaymentdetail/30_assert', 'salesrebateinvoicepaymentdetail/40_fk')
   AND CONCAT(`step`, ':', `checksum`) NOT IN ('salesrebate/10_alter:dea092103d2ced57326d40da17b9a1542461975db80bb6c4ae5a2322412a2454', 'salesrebate/20_cleanup:7ca202a9ea30e1de960b82f3e9adf5ecbca067b044015ffa811793f21288d50b', 'salesrebate/30_assert:b3a483e61030d8e668fc423109b80d0dcef4e8b28e8042f9a68473b61c233f51', 'salesrebate/40_fk:b1032b0f90c9ddbad70b374dd9df2ea9f0607cd98a3b32affb3f4968fde7a388', 'salesrebateassignment/10_alter:3749040d176ce3eb07edf5d7cf83c66e42813b2c056e18b91e4eb3577bf60558', 'salesrebateassignment/20_cleanup:47eba39e9816c1d03634e4387cc18337e952a70cce096b6cfc5aa92b7ccb1019', 'salesrebateassignment/30_assert:5dfcf2c93c03c200dd6629d2bae2fa7d3014cfa6407037901d4e94f854993c1c', 'salesrebateassignment/40_fk:0d0823a5ba15305d919c56ce668b1e205fd8d4ffb5ea807767d4c1b5f3105e30', 'salesrebatedetail/10_alter:0d4a3a87e3ce4be5e07f6b20df1b33120afc5dd66f9a9a61a81422f589a03414', 'salesrebatedetail/20_cleanup:c665406bb1dbf36a2c4ce7a0379ab2e812fa0d28bff653740a50daab344963ff', 'salesrebatedetail/30_assert:f5216fc7694499a4a9a770c0a2a8a5f4efe53c989534b30ba8c76282ee05f501', 'salesrebatedetail/40_fk:5cb3ee70c4b9c49de61d8bd5ad120eb4e81a9e98b3d3fed5521d4e03cfc6440e', 'salesrebateinvoice/10_alter:8bf7756afe9876d458abaf2ca0ed39563ff89c6d1040c695188fa17ad56eb206', 'salesrebateinvoice/20_cleanup:f91bcd03a6cbb43ef852f210e36449e9399ae0ba06565162d7bdf156374be9bf', 'salesrebateinvoice/30_assert:aa29a35d4ff47d68f52661864a3411d5e7c6ee55fe94466417d8710a4d0333d2', 'salesrebateinvoice/40_fk:d7cec5eab80d5f9e2fc19e33f5ee7713f57a9f1475ce8708a8298b329d12c21d', 'salesrebateinvoiceassignment/10_alter:d531b8f8287b06b4c23421202d843616affee6d6e889e618ffd5ca142e059526', 'salesrebateinvoiceassignment/20_cleanup:dba497c1423809dcd3383668f2a5da6d2648cb6ebf4c1a2f5f2947c73b4ae30e', 'salesrebateinvoiceassignment/30_assert:c975972fc1a167e85736bcfd44ecc75922388a9b2a8efc52b3a6e2f7feec46f2', 'salesrebateinvoiceassignment/40_fk:db658fb8be5df54cbcbcecb3eea4dd2097e235adea61110ebed1e23371a256c7', 'salesrebateinvoicedetail/10_alter:33bb2ca2ce648b494dad881e83541f5dbc44f525c3ad2c4fa8ee22eaa43a0244', 'salesrebateinvoicedetail/20_cleanup:65062f231b06ca8a775d2313d2b6baebf87df31e3605bd7e90062f832522a02b', 'salesrebateinvoicedetail/30_assert:5b21ef9d440cb6b8b26ff372b3674cc585184ca3d29a3cf463be5563106090e8', 'salesrebateinvoicedetail/40_fk:6b43d9348591f1d5717ca2cddbe93d53fbe88c2fc09eebaa5270e794da4cae17', 'salesrebateinvoicepaymentdetail/10_alter:6786d1ec9714402be9c0ce293f6a5d07b30563e299896ba61b0599ca44368a3f', 'salesrebateinvoicepaymentdetail/20_cleanup:4dc7ee5041655e1087c9278578b777a6a266ef1705f46c8fcb530d1a7715ae17', 'salesrebateinvoicepaymentdetail/30_assert:4219b08db05c6e2c46f855a061a0667c501db677120e64996c6fd0117f3bec5f', 'salesrebateinvoicepaymentdetail/40_fk:771ced8359b4c50b614b2a94db579b5c778734bf7466677c29bdbbc8bbfc3848');
SET @pf_ck = IF(@ck_bad = 0,
    'SELECT ''preflight: ledger matches this file'' AS preflight_checksum',
    CONCAT('SELECT `ABORT: ', @ck_bad, ' step(s) here were applied from a DIFFERENT version of this file. Their payloads changed. Compare before re-importing; do not delete ledger rows blindly.`'));
PREPARE _pf FROM @pf_ck; EXECUTE _pf; DEALLOCATE PREPARE _pf;

-- ---------------------------------------------------------------------
-- unit: salesrebate    (transaction)
-- ---------------------------------------------------------------------
             AND @@SQL_MODE LIKE '%NO_AUTO_VALUE_ON_ZERO%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_DATE%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_IN_DATE%',
        @@SQL_MODE,
        CONCAT(REPLACE(REPLACE(@@SQL_MODE, 'NO_ZERO_IN_DATE', ''), 'NO_ZERO_DATE', ''),
               ',NO_AUTO_VALUE_ON_ZERO,STRICT_TRANS_TABLES'));
-- ---------------------------------------------------------------------
-- salesrebate/10_alter  --  source section A
-- The merged ALTER: new columns, type/charset changes, column order, NULL relaxation
-- and the indexes every foreign key needs -- ONE statement, so InnoDB rebuilds this
-- table ONCE. The original migration split these across five sections and rebuilt some
-- tables four times; that is where its 12 hours went. Do not split this back up.
--
-- Clause order is the original section order (3b, 3d, 3e, 4, 7), which is what keeps
-- every ADD COLUMN ... AFTER positioned exactly as before.
-- ---------------------------------------------------------------------

SET @step = 'salesrebate/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `salesrebate`
  MODIFY COLUMN `UserIDInput` int DEFAULT NULL,
  MODIFY COLUMN `UserIDSales` int DEFAULT NULL,
  MODIFY COLUMN `SalesRebateStatusID` int DEFAULT NULL,
  MODIFY COLUMN `CompanyID` int DEFAULT NULL,
  MODIFY COLUMN `DivisionID` int DEFAULT NULL,
  MODIFY COLUMN `IndustryID` int DEFAULT NULL,
  MODIFY COLUMN `CCPaymentTerm` int DEFAULT NULL,
  MODIFY COLUMN `ReferenceRebateID` int DEFAULT NULL,
  ADD INDEX `salesrebate_CCPaymentTerm` (`CCPaymentTerm`),
  ADD INDEX `salesrebate_CompanyID` (`CompanyID`),
  ADD INDEX `salesrebate_DivisionID` (`DivisionID`),
  ADD INDEX `salesrebate_IndustryID` (`IndustryID`),
  ADD INDEX `salesrebate_ReferenceRebateID` (`ReferenceRebateID`),
  ADD INDEX `salesrebate_SalesRebateStatusID` (`SalesRebateStatusID`),
  ADD INDEX `salesrebate_UserIDInput` (`UserIDInput`),
  ADD INDEX `salesrebate_UserIDSales` (`UserIDSales`)', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'dea092103d2ced57326d40da17b9a1542461975db80bb6c4ae5a2322412a2454', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- salesrebate/20_cleanup  --  source section B (= the original sections 5 and 6, merged)
-- 0-sentinels AND orphaned references -> NULL, one pass per table.
--     section 5:  WHERE `c` = 0
--     section 6:  WHERE `c` IS NOT NULL AND parent.ID IS NULL
--     merged   :  WHERE `c` IS NOT NULL AND (`c` = 0 OR parent.ID IS NULL)
-- Every LEFT JOIN is a primary-key equality, so none of them can multiply rows.
--
-- DATA CHANGE, and this script cannot reverse it. Run the audit first.
-- In its own transaction, with the ledger row inside it: either the cleanup and the
-- record of it both land, or neither does.
-- ---------------------------------------------------------------------

START TRANSACTION;

SET @step = 'salesrebate/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `salesrebate` c
  LEFT JOIN `quotationpaymentterm` p0 ON c.`CCPaymentTerm` = p0.`ID`
  LEFT JOIN `company` p1 ON c.`CompanyID` = p1.`ID`
  LEFT JOIN `division` p2 ON c.`DivisionID` = p2.`ID`
  LEFT JOIN `industry` p3 ON c.`IndustryID` = p3.`ID`
  LEFT JOIN `salesrebate` p4 ON c.`ReferenceRebateID` = p4.`ID`
  LEFT JOIN `salesrebatestatus` p5 ON c.`SalesRebateStatusID` = p5.`ID`
  LEFT JOIN `users` p6 ON c.`UserIDInput` = p6.`ID`
  LEFT JOIN `users` p7 ON c.`UserIDSales` = p7.`ID`
   SET
       c.`CCPaymentTerm` = IF((c.`CCPaymentTerm` IS NOT NULL AND (c.`CCPaymentTerm` = 0 OR p0.`ID` IS NULL)), NULL, c.`CCPaymentTerm`),
       c.`CompanyID` = IF((c.`CompanyID` IS NOT NULL AND (c.`CompanyID` = 0 OR p1.`ID` IS NULL)), NULL, c.`CompanyID`),
       c.`DivisionID` = IF((c.`DivisionID` IS NOT NULL AND (c.`DivisionID` = 0 OR p2.`ID` IS NULL)), NULL, c.`DivisionID`),
       c.`IndustryID` = IF((c.`IndustryID` IS NOT NULL AND (c.`IndustryID` = 0 OR p3.`ID` IS NULL)), NULL, c.`IndustryID`),
       c.`ReferenceRebateID` = IF((c.`ReferenceRebateID` IS NOT NULL AND (c.`ReferenceRebateID` = 0 OR p4.`ID` IS NULL)), NULL, c.`ReferenceRebateID`),
       c.`SalesRebateStatusID` = IF((c.`SalesRebateStatusID` IS NOT NULL AND (c.`SalesRebateStatusID` = 0 OR p5.`ID` IS NULL)), NULL, c.`SalesRebateStatusID`),
       c.`UserIDInput` = IF((c.`UserIDInput` IS NOT NULL AND (c.`UserIDInput` = 0 OR p6.`ID` IS NULL)), NULL, c.`UserIDInput`),
       c.`UserIDSales` = IF((c.`UserIDSales` IS NOT NULL AND (c.`UserIDSales` = 0 OR p7.`ID` IS NULL)), NULL, c.`UserIDSales`)
 WHERE  (c.`CCPaymentTerm` IS NOT NULL AND (c.`CCPaymentTerm` = 0 OR p0.`ID` IS NULL))
    OR (c.`CompanyID` IS NOT NULL AND (c.`CompanyID` = 0 OR p1.`ID` IS NULL))
    OR (c.`DivisionID` IS NOT NULL AND (c.`DivisionID` = 0 OR p2.`ID` IS NULL))
    OR (c.`IndustryID` IS NOT NULL AND (c.`IndustryID` = 0 OR p3.`ID` IS NULL))
    OR (c.`ReferenceRebateID` IS NOT NULL AND (c.`ReferenceRebateID` = 0 OR p4.`ID` IS NULL))
    OR (c.`SalesRebateStatusID` IS NOT NULL AND (c.`SalesRebateStatusID` = 0 OR p5.`ID` IS NULL))
    OR (c.`UserIDInput` IS NOT NULL AND (c.`UserIDInput` = 0 OR p6.`ID` IS NULL))
    OR (c.`UserIDSales` IS NOT NULL AND (c.`UserIDSales` = 0 OR p7.`ID` IS NULL))', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '7ca202a9ea30e1de960b82f3e9adf5ecbca067b044015ffa811793f21288d50b', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- salesrebate/30_assert  --  source section 7b
-- Orphan assertion over this table's 8 foreign-key relationships.
--
-- This is what pays for 40_fk being fast. The original created the constraints with
-- FOREIGN_KEY_CHECKS ON so a row the cleanup missed would abort the run, and paid for it
-- with a full table copy per constraint. This buys the same protection with one indexed
-- pass, and 40_fk then adds the constraints as metadata only.
--
-- NOT ledger-guarded on the way in, unlike every other phase: it only reads, and the
-- point of it is to be re-runnable. It does record its ledger row -- 40_fk requires it.
--
-- IF THIS ABORTS: a row survived 20_cleanup. Same stop-and-look event the original would
-- have hit as ERROR 1452 inside section 8, but nothing has been created yet.
-- ---------------------------------------------------------------------

SET @step = 'salesrebate/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `salesrebate` c
  LEFT JOIN `quotationpaymentterm` p0 ON c.`CCPaymentTerm` = p0.`ID`
  LEFT JOIN `company` p1 ON c.`CompanyID` = p1.`ID`
  LEFT JOIN `division` p2 ON c.`DivisionID` = p2.`ID`
  LEFT JOIN `industry` p3 ON c.`IndustryID` = p3.`ID`
  LEFT JOIN `salesrebate` p4 ON c.`ReferenceRebateID` = p4.`ID`
  LEFT JOIN `salesrebatestatus` p5 ON c.`SalesRebateStatusID` = p5.`ID`
  LEFT JOIN `users` p6 ON c.`UserIDInput` = p6.`ID`
  LEFT JOIN `users` p7 ON c.`UserIDSales` = p7.`ID`
 WHERE  (c.`CCPaymentTerm` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`CompanyID` IS NOT NULL AND p1.`ID` IS NULL)
    OR (c.`DivisionID` IS NOT NULL AND p2.`ID` IS NULL)
    OR (c.`IndustryID` IS NOT NULL AND p3.`ID` IS NULL)
    OR (c.`ReferenceRebateID` IS NOT NULL AND p4.`ID` IS NULL)
    OR (c.`SalesRebateStatusID` IS NOT NULL AND p5.`ID` IS NULL)
    OR (c.`UserIDInput` IS NOT NULL AND p6.`ID` IS NULL)
    OR (c.`UserIDSales` IS NOT NULL AND p7.`ID` IS NULL);
SET @orphans = @orphans + @n;

-- Two-row subquery on the false branch: ERROR 1242, an abort, before 40_fk runs.
SELECT IF(@orphans = 0,
          'salesrebate: orphan check OK - 0 rows across 8 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `salesrebate` still reference a parent that does not exist')
           UNION ALL
           SELECT 'Run 20_cleanup for this table first. Do NOT skip this check.')
       ) AS preflight_orphans;

INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'b3a483e61030d8e668fc423109b80d0dcef4e8b28e8042f9a68473b61c233f51', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- salesrebate/40_fk  --  source section 8
-- The constraints, one ALTER for the whole table.
--
-- FOREIGN_KEY_CHECKS is turned OFF for this statement and restored afterwards. With
-- checks on InnoDB cannot add a foreign key in place -- it copies the whole table and
-- re-validates every row, which is where the original migration's 154 table copies
-- came from. The validation is not skipped, it MOVED: 30_assert proves zero orphans
-- and refuses to let this run otherwise.
-- ---------------------------------------------------------------------

SET @fk_prev = @@FOREIGN_KEY_CHECKS;

SET @step = 'salesrebate/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `salesrebate`
  ADD CONSTRAINT `salesrebate_CCPaymentTerm` FOREIGN KEY (`CCPaymentTerm`) REFERENCES `quotationpaymentterm` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `salesrebate_CompanyID` FOREIGN KEY (`CompanyID`) REFERENCES `company` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `salesrebate_DivisionID` FOREIGN KEY (`DivisionID`) REFERENCES `division` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `salesrebate_IndustryID` FOREIGN KEY (`IndustryID`) REFERENCES `industry` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `salesrebate_ReferenceRebateID` FOREIGN KEY (`ReferenceRebateID`) REFERENCES `salesrebate` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `salesrebate_SalesRebateStatusID` FOREIGN KEY (`SalesRebateStatusID`) REFERENCES `salesrebatestatus` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `salesrebate_UserIDInput` FOREIGN KEY (`UserIDInput`) REFERENCES `users` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `salesrebate_UserIDSales` FOREIGN KEY (`UserIDSales`) REFERENCES `users` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'b1032b0f90c9ddbad70b374dd9df2ea9f0607cd98a3b32affb3f4968fde7a388', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: salesrebateassignment    (detail, owned by salesrebate)
-- ---------------------------------------------------------------------
             AND @@SQL_MODE LIKE '%NO_AUTO_VALUE_ON_ZERO%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_DATE%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_IN_DATE%',
        @@SQL_MODE,
        CONCAT(REPLACE(REPLACE(@@SQL_MODE, 'NO_ZERO_IN_DATE', ''), 'NO_ZERO_DATE', ''),
               ',NO_AUTO_VALUE_ON_ZERO,STRICT_TRANS_TABLES'));
-- ---------------------------------------------------------------------
-- salesrebateassignment/10_alter  --  source section A
-- The merged ALTER: new columns, type/charset changes, column order, NULL relaxation
-- and the indexes every foreign key needs -- ONE statement, so InnoDB rebuilds this
-- table ONCE. The original migration split these across five sections and rebuilt some
-- tables four times; that is where its 12 hours went. Do not split this back up.
--
-- Clause order is the original section order (3b, 3d, 3e, 4, 7), which is what keeps
-- every ADD COLUMN ... AFTER positioned exactly as before.
-- ---------------------------------------------------------------------

SET @step = 'salesrebateassignment/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `salesrebateassignment`
  MODIFY COLUMN `UserIDInput` int DEFAULT NULL,
  MODIFY COLUMN `SalesRebateID` int DEFAULT NULL,
  MODIFY COLUMN `SalesRebateStatusID` int DEFAULT NULL,
  ADD INDEX `salesrebateassignment_SalesRebateID` (`SalesRebateID`),
  ADD INDEX `salesrebateassignment_SalesRebateStatusID` (`SalesRebateStatusID`),
  ADD INDEX `salesrebateassignment_UserIDInput` (`UserIDInput`)', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '3749040d176ce3eb07edf5d7cf83c66e42813b2c056e18b91e4eb3577bf60558', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- salesrebateassignment/20_cleanup  --  source section B (= the original sections 5 and 6, merged)
-- 0-sentinels AND orphaned references -> NULL, one pass per table.
--     section 5:  WHERE `c` = 0
--     section 6:  WHERE `c` IS NOT NULL AND parent.ID IS NULL
--     merged   :  WHERE `c` IS NOT NULL AND (`c` = 0 OR parent.ID IS NULL)
-- Every LEFT JOIN is a primary-key equality, so none of them can multiply rows.
--
-- DATA CHANGE, and this script cannot reverse it. Run the audit first.
-- In its own transaction, with the ledger row inside it: either the cleanup and the
-- record of it both land, or neither does.
-- ---------------------------------------------------------------------

START TRANSACTION;

SET @step = 'salesrebateassignment/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `salesrebateassignment` c
  LEFT JOIN `salesrebate` p0 ON c.`SalesRebateID` = p0.`ID`
  LEFT JOIN `salesrebatestatus` p1 ON c.`SalesRebateStatusID` = p1.`ID`
  LEFT JOIN `users` p2 ON c.`UserIDInput` = p2.`ID`
   SET
       c.`SalesRebateID` = IF((c.`SalesRebateID` IS NOT NULL AND (c.`SalesRebateID` = 0 OR p0.`ID` IS NULL)), NULL, c.`SalesRebateID`),
       c.`SalesRebateStatusID` = IF((c.`SalesRebateStatusID` IS NOT NULL AND (c.`SalesRebateStatusID` = 0 OR p1.`ID` IS NULL)), NULL, c.`SalesRebateStatusID`),
       c.`UserIDInput` = IF((c.`UserIDInput` IS NOT NULL AND (c.`UserIDInput` = 0 OR p2.`ID` IS NULL)), NULL, c.`UserIDInput`)
 WHERE  (c.`SalesRebateID` IS NOT NULL AND (c.`SalesRebateID` = 0 OR p0.`ID` IS NULL))
    OR (c.`SalesRebateStatusID` IS NOT NULL AND (c.`SalesRebateStatusID` = 0 OR p1.`ID` IS NULL))
    OR (c.`UserIDInput` IS NOT NULL AND (c.`UserIDInput` = 0 OR p2.`ID` IS NULL))', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '47eba39e9816c1d03634e4387cc18337e952a70cce096b6cfc5aa92b7ccb1019', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- salesrebateassignment/30_assert  --  source section 7b
-- Orphan assertion over this table's 3 foreign-key relationships.
--
-- This is what pays for 40_fk being fast. The original created the constraints with
-- FOREIGN_KEY_CHECKS ON so a row the cleanup missed would abort the run, and paid for it
-- with a full table copy per constraint. This buys the same protection with one indexed
-- pass, and 40_fk then adds the constraints as metadata only.
--
-- NOT ledger-guarded on the way in, unlike every other phase: it only reads, and the
-- point of it is to be re-runnable. It does record its ledger row -- 40_fk requires it.
--
-- IF THIS ABORTS: a row survived 20_cleanup. Same stop-and-look event the original would
-- have hit as ERROR 1452 inside section 8, but nothing has been created yet.
-- ---------------------------------------------------------------------

SET @step = 'salesrebateassignment/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `salesrebateassignment` c
  LEFT JOIN `salesrebate` p0 ON c.`SalesRebateID` = p0.`ID`
  LEFT JOIN `salesrebatestatus` p1 ON c.`SalesRebateStatusID` = p1.`ID`
  LEFT JOIN `users` p2 ON c.`UserIDInput` = p2.`ID`
 WHERE  (c.`SalesRebateID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`SalesRebateStatusID` IS NOT NULL AND p1.`ID` IS NULL)
    OR (c.`UserIDInput` IS NOT NULL AND p2.`ID` IS NULL);
SET @orphans = @orphans + @n;

-- Two-row subquery on the false branch: ERROR 1242, an abort, before 40_fk runs.
SELECT IF(@orphans = 0,
          'salesrebateassignment: orphan check OK - 0 rows across 3 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `salesrebateassignment` still reference a parent that does not exist')
           UNION ALL
           SELECT 'Run 20_cleanup for this table first. Do NOT skip this check.')
       ) AS preflight_orphans;

INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '5dfcf2c93c03c200dd6629d2bae2fa7d3014cfa6407037901d4e94f854993c1c', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- salesrebateassignment/40_fk  --  source section 8
-- The constraints, one ALTER for the whole table.
--
-- FOREIGN_KEY_CHECKS is turned OFF for this statement and restored afterwards. With
-- checks on InnoDB cannot add a foreign key in place -- it copies the whole table and
-- re-validates every row, which is where the original migration's 154 table copies
-- came from. The validation is not skipped, it MOVED: 30_assert proves zero orphans
-- and refuses to let this run otherwise.
-- ---------------------------------------------------------------------

SET @fk_prev = @@FOREIGN_KEY_CHECKS;

SET @step = 'salesrebateassignment/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `salesrebateassignment`
  ADD CONSTRAINT `salesrebateassignment_SalesRebateID` FOREIGN KEY (`SalesRebateID`) REFERENCES `salesrebate` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `salesrebateassignment_SalesRebateStatusID` FOREIGN KEY (`SalesRebateStatusID`) REFERENCES `salesrebatestatus` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `salesrebateassignment_UserIDInput` FOREIGN KEY (`UserIDInput`) REFERENCES `users` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '0d0823a5ba15305d919c56ce668b1e205fd8d4ffb5ea807767d4c1b5f3105e30', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: salesrebatedetail    (detail, owned by salesrebate)
-- ---------------------------------------------------------------------
             AND @@SQL_MODE LIKE '%NO_AUTO_VALUE_ON_ZERO%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_DATE%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_IN_DATE%',
        @@SQL_MODE,
        CONCAT(REPLACE(REPLACE(@@SQL_MODE, 'NO_ZERO_IN_DATE', ''), 'NO_ZERO_DATE', ''),
               ',NO_AUTO_VALUE_ON_ZERO,STRICT_TRANS_TABLES'));
-- ---------------------------------------------------------------------
-- salesrebatedetail/10_alter  --  source section A
-- The merged ALTER: new columns, type/charset changes, column order, NULL relaxation
-- and the indexes every foreign key needs -- ONE statement, so InnoDB rebuilds this
-- table ONCE. The original migration split these across five sections and rebuilt some
-- tables four times; that is where its 12 hours went. Do not split this back up.
--
-- Clause order is the original section order (3b, 3d, 3e, 4, 7), which is what keeps
-- every ADD COLUMN ... AFTER positioned exactly as before.
-- ---------------------------------------------------------------------

SET @step = 'salesrebatedetail/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `salesrebatedetail`
  MODIFY COLUMN `Recipient` varchar(500) NOT NULL,
  MODIFY COLUMN `SalesRebateID` int DEFAULT NULL,
  MODIFY COLUMN `CompanyCPID` int DEFAULT NULL,
  ADD INDEX `salesrebatedetail_CompanyCPID` (`CompanyCPID`),
  ADD INDEX `salesrebatedetail_SalesRebateID` (`SalesRebateID`)', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '0d4a3a87e3ce4be5e07f6b20df1b33120afc5dd66f9a9a61a81422f589a03414', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- salesrebatedetail/20_cleanup  --  source section B (= the original sections 5 and 6, merged)
-- 0-sentinels AND orphaned references -> NULL, one pass per table.
--     section 5:  WHERE `c` = 0
--     section 6:  WHERE `c` IS NOT NULL AND parent.ID IS NULL
--     merged   :  WHERE `c` IS NOT NULL AND (`c` = 0 OR parent.ID IS NULL)
-- Every LEFT JOIN is a primary-key equality, so none of them can multiply rows.
--
-- DATA CHANGE, and this script cannot reverse it. Run the audit first.
-- In its own transaction, with the ledger row inside it: either the cleanup and the
-- record of it both land, or neither does.
-- ---------------------------------------------------------------------

START TRANSACTION;

SET @step = 'salesrebatedetail/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `salesrebatedetail` c
  LEFT JOIN `companycp` p0 ON c.`CompanyCPID` = p0.`ID`
  LEFT JOIN `salesrebate` p1 ON c.`SalesRebateID` = p1.`ID`
   SET
       c.`CompanyCPID` = IF((c.`CompanyCPID` IS NOT NULL AND (c.`CompanyCPID` = 0 OR p0.`ID` IS NULL)), NULL, c.`CompanyCPID`),
       c.`SalesRebateID` = IF((c.`SalesRebateID` IS NOT NULL AND (c.`SalesRebateID` = 0 OR p1.`ID` IS NULL)), NULL, c.`SalesRebateID`)
 WHERE  (c.`CompanyCPID` IS NOT NULL AND (c.`CompanyCPID` = 0 OR p0.`ID` IS NULL))
    OR (c.`SalesRebateID` IS NOT NULL AND (c.`SalesRebateID` = 0 OR p1.`ID` IS NULL))', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'c665406bb1dbf36a2c4ce7a0379ab2e812fa0d28bff653740a50daab344963ff', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- salesrebatedetail/30_assert  --  source section 7b
-- Orphan assertion over this table's 2 foreign-key relationships.
--
-- This is what pays for 40_fk being fast. The original created the constraints with
-- FOREIGN_KEY_CHECKS ON so a row the cleanup missed would abort the run, and paid for it
-- with a full table copy per constraint. This buys the same protection with one indexed
-- pass, and 40_fk then adds the constraints as metadata only.
--
-- NOT ledger-guarded on the way in, unlike every other phase: it only reads, and the
-- point of it is to be re-runnable. It does record its ledger row -- 40_fk requires it.
--
-- IF THIS ABORTS: a row survived 20_cleanup. Same stop-and-look event the original would
-- have hit as ERROR 1452 inside section 8, but nothing has been created yet.
-- ---------------------------------------------------------------------

SET @step = 'salesrebatedetail/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `salesrebatedetail` c
  LEFT JOIN `companycp` p0 ON c.`CompanyCPID` = p0.`ID`
  LEFT JOIN `salesrebate` p1 ON c.`SalesRebateID` = p1.`ID`
 WHERE  (c.`CompanyCPID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`SalesRebateID` IS NOT NULL AND p1.`ID` IS NULL);
SET @orphans = @orphans + @n;

-- Two-row subquery on the false branch: ERROR 1242, an abort, before 40_fk runs.
SELECT IF(@orphans = 0,
          'salesrebatedetail: orphan check OK - 0 rows across 2 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `salesrebatedetail` still reference a parent that does not exist')
           UNION ALL
           SELECT 'Run 20_cleanup for this table first. Do NOT skip this check.')
       ) AS preflight_orphans;

INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'f5216fc7694499a4a9a770c0a2a8a5f4efe53c989534b30ba8c76282ee05f501', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- salesrebatedetail/40_fk  --  source section 8
-- The constraints, one ALTER for the whole table.
--
-- FOREIGN_KEY_CHECKS is turned OFF for this statement and restored afterwards. With
-- checks on InnoDB cannot add a foreign key in place -- it copies the whole table and
-- re-validates every row, which is where the original migration's 154 table copies
-- came from. The validation is not skipped, it MOVED: 30_assert proves zero orphans
-- and refuses to let this run otherwise.
-- ---------------------------------------------------------------------

SET @fk_prev = @@FOREIGN_KEY_CHECKS;

SET @step = 'salesrebatedetail/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `salesrebatedetail`
  ADD CONSTRAINT `salesrebatedetail_CompanyCPID` FOREIGN KEY (`CompanyCPID`) REFERENCES `companycp` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `salesrebatedetail_SalesRebateID` FOREIGN KEY (`SalesRebateID`) REFERENCES `salesrebate` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '5cb3ee70c4b9c49de61d8bd5ad120eb4e81a9e98b3d3fed5521d4e03cfc6440e', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: salesrebateinvoicepaymentdetail    (detail, owned by salesrebate)
-- ---------------------------------------------------------------------
             AND @@SQL_MODE LIKE '%NO_AUTO_VALUE_ON_ZERO%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_DATE%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_IN_DATE%',
        @@SQL_MODE,
        CONCAT(REPLACE(REPLACE(@@SQL_MODE, 'NO_ZERO_IN_DATE', ''), 'NO_ZERO_DATE', ''),
               ',NO_AUTO_VALUE_ON_ZERO,STRICT_TRANS_TABLES'));
-- ---------------------------------------------------------------------
-- salesrebateinvoicepaymentdetail/10_alter  --  source section A
-- The merged ALTER: new columns, type/charset changes, column order, NULL relaxation
-- and the indexes every foreign key needs -- ONE statement, so InnoDB rebuilds this
-- table ONCE. The original migration split these across five sections and rebuilt some
-- tables four times; that is where its 12 hours went. Do not split this back up.
--
-- Clause order is the original section order (3b, 3d, 3e, 4, 7), which is what keeps
-- every ADD COLUMN ... AFTER positioned exactly as before.
-- ---------------------------------------------------------------------

SET @step = 'salesrebateinvoicepaymentdetail/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `salesrebateinvoicepaymentdetail`
  MODIFY COLUMN `SalesRebateInvoiceDetailID` int DEFAULT NULL,
  ADD INDEX `salesrebateinvoicepaymentdetail_SalesRebateInvoiceDetailID` (`SalesRebateInvoiceDetailID`)', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '6786d1ec9714402be9c0ce293f6a5d07b30563e299896ba61b0599ca44368a3f', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- salesrebateinvoicepaymentdetail/20_cleanup  --  source section B (= the original sections 5 and 6, merged)
-- 0-sentinels AND orphaned references -> NULL, one pass per table.
--     section 5:  WHERE `c` = 0
--     section 6:  WHERE `c` IS NOT NULL AND parent.ID IS NULL
--     merged   :  WHERE `c` IS NOT NULL AND (`c` = 0 OR parent.ID IS NULL)
-- Every LEFT JOIN is a primary-key equality, so none of them can multiply rows.
--
-- DATA CHANGE, and this script cannot reverse it. Run the audit first.
-- In its own transaction, with the ledger row inside it: either the cleanup and the
-- record of it both land, or neither does.
-- ---------------------------------------------------------------------

START TRANSACTION;

SET @step = 'salesrebateinvoicepaymentdetail/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `salesrebateinvoicepaymentdetail` c
  LEFT JOIN `salesrebateinvoicedetail` p0 ON c.`SalesRebateInvoiceDetailID` = p0.`ID`
   SET
       c.`SalesRebateInvoiceDetailID` = IF((c.`SalesRebateInvoiceDetailID` IS NOT NULL AND (c.`SalesRebateInvoiceDetailID` = 0 OR p0.`ID` IS NULL)), NULL, c.`SalesRebateInvoiceDetailID`)
 WHERE  (c.`SalesRebateInvoiceDetailID` IS NOT NULL AND (c.`SalesRebateInvoiceDetailID` = 0 OR p0.`ID` IS NULL))', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '4dc7ee5041655e1087c9278578b777a6a266ef1705f46c8fcb530d1a7715ae17', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- salesrebateinvoicepaymentdetail/30_assert  --  source section 7b
-- Orphan assertion over this table's 1 foreign-key relationships.
--
-- This is what pays for 40_fk being fast. The original created the constraints with
-- FOREIGN_KEY_CHECKS ON so a row the cleanup missed would abort the run, and paid for it
-- with a full table copy per constraint. This buys the same protection with one indexed
-- pass, and 40_fk then adds the constraints as metadata only.
--
-- NOT ledger-guarded on the way in, unlike every other phase: it only reads, and the
-- point of it is to be re-runnable. It does record its ledger row -- 40_fk requires it.
--
-- IF THIS ABORTS: a row survived 20_cleanup. Same stop-and-look event the original would
-- have hit as ERROR 1452 inside section 8, but nothing has been created yet.
-- ---------------------------------------------------------------------

SET @step = 'salesrebateinvoicepaymentdetail/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `salesrebateinvoicepaymentdetail` c
  LEFT JOIN `salesrebateinvoicedetail` p0 ON c.`SalesRebateInvoiceDetailID` = p0.`ID`
 WHERE  (c.`SalesRebateInvoiceDetailID` IS NOT NULL AND p0.`ID` IS NULL);
SET @orphans = @orphans + @n;

-- Two-row subquery on the false branch: ERROR 1242, an abort, before 40_fk runs.
SELECT IF(@orphans = 0,
          'salesrebateinvoicepaymentdetail: orphan check OK - 0 rows across 1 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `salesrebateinvoicepaymentdetail` still reference a parent that does not exist')
           UNION ALL
           SELECT 'Run 20_cleanup for this table first. Do NOT skip this check.')
       ) AS preflight_orphans;

INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '4219b08db05c6e2c46f855a061a0667c501db677120e64996c6fd0117f3bec5f', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- salesrebateinvoicepaymentdetail/40_fk  --  source section 8
-- The constraints, one ALTER for the whole table.
--
-- FOREIGN_KEY_CHECKS is turned OFF for this statement and restored afterwards. With
-- checks on InnoDB cannot add a foreign key in place -- it copies the whole table and
-- re-validates every row, which is where the original migration's 154 table copies
-- came from. The validation is not skipped, it MOVED: 30_assert proves zero orphans
-- and refuses to let this run otherwise.
-- ---------------------------------------------------------------------

SET @fk_prev = @@FOREIGN_KEY_CHECKS;

SET @step = 'salesrebateinvoicepaymentdetail/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `salesrebateinvoicepaymentdetail` ADD CONSTRAINT `salesrebateinvoicepaymentdetail_SalesRebateInvoiceDetailID` FOREIGN KEY (`SalesRebateInvoiceDetailID`) REFERENCES `salesrebateinvoicedetail` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '771ced8359b4c50b614b2a94db579b5c778734bf7466677c29bdbbc8bbfc3848', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: salesrebateinvoice    (transaction)
-- ---------------------------------------------------------------------
             AND @@SQL_MODE LIKE '%NO_AUTO_VALUE_ON_ZERO%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_DATE%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_IN_DATE%',
        @@SQL_MODE,
        CONCAT(REPLACE(REPLACE(@@SQL_MODE, 'NO_ZERO_IN_DATE', ''), 'NO_ZERO_DATE', ''),
               ',NO_AUTO_VALUE_ON_ZERO,STRICT_TRANS_TABLES'));
-- ---------------------------------------------------------------------
-- salesrebateinvoice/10_alter  --  source section A
-- The merged ALTER: new columns, type/charset changes, column order, NULL relaxation
-- and the indexes every foreign key needs -- ONE statement, so InnoDB rebuilds this
-- table ONCE. The original migration split these across five sections and rebuilt some
-- tables four times; that is where its 12 hours went. Do not split this back up.
--
-- Clause order is the original section order (3b, 3d, 3e, 4, 7), which is what keeps
-- every ADD COLUMN ... AFTER positioned exactly as before.
-- ---------------------------------------------------------------------

SET @step = 'salesrebateinvoice/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `salesrebateinvoice`
  MODIFY COLUMN `SalesRebateID` int DEFAULT NULL,
  MODIFY COLUMN `SalesRebateInvoiceStatusID` int DEFAULT NULL,
  MODIFY COLUMN `UserInput` int DEFAULT NULL,
  MODIFY COLUMN `CompanyID` int DEFAULT NULL,
  MODIFY COLUMN `DivisionID` int DEFAULT NULL,
  MODIFY COLUMN `IndustryID` int DEFAULT NULL,
  ADD INDEX `salesrebateinvoice_CompanyID` (`CompanyID`),
  ADD INDEX `salesrebateinvoice_DivisionID` (`DivisionID`),
  ADD INDEX `salesrebateinvoice_IndustryID` (`IndustryID`),
  ADD INDEX `salesrebateinvoice_SalesRebateID` (`SalesRebateID`),
  ADD INDEX `salesrebateinvoice_SalesRebateInvoiceStatusID` (`SalesRebateInvoiceStatusID`),
  ADD INDEX `salesrebateinvoice_UserInput` (`UserInput`)', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '8bf7756afe9876d458abaf2ca0ed39563ff89c6d1040c695188fa17ad56eb206', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- salesrebateinvoice/20_cleanup  --  source section B (= the original sections 5 and 6, merged)
-- 0-sentinels AND orphaned references -> NULL, one pass per table.
--     section 5:  WHERE `c` = 0
--     section 6:  WHERE `c` IS NOT NULL AND parent.ID IS NULL
--     merged   :  WHERE `c` IS NOT NULL AND (`c` = 0 OR parent.ID IS NULL)
-- Every LEFT JOIN is a primary-key equality, so none of them can multiply rows.
--
-- DATA CHANGE, and this script cannot reverse it. Run the audit first.
-- In its own transaction, with the ledger row inside it: either the cleanup and the
-- record of it both land, or neither does.
-- ---------------------------------------------------------------------

START TRANSACTION;

SET @step = 'salesrebateinvoice/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `salesrebateinvoice` c
  LEFT JOIN `company` p0 ON c.`CompanyID` = p0.`ID`
  LEFT JOIN `division` p1 ON c.`DivisionID` = p1.`ID`
  LEFT JOIN `industry` p2 ON c.`IndustryID` = p2.`ID`
  LEFT JOIN `salesrebate` p3 ON c.`SalesRebateID` = p3.`ID`
  LEFT JOIN `salesrebateinvoicedetailstatus` p4 ON c.`SalesRebateInvoiceStatusID` = p4.`ID`
  LEFT JOIN `users` p5 ON c.`UserInput` = p5.`ID`
   SET
       c.`CompanyID` = IF((c.`CompanyID` IS NOT NULL AND (c.`CompanyID` = 0 OR p0.`ID` IS NULL)), NULL, c.`CompanyID`),
       c.`DivisionID` = IF((c.`DivisionID` IS NOT NULL AND (c.`DivisionID` = 0 OR p1.`ID` IS NULL)), NULL, c.`DivisionID`),
       c.`IndustryID` = IF((c.`IndustryID` IS NOT NULL AND (c.`IndustryID` = 0 OR p2.`ID` IS NULL)), NULL, c.`IndustryID`),
       c.`SalesRebateID` = IF((c.`SalesRebateID` IS NOT NULL AND (c.`SalesRebateID` = 0 OR p3.`ID` IS NULL)), NULL, c.`SalesRebateID`),
       c.`SalesRebateInvoiceStatusID` = IF((c.`SalesRebateInvoiceStatusID` IS NOT NULL AND (c.`SalesRebateInvoiceStatusID` = 0 OR p4.`ID` IS NULL)), NULL, c.`SalesRebateInvoiceStatusID`),
       c.`UserInput` = IF((c.`UserInput` IS NOT NULL AND (c.`UserInput` = 0 OR p5.`ID` IS NULL)), NULL, c.`UserInput`)
 WHERE  (c.`CompanyID` IS NOT NULL AND (c.`CompanyID` = 0 OR p0.`ID` IS NULL))
    OR (c.`DivisionID` IS NOT NULL AND (c.`DivisionID` = 0 OR p1.`ID` IS NULL))
    OR (c.`IndustryID` IS NOT NULL AND (c.`IndustryID` = 0 OR p2.`ID` IS NULL))
    OR (c.`SalesRebateID` IS NOT NULL AND (c.`SalesRebateID` = 0 OR p3.`ID` IS NULL))
    OR (c.`SalesRebateInvoiceStatusID` IS NOT NULL AND (c.`SalesRebateInvoiceStatusID` = 0 OR p4.`ID` IS NULL))
    OR (c.`UserInput` IS NOT NULL AND (c.`UserInput` = 0 OR p5.`ID` IS NULL))', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'f91bcd03a6cbb43ef852f210e36449e9399ae0ba06565162d7bdf156374be9bf', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- salesrebateinvoice/30_assert  --  source section 7b
-- Orphan assertion over this table's 6 foreign-key relationships.
--
-- This is what pays for 40_fk being fast. The original created the constraints with
-- FOREIGN_KEY_CHECKS ON so a row the cleanup missed would abort the run, and paid for it
-- with a full table copy per constraint. This buys the same protection with one indexed
-- pass, and 40_fk then adds the constraints as metadata only.
--
-- NOT ledger-guarded on the way in, unlike every other phase: it only reads, and the
-- point of it is to be re-runnable. It does record its ledger row -- 40_fk requires it.
--
-- IF THIS ABORTS: a row survived 20_cleanup. Same stop-and-look event the original would
-- have hit as ERROR 1452 inside section 8, but nothing has been created yet.
-- ---------------------------------------------------------------------

SET @step = 'salesrebateinvoice/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `salesrebateinvoice` c
  LEFT JOIN `company` p0 ON c.`CompanyID` = p0.`ID`
  LEFT JOIN `division` p1 ON c.`DivisionID` = p1.`ID`
  LEFT JOIN `industry` p2 ON c.`IndustryID` = p2.`ID`
  LEFT JOIN `salesrebate` p3 ON c.`SalesRebateID` = p3.`ID`
  LEFT JOIN `salesrebateinvoicedetailstatus` p4 ON c.`SalesRebateInvoiceStatusID` = p4.`ID`
  LEFT JOIN `users` p5 ON c.`UserInput` = p5.`ID`
 WHERE  (c.`CompanyID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`DivisionID` IS NOT NULL AND p1.`ID` IS NULL)
    OR (c.`IndustryID` IS NOT NULL AND p2.`ID` IS NULL)
    OR (c.`SalesRebateID` IS NOT NULL AND p3.`ID` IS NULL)
    OR (c.`SalesRebateInvoiceStatusID` IS NOT NULL AND p4.`ID` IS NULL)
    OR (c.`UserInput` IS NOT NULL AND p5.`ID` IS NULL);
SET @orphans = @orphans + @n;

-- Two-row subquery on the false branch: ERROR 1242, an abort, before 40_fk runs.
SELECT IF(@orphans = 0,
          'salesrebateinvoice: orphan check OK - 0 rows across 6 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `salesrebateinvoice` still reference a parent that does not exist')
           UNION ALL
           SELECT 'Run 20_cleanup for this table first. Do NOT skip this check.')
       ) AS preflight_orphans;

INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'aa29a35d4ff47d68f52661864a3411d5e7c6ee55fe94466417d8710a4d0333d2', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- salesrebateinvoice/40_fk  --  source section 8
-- The constraints, one ALTER for the whole table.
--
-- FOREIGN_KEY_CHECKS is turned OFF for this statement and restored afterwards. With
-- checks on InnoDB cannot add a foreign key in place -- it copies the whole table and
-- re-validates every row, which is where the original migration's 154 table copies
-- came from. The validation is not skipped, it MOVED: 30_assert proves zero orphans
-- and refuses to let this run otherwise.
-- ---------------------------------------------------------------------

SET @fk_prev = @@FOREIGN_KEY_CHECKS;

SET @step = 'salesrebateinvoice/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `salesrebateinvoice`
  ADD CONSTRAINT `salesrebateinvoice_CompanyID` FOREIGN KEY (`CompanyID`) REFERENCES `company` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `salesrebateinvoice_DivisionID` FOREIGN KEY (`DivisionID`) REFERENCES `division` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `salesrebateinvoice_IndustryID` FOREIGN KEY (`IndustryID`) REFERENCES `industry` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `salesrebateinvoice_SalesRebateID` FOREIGN KEY (`SalesRebateID`) REFERENCES `salesrebate` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `salesrebateinvoice_SalesRebateInvoiceStatusID` FOREIGN KEY (`SalesRebateInvoiceStatusID`) REFERENCES `salesrebateinvoicedetailstatus` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `salesrebateinvoice_UserInput` FOREIGN KEY (`UserInput`) REFERENCES `users` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'd7cec5eab80d5f9e2fc19e33f5ee7713f57a9f1475ce8708a8298b329d12c21d', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: salesrebateinvoiceassignment    (detail, owned by salesrebateinvoice)
-- ---------------------------------------------------------------------
             AND @@SQL_MODE LIKE '%NO_AUTO_VALUE_ON_ZERO%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_DATE%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_IN_DATE%',
        @@SQL_MODE,
        CONCAT(REPLACE(REPLACE(@@SQL_MODE, 'NO_ZERO_IN_DATE', ''), 'NO_ZERO_DATE', ''),
               ',NO_AUTO_VALUE_ON_ZERO,STRICT_TRANS_TABLES'));
-- ---------------------------------------------------------------------
-- salesrebateinvoiceassignment/10_alter  --  source section A
-- The merged ALTER: new columns, type/charset changes, column order, NULL relaxation
-- and the indexes every foreign key needs -- ONE statement, so InnoDB rebuilds this
-- table ONCE. The original migration split these across five sections and rebuilt some
-- tables four times; that is where its 12 hours went. Do not split this back up.
--
-- Clause order is the original section order (3b, 3d, 3e, 4, 7), which is what keeps
-- every ADD COLUMN ... AFTER positioned exactly as before.
-- ---------------------------------------------------------------------

SET @step = 'salesrebateinvoiceassignment/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `salesrebateinvoiceassignment`
  MODIFY COLUMN `UserIDInput` int DEFAULT NULL,
  MODIFY COLUMN `SalesRebateInvoiceID` int DEFAULT NULL,
  MODIFY COLUMN `SalesRebateInvoiceStatusID` int DEFAULT NULL,
  ADD INDEX `salesrebateinvoiceassignment_SalesRebateInvoiceID` (`SalesRebateInvoiceID`),
  ADD INDEX `salesrebateinvoiceassignment_SalesRebateInvoiceStatusID` (`SalesRebateInvoiceStatusID`),
  ADD INDEX `salesrebateinvoiceassignment_UserIDInput` (`UserIDInput`)', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'd531b8f8287b06b4c23421202d843616affee6d6e889e618ffd5ca142e059526', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- salesrebateinvoiceassignment/20_cleanup  --  source section B (= the original sections 5 and 6, merged)
-- 0-sentinels AND orphaned references -> NULL, one pass per table.
--     section 5:  WHERE `c` = 0
--     section 6:  WHERE `c` IS NOT NULL AND parent.ID IS NULL
--     merged   :  WHERE `c` IS NOT NULL AND (`c` = 0 OR parent.ID IS NULL)
-- Every LEFT JOIN is a primary-key equality, so none of them can multiply rows.
--
-- DATA CHANGE, and this script cannot reverse it. Run the audit first.
-- In its own transaction, with the ledger row inside it: either the cleanup and the
-- record of it both land, or neither does.
-- ---------------------------------------------------------------------

START TRANSACTION;

SET @step = 'salesrebateinvoiceassignment/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `salesrebateinvoiceassignment` c
  LEFT JOIN `salesrebateinvoice` p0 ON c.`SalesRebateInvoiceID` = p0.`ID`
  LEFT JOIN `salesrebateinvoicedetailstatus` p1 ON c.`SalesRebateInvoiceStatusID` = p1.`ID`
  LEFT JOIN `users` p2 ON c.`UserIDInput` = p2.`ID`
   SET
       c.`SalesRebateInvoiceID` = IF((c.`SalesRebateInvoiceID` IS NOT NULL AND (c.`SalesRebateInvoiceID` = 0 OR p0.`ID` IS NULL)), NULL, c.`SalesRebateInvoiceID`),
       c.`SalesRebateInvoiceStatusID` = IF((c.`SalesRebateInvoiceStatusID` IS NOT NULL AND (c.`SalesRebateInvoiceStatusID` = 0 OR p1.`ID` IS NULL)), NULL, c.`SalesRebateInvoiceStatusID`),
       c.`UserIDInput` = IF((c.`UserIDInput` IS NOT NULL AND (c.`UserIDInput` = 0 OR p2.`ID` IS NULL)), NULL, c.`UserIDInput`)
 WHERE  (c.`SalesRebateInvoiceID` IS NOT NULL AND (c.`SalesRebateInvoiceID` = 0 OR p0.`ID` IS NULL))
    OR (c.`SalesRebateInvoiceStatusID` IS NOT NULL AND (c.`SalesRebateInvoiceStatusID` = 0 OR p1.`ID` IS NULL))
    OR (c.`UserIDInput` IS NOT NULL AND (c.`UserIDInput` = 0 OR p2.`ID` IS NULL))', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'dba497c1423809dcd3383668f2a5da6d2648cb6ebf4c1a2f5f2947c73b4ae30e', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- salesrebateinvoiceassignment/30_assert  --  source section 7b
-- Orphan assertion over this table's 3 foreign-key relationships.
--
-- This is what pays for 40_fk being fast. The original created the constraints with
-- FOREIGN_KEY_CHECKS ON so a row the cleanup missed would abort the run, and paid for it
-- with a full table copy per constraint. This buys the same protection with one indexed
-- pass, and 40_fk then adds the constraints as metadata only.
--
-- NOT ledger-guarded on the way in, unlike every other phase: it only reads, and the
-- point of it is to be re-runnable. It does record its ledger row -- 40_fk requires it.
--
-- IF THIS ABORTS: a row survived 20_cleanup. Same stop-and-look event the original would
-- have hit as ERROR 1452 inside section 8, but nothing has been created yet.
-- ---------------------------------------------------------------------

SET @step = 'salesrebateinvoiceassignment/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `salesrebateinvoiceassignment` c
  LEFT JOIN `salesrebateinvoice` p0 ON c.`SalesRebateInvoiceID` = p0.`ID`
  LEFT JOIN `salesrebateinvoicedetailstatus` p1 ON c.`SalesRebateInvoiceStatusID` = p1.`ID`
  LEFT JOIN `users` p2 ON c.`UserIDInput` = p2.`ID`
 WHERE  (c.`SalesRebateInvoiceID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`SalesRebateInvoiceStatusID` IS NOT NULL AND p1.`ID` IS NULL)
    OR (c.`UserIDInput` IS NOT NULL AND p2.`ID` IS NULL);
SET @orphans = @orphans + @n;

-- Two-row subquery on the false branch: ERROR 1242, an abort, before 40_fk runs.
SELECT IF(@orphans = 0,
          'salesrebateinvoiceassignment: orphan check OK - 0 rows across 3 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `salesrebateinvoiceassignment` still reference a parent that does not exist')
           UNION ALL
           SELECT 'Run 20_cleanup for this table first. Do NOT skip this check.')
       ) AS preflight_orphans;

INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'c975972fc1a167e85736bcfd44ecc75922388a9b2a8efc52b3a6e2f7feec46f2', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- salesrebateinvoiceassignment/40_fk  --  source section 8
-- The constraints, one ALTER for the whole table.
--
-- FOREIGN_KEY_CHECKS is turned OFF for this statement and restored afterwards. With
-- checks on InnoDB cannot add a foreign key in place -- it copies the whole table and
-- re-validates every row, which is where the original migration's 154 table copies
-- came from. The validation is not skipped, it MOVED: 30_assert proves zero orphans
-- and refuses to let this run otherwise.
-- ---------------------------------------------------------------------

SET @fk_prev = @@FOREIGN_KEY_CHECKS;

SET @step = 'salesrebateinvoiceassignment/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `salesrebateinvoiceassignment`
  ADD CONSTRAINT `salesrebateinvoiceassignment_SalesRebateInvoiceID` FOREIGN KEY (`SalesRebateInvoiceID`) REFERENCES `salesrebateinvoice` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `salesrebateinvoiceassignment_SalesRebateInvoiceStatusID` FOREIGN KEY (`SalesRebateInvoiceStatusID`) REFERENCES `salesrebateinvoicedetailstatus` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `salesrebateinvoiceassignment_UserIDInput` FOREIGN KEY (`UserIDInput`) REFERENCES `users` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'db658fb8be5df54cbcbcecb3eea4dd2097e235adea61110ebed1e23371a256c7', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: salesrebateinvoicedetail    (detail, owned by salesrebateinvoice)
-- ---------------------------------------------------------------------
             AND @@SQL_MODE LIKE '%NO_AUTO_VALUE_ON_ZERO%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_DATE%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_IN_DATE%',
        @@SQL_MODE,
        CONCAT(REPLACE(REPLACE(@@SQL_MODE, 'NO_ZERO_IN_DATE', ''), 'NO_ZERO_DATE', ''),
               ',NO_AUTO_VALUE_ON_ZERO,STRICT_TRANS_TABLES'));
-- ---------------------------------------------------------------------
-- salesrebateinvoicedetail/10_alter  --  source section A
-- The merged ALTER: new columns, type/charset changes, column order, NULL relaxation
-- and the indexes every foreign key needs -- ONE statement, so InnoDB rebuilds this
-- table ONCE. The original migration split these across five sections and rebuilt some
-- tables four times; that is where its 12 hours went. Do not split this back up.
--
-- Clause order is the original section order (3b, 3d, 3e, 4, 7), which is what keeps
-- every ADD COLUMN ... AFTER positioned exactly as before.
-- ---------------------------------------------------------------------

SET @step = 'salesrebateinvoicedetail/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `salesrebateinvoicedetail`
  MODIFY COLUMN `SalesRebateInvoiceDetailStatusID` int DEFAULT NULL,
  MODIFY COLUMN `SalesRebateInvoiceID` int DEFAULT NULL,
  MODIFY COLUMN `SalesRebateID` int DEFAULT NULL,
  MODIFY COLUMN `PaymentCPID` int DEFAULT NULL,
  ADD INDEX `salesrebateinvoicedetail_PaymentCPID` (`PaymentCPID`),
  ADD INDEX `salesrebateinvoicedetail_SalesRebateID` (`SalesRebateID`),
  ADD INDEX `salesrebateinvoicedetail_SalesRebateInvoiceDetailStatusID` (`SalesRebateInvoiceDetailStatusID`),
  ADD INDEX `salesrebateinvoicedetail_SalesRebateInvoiceID` (`SalesRebateInvoiceID`)', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '33bb2ca2ce648b494dad881e83541f5dbc44f525c3ad2c4fa8ee22eaa43a0244', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- salesrebateinvoicedetail/20_cleanup  --  source section B (= the original sections 5 and 6, merged)
-- 0-sentinels AND orphaned references -> NULL, one pass per table.
--     section 5:  WHERE `c` = 0
--     section 6:  WHERE `c` IS NOT NULL AND parent.ID IS NULL
--     merged   :  WHERE `c` IS NOT NULL AND (`c` = 0 OR parent.ID IS NULL)
-- Every LEFT JOIN is a primary-key equality, so none of them can multiply rows.
--
-- DATA CHANGE, and this script cannot reverse it. Run the audit first.
-- In its own transaction, with the ledger row inside it: either the cleanup and the
-- record of it both land, or neither does.
-- ---------------------------------------------------------------------

START TRANSACTION;

SET @step = 'salesrebateinvoicedetail/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `salesrebateinvoicedetail` c
  LEFT JOIN `companycp` p0 ON c.`PaymentCPID` = p0.`ID`
  LEFT JOIN `salesrebate` p1 ON c.`SalesRebateID` = p1.`ID`
  LEFT JOIN `salesrebateinvoicedetailstatus` p2 ON c.`SalesRebateInvoiceDetailStatusID` = p2.`ID`
  LEFT JOIN `salesrebateinvoice` p3 ON c.`SalesRebateInvoiceID` = p3.`ID`
   SET
       c.`PaymentCPID` = IF((c.`PaymentCPID` IS NOT NULL AND (c.`PaymentCPID` = 0 OR p0.`ID` IS NULL)), NULL, c.`PaymentCPID`),
       c.`SalesRebateID` = IF((c.`SalesRebateID` IS NOT NULL AND (c.`SalesRebateID` = 0 OR p1.`ID` IS NULL)), NULL, c.`SalesRebateID`),
       c.`SalesRebateInvoiceDetailStatusID` = IF((c.`SalesRebateInvoiceDetailStatusID` IS NOT NULL AND (c.`SalesRebateInvoiceDetailStatusID` = 0 OR p2.`ID` IS NULL)), NULL, c.`SalesRebateInvoiceDetailStatusID`),
       c.`SalesRebateInvoiceID` = IF((c.`SalesRebateInvoiceID` IS NOT NULL AND (c.`SalesRebateInvoiceID` = 0 OR p3.`ID` IS NULL)), NULL, c.`SalesRebateInvoiceID`)
 WHERE  (c.`PaymentCPID` IS NOT NULL AND (c.`PaymentCPID` = 0 OR p0.`ID` IS NULL))
    OR (c.`SalesRebateID` IS NOT NULL AND (c.`SalesRebateID` = 0 OR p1.`ID` IS NULL))
    OR (c.`SalesRebateInvoiceDetailStatusID` IS NOT NULL AND (c.`SalesRebateInvoiceDetailStatusID` = 0 OR p2.`ID` IS NULL))
    OR (c.`SalesRebateInvoiceID` IS NOT NULL AND (c.`SalesRebateInvoiceID` = 0 OR p3.`ID` IS NULL))', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '65062f231b06ca8a775d2313d2b6baebf87df31e3605bd7e90062f832522a02b', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- salesrebateinvoicedetail/30_assert  --  source section 7b
-- Orphan assertion over this table's 4 foreign-key relationships.
--
-- This is what pays for 40_fk being fast. The original created the constraints with
-- FOREIGN_KEY_CHECKS ON so a row the cleanup missed would abort the run, and paid for it
-- with a full table copy per constraint. This buys the same protection with one indexed
-- pass, and 40_fk then adds the constraints as metadata only.
--
-- NOT ledger-guarded on the way in, unlike every other phase: it only reads, and the
-- point of it is to be re-runnable. It does record its ledger row -- 40_fk requires it.
--
-- IF THIS ABORTS: a row survived 20_cleanup. Same stop-and-look event the original would
-- have hit as ERROR 1452 inside section 8, but nothing has been created yet.
-- ---------------------------------------------------------------------

SET @step = 'salesrebateinvoicedetail/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `salesrebateinvoicedetail` c
  LEFT JOIN `companycp` p0 ON c.`PaymentCPID` = p0.`ID`
  LEFT JOIN `salesrebate` p1 ON c.`SalesRebateID` = p1.`ID`
  LEFT JOIN `salesrebateinvoicedetailstatus` p2 ON c.`SalesRebateInvoiceDetailStatusID` = p2.`ID`
  LEFT JOIN `salesrebateinvoice` p3 ON c.`SalesRebateInvoiceID` = p3.`ID`
 WHERE  (c.`PaymentCPID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`SalesRebateID` IS NOT NULL AND p1.`ID` IS NULL)
    OR (c.`SalesRebateInvoiceDetailStatusID` IS NOT NULL AND p2.`ID` IS NULL)
    OR (c.`SalesRebateInvoiceID` IS NOT NULL AND p3.`ID` IS NULL);
SET @orphans = @orphans + @n;

-- Two-row subquery on the false branch: ERROR 1242, an abort, before 40_fk runs.
SELECT IF(@orphans = 0,
          'salesrebateinvoicedetail: orphan check OK - 0 rows across 4 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `salesrebateinvoicedetail` still reference a parent that does not exist')
           UNION ALL
           SELECT 'Run 20_cleanup for this table first. Do NOT skip this check.')
       ) AS preflight_orphans;

INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '5b21ef9d440cb6b8b26ff372b3674cc585184ca3d29a3cf463be5563106090e8', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- salesrebateinvoicedetail/40_fk  --  source section 8
-- The constraints, one ALTER for the whole table.
--
-- FOREIGN_KEY_CHECKS is turned OFF for this statement and restored afterwards. With
-- checks on InnoDB cannot add a foreign key in place -- it copies the whole table and
-- re-validates every row, which is where the original migration's 154 table copies
-- came from. The validation is not skipped, it MOVED: 30_assert proves zero orphans
-- and refuses to let this run otherwise.
-- ---------------------------------------------------------------------

SET @fk_prev = @@FOREIGN_KEY_CHECKS;

SET @step = 'salesrebateinvoicedetail/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `salesrebateinvoicedetail`
  ADD CONSTRAINT `salesrebateinvoicedetail_PaymentCPID` FOREIGN KEY (`PaymentCPID`) REFERENCES `companycp` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `salesrebateinvoicedetail_SalesRebateID` FOREIGN KEY (`SalesRebateID`) REFERENCES `salesrebate` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `salesrebateinvoicedetail_SalesRebateInvoiceDetailStatusID` FOREIGN KEY (`SalesRebateInvoiceDetailStatusID`) REFERENCES `salesrebateinvoicedetailstatus` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `salesrebateinvoicedetail_SalesRebateInvoiceID` FOREIGN KEY (`SalesRebateInvoiceID`) REFERENCES `salesrebateinvoice` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '6b43d9348591f1d5717ca2cddbe93d53fbe88c2fc09eebaa5270e794da4cae17', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- --------------------------------------------------------------- postflight
-- DID THE WORK ACTUALLY LAND?
--
-- Every step records itself in `_migration_ledger` immediately after its statement runs,
-- WITHOUT checking that the statement succeeded. That is inherited from step/ unchanged,
-- and there it is safe because run.sh runs mysql without --force, so the first error stops
-- everything. Imported by hand, the client decides -- and "continue on error" would leave
-- failed steps marked applied.
--
-- So this file checks its own work against information_schema before it finishes. It is
-- the only thing here that is NOT copied from step/. It reads; it changes nothing.

-- postflight-set: fk
SET @want_fk = 27;
SELECT COUNT(*), IFNULL(SUBSTRING(GROUP_CONCAT(n ORDER BY n SEPARATOR ', '), 1, 60), '')
  INTO @missn_fk, @miss_fk
  FROM (SELECT 'salesrebate.salesrebate_CCPaymentTerm' AS n UNION ALL SELECT 'salesrebate.salesrebate_CompanyID' UNION ALL SELECT 'salesrebate.salesrebate_DivisionID' UNION ALL SELECT 'salesrebate.salesrebate_IndustryID' UNION ALL SELECT 'salesrebate.salesrebate_ReferenceRebateID' UNION ALL SELECT 'salesrebate.salesrebate_SalesRebateStatusID' UNION ALL SELECT 'salesrebate.salesrebate_UserIDInput' UNION ALL SELECT 'salesrebate.salesrebate_UserIDSales' UNION ALL SELECT 'salesrebateassignment.salesrebateassignment_SalesRebateID' UNION ALL SELECT 'salesrebateassignment.salesrebateassignment_SalesRebateStatusID' UNION ALL SELECT 'salesrebateassignment.salesrebateassignment_UserIDInput' UNION ALL SELECT 'salesrebatedetail.salesrebatedetail_CompanyCPID' UNION ALL SELECT 'salesrebatedetail.salesrebatedetail_SalesRebateID' UNION ALL SELECT 'salesrebateinvoice.salesrebateinvoice_CompanyID' UNION ALL SELECT 'salesrebateinvoice.salesrebateinvoice_DivisionID' UNION ALL SELECT 'salesrebateinvoice.salesrebateinvoice_IndustryID' UNION ALL SELECT 'salesrebateinvoice.salesrebateinvoice_SalesRebateID' UNION ALL SELECT 'salesrebateinvoice.salesrebateinvoice_SalesRebateInvoiceStatusID' UNION ALL SELECT 'salesrebateinvoice.salesrebateinvoice_UserInput' UNION ALL SELECT 'salesrebateinvoiceassignment.salesrebateinvoiceassignment_SalesRebateInvoiceID' UNION ALL SELECT 'salesrebateinvoiceassignment.salesrebateinvoiceassignment_SalesRebateInvoiceStatusID' UNION ALL SELECT 'salesrebateinvoiceassignment.salesrebateinvoiceassignment_UserIDInput' UNION ALL SELECT 'salesrebateinvoicedetail.salesrebateinvoicedetail_PaymentCPID' UNION ALL SELECT 'salesrebateinvoicedetail.salesrebateinvoicedetail_SalesRebateID' UNION ALL SELECT 'salesrebateinvoicedetail.salesrebateinvoicedetail_SalesRebateInvoiceDetailStatusID' UNION ALL SELECT 'salesrebateinvoicedetail.salesrebateinvoicedetail_SalesRebateInvoiceID' UNION ALL SELECT 'salesrebateinvoicepaymentdetail.salesrebateinvoicepaymentdetail_SalesRebateInvoiceDetailID') _w
 WHERE n NOT IN (SELECT CONCAT(TABLE_NAME, '.', CONSTRAINT_NAME) FROM information_schema.TABLE_CONSTRAINTS WHERE CONSTRAINT_SCHEMA = DATABASE() AND CONSTRAINT_TYPE = 'FOREIGN KEY');
SET @have_fk = @want_fk - @missn_fk;
SET @pf_fk = IF(@missn_fk = 0,
    CONCAT('SELECT ''postflight foreign keys: ', @have_fk, '/', @want_fk, ' present'' AS postflight_fk'),
    CONCAT('SELECT `ABORT postflight: MISSING foreign keys: ', @miss_fk,
           ' -- ', @missn_fk, ' of ', @want_fk, ' absent. A step is recorded in',
           ' _migration_ledger but did not take effect.`'));
PREPARE _pf FROM @pf_fk; EXECUTE _pf; DEALLOCATE PREPARE _pf;

-- postflight-set: idx
SET @want_idx = 27;
SELECT COUNT(*), IFNULL(SUBSTRING(GROUP_CONCAT(n ORDER BY n SEPARATOR ', '), 1, 60), '')
  INTO @missn_idx, @miss_idx
  FROM (SELECT 'salesrebate.salesrebate_CCPaymentTerm' AS n UNION ALL SELECT 'salesrebate.salesrebate_CompanyID' UNION ALL SELECT 'salesrebate.salesrebate_DivisionID' UNION ALL SELECT 'salesrebate.salesrebate_IndustryID' UNION ALL SELECT 'salesrebate.salesrebate_ReferenceRebateID' UNION ALL SELECT 'salesrebate.salesrebate_SalesRebateStatusID' UNION ALL SELECT 'salesrebate.salesrebate_UserIDInput' UNION ALL SELECT 'salesrebate.salesrebate_UserIDSales' UNION ALL SELECT 'salesrebateassignment.salesrebateassignment_SalesRebateID' UNION ALL SELECT 'salesrebateassignment.salesrebateassignment_SalesRebateStatusID' UNION ALL SELECT 'salesrebateassignment.salesrebateassignment_UserIDInput' UNION ALL SELECT 'salesrebatedetail.salesrebatedetail_CompanyCPID' UNION ALL SELECT 'salesrebatedetail.salesrebatedetail_SalesRebateID' UNION ALL SELECT 'salesrebateinvoice.salesrebateinvoice_CompanyID' UNION ALL SELECT 'salesrebateinvoice.salesrebateinvoice_DivisionID' UNION ALL SELECT 'salesrebateinvoice.salesrebateinvoice_IndustryID' UNION ALL SELECT 'salesrebateinvoice.salesrebateinvoice_SalesRebateID' UNION ALL SELECT 'salesrebateinvoice.salesrebateinvoice_SalesRebateInvoiceStatusID' UNION ALL SELECT 'salesrebateinvoice.salesrebateinvoice_UserInput' UNION ALL SELECT 'salesrebateinvoiceassignment.salesrebateinvoiceassignment_SalesRebateInvoiceID' UNION ALL SELECT 'salesrebateinvoiceassignment.salesrebateinvoiceassignment_SalesRebateInvoiceStatusID' UNION ALL SELECT 'salesrebateinvoiceassignment.salesrebateinvoiceassignment_UserIDInput' UNION ALL SELECT 'salesrebateinvoicedetail.salesrebateinvoicedetail_PaymentCPID' UNION ALL SELECT 'salesrebateinvoicedetail.salesrebateinvoicedetail_SalesRebateID' UNION ALL SELECT 'salesrebateinvoicedetail.salesrebateinvoicedetail_SalesRebateInvoiceDetailStatusID' UNION ALL SELECT 'salesrebateinvoicedetail.salesrebateinvoicedetail_SalesRebateInvoiceID' UNION ALL SELECT 'salesrebateinvoicepaymentdetail.salesrebateinvoicepaymentdetail_SalesRebateInvoiceDetailID') _w
 WHERE n NOT IN (SELECT CONCAT(TABLE_NAME, '.', INDEX_NAME) FROM information_schema.STATISTICS WHERE TABLE_SCHEMA = DATABASE());
SET @have_idx = @want_idx - @missn_idx;
SET @pf_idx = IF(@missn_idx = 0,
    CONCAT('SELECT ''postflight indexes: ', @have_idx, '/', @want_idx, ' present'' AS postflight_idx'),
    CONCAT('SELECT `ABORT postflight: MISSING indexes: ', @miss_idx,
           ' -- ', @missn_idx, ' of ', @want_idx, ' absent. A step is recorded in',
           ' _migration_ledger but did not take effect.`'));
PREPARE _pf FROM @pf_idx; EXECUTE _pf; DEALLOCATE PREPARE _pf;

-- postflight-set: typ
SET @want_typ = 28;
SELECT COUNT(*), IFNULL(SUBSTRING(GROUP_CONCAT(n ORDER BY n SEPARATOR ', '), 1, 60), '')
  INTO @missn_typ, @miss_typ
  FROM (SELECT 'salesrebate.CCPaymentTerm.int' AS n UNION ALL SELECT 'salesrebate.CompanyID.int' UNION ALL SELECT 'salesrebate.DivisionID.int' UNION ALL SELECT 'salesrebate.IndustryID.int' UNION ALL SELECT 'salesrebate.ReferenceRebateID.int' UNION ALL SELECT 'salesrebate.SalesRebateStatusID.int' UNION ALL SELECT 'salesrebate.UserIDInput.int' UNION ALL SELECT 'salesrebate.UserIDSales.int' UNION ALL SELECT 'salesrebateassignment.SalesRebateID.int' UNION ALL SELECT 'salesrebateassignment.SalesRebateStatusID.int' UNION ALL SELECT 'salesrebateassignment.UserIDInput.int' UNION ALL SELECT 'salesrebatedetail.CompanyCPID.int' UNION ALL SELECT 'salesrebatedetail.Recipient.varchar' UNION ALL SELECT 'salesrebatedetail.SalesRebateID.int' UNION ALL SELECT 'salesrebateinvoice.CompanyID.int' UNION ALL SELECT 'salesrebateinvoice.DivisionID.int' UNION ALL SELECT 'salesrebateinvoice.IndustryID.int' UNION ALL SELECT 'salesrebateinvoice.SalesRebateID.int' UNION ALL SELECT 'salesrebateinvoice.SalesRebateInvoiceStatusID.int' UNION ALL SELECT 'salesrebateinvoice.UserInput.int' UNION ALL SELECT 'salesrebateinvoiceassignment.SalesRebateInvoiceID.int' UNION ALL SELECT 'salesrebateinvoiceassignment.SalesRebateInvoiceStatusID.int' UNION ALL SELECT 'salesrebateinvoiceassignment.UserIDInput.int' UNION ALL SELECT 'salesrebateinvoicedetail.PaymentCPID.int' UNION ALL SELECT 'salesrebateinvoicedetail.SalesRebateID.int' UNION ALL SELECT 'salesrebateinvoicedetail.SalesRebateInvoiceDetailStatusID.int' UNION ALL SELECT 'salesrebateinvoicedetail.SalesRebateInvoiceID.int' UNION ALL SELECT 'salesrebateinvoicepaymentdetail.SalesRebateInvoiceDetailID.int') _w
 WHERE n NOT IN (SELECT CONCAT(TABLE_NAME, '.', COLUMN_NAME, '.', DATA_TYPE) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE());
SET @have_typ = @want_typ - @missn_typ;
SET @pf_typ = IF(@missn_typ = 0,
    CONCAT('SELECT ''postflight retyped columns: ', @have_typ, '/', @want_typ, ' present'' AS postflight_typ'),
    CONCAT('SELECT `ABORT postflight: MISSING retyped columns: ', @miss_typ,
           ' -- ', @missn_typ, ' of ', @want_typ, ' absent. A step is recorded in',
           ' _migration_ledger but did not take effect.`'));
PREPARE _pf FROM @pf_typ; EXECUTE _pf; DEALLOCATE PREPARE _pf;

-- --------------------------------------------------------------- restore
-- IFNULL on all four: if phpMyAdmin resumed this import on a fresh connection the
-- @OLD_ variables are gone, and a bare SET from NULL is ERROR 1231.
--
-- The CAST is on the two timeouts and NOWHERE ELSE, on purpose. An INTEGER system
-- variable rejects IFNULL()'s result type outright (ERROR 1232, every time, not only
-- when NULL). FOREIGN_KEY_CHECKS is a boolean and SQL_MODE is a set; both accept a
-- string result, so they need no CAST. Do not "fix" the asymmetry, and do not copy
-- line 3's shape onto a new integer variable.
SET SESSION lock_wait_timeout = CAST(IFNULL(@OLD_LOCK_WAIT, 86400) AS UNSIGNED);
SET SESSION innodb_lock_wait_timeout = CAST(IFNULL(@OLD_INNODB_LOCK_WAIT, 50) AS UNSIGNED);
