-- Migration: merged replacement for the interim regionalization migrations -- 0006_regions_and_superadmins, 0007_region_columns_backfill, -- 0008_region_cache_versions, and 0009_three_const_tables. -- -- Also folds in the later standalone migrations that used to run after this file: -- * 0007_addresses_bound_id -> addresses.bound_id (+ backfill to 1) -- * 0008_user_creds_unique_and_min_order_cleanup -> user_creds unique index and -- removal of the retired `minRegularOrderValue` -- -- Also folds in 0007_coupon_targets_json (never applied on its own): coupon product -- targeting collapses into `coupons.sku_ids` / `reserved_coupons.sku_ids`, and the -- `coupon_applicable_products` table is folded then dropped leaf-first before the -- rebuild (it references coupons/product_skus). The file does not create a -- replacement for that table. -- -- The originals created two throwaway staging tables purely to copy from and -- then drop them: -- * `region_bound_settings` (created + seeded in 0006, dropped in 0009) -- * `region_cache_versions` (created + seeded in 0008, dropped in 0009) -- This script creates neither. The final tables are seeded directly: -- * global keys + per-region version counters + region-level business keys -- -> `region_consts` (global ones -> `global_consts`) -- * per-bound business keys -> `region_bound_consts` -- (incl. `isFlashDeliveryEnabled`, which each bound switches independently) -- -- Also folds in the later removal of online payments (never applied on its own): -- the app is Cash-on-Delivery only, so `payment_info`, `payments` and `refunds` -- are dropped and the payment flags/columns disappear from `orders` and -- `order_status` (Phase 5). -- -- Phases, kept in the original dependency order: -- 1. regions / region_bounds / superadmins + seeds (from 0006) -- 2. region_id backfill + 31-table rebuild (from 0007) -- 3. global_consts / region_consts / region_bound_consts (from 0008+0009) -- 4. coupon product targets -> `sku_ids` JSON arrays (from 0007_coupon_targets_json) -- 5. online payments / refunds removed (COD only) -- -- Verified: applying this file to apps/backend/dumps/latest.sql yields the same -- schema and the same rows as applying 0006..0009 in order. -- -- NOTE: SQLite has no `ADD COLUMN IF NOT EXISTS`; the CREATEs use IF NOT EXISTS -- so the file is partially re-runnable, but rely on the migration journal to run -- it once. As in 0007, re-running without resetting the database will fail. -- ===================================================================== -- Phase 1 (from 0006): regions, region bounds, and the bootstrap superadmin. -- `region_bound_settings` is not created here; its rows are seeded straight -- into `region_bound_consts` in Phase 3. -- ===================================================================== CREATE TABLE IF NOT EXISTS `regions` ( `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, `name` text NOT NULL, `description` text, `created_at` text DEFAULT (CURRENT_TIMESTAMP) NOT NULL ); --> statement-breakpoint CREATE TABLE IF NOT EXISTS `region_bounds` ( `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, `region_id` integer NOT NULL, `description` text, `geojson` text NOT NULL, `priority` text NOT NULL, `center_lat` real, `center_lng` real, FOREIGN KEY (`region_id`) REFERENCES `regions`(`id`) ON UPDATE no action ON DELETE no action ); --> statement-breakpoint CREATE UNIQUE INDEX IF NOT EXISTS `unique_region_bound_priority` ON `region_bounds` (`region_id`, `priority`); --> statement-breakpoint CREATE TABLE IF NOT EXISTS `superadmins` ( `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, `username` text NOT NULL, `password_hash` text NOT NULL, `created_at` text DEFAULT (CURRENT_TIMESTAMP) NOT NULL ); --> statement-breakpoint CREATE UNIQUE INDEX IF NOT EXISTS `unique_superadmin_username` ON `superadmins` (`username`); --> statement-breakpoint -- Seed region. INSERT INTO `regions` (`name`, `description`) SELECT 'Mahabubnagar', 'Default region (all pre-existing data backfilled here)' WHERE NOT EXISTS (SELECT 1 FROM `regions` WHERE `name` = 'Mahabubnagar'); --> statement-breakpoint -- Seed bounds (exact GeoJSON from apps/backend/src/map-assets/Mbnr-1.geojson / Mbnr-2.geojson). INSERT INTO `region_bounds` (`region_id`, `description`, `geojson`, `priority`) SELECT id, 'Mbnr-1', '{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"name":"Polygon 4"},"geometry":{"type":"Polygon","coordinates":[[[77.9802307,16.7224827],[77.9832452,16.7186281],[77.9885003,16.7191643],[78.0027771,16.7184524],[78.0167635,16.717821],[78.0176657,16.7225884],[78.0245685,16.7301059],[78.0346065,16.7366045],[78.0483126,16.7469324],[78.0558892,16.7506815],[78.0533183,16.7547082],[78.0497798,16.7596596],[78.0456892,16.7640471],[78.0383339,16.7641426],[78.0343234,16.758687],[78.021375,16.7570244],[78.0163704,16.758279],[78.0128516,16.7590231],[78.0120219,16.7648881],[78.0095524,16.7664414],[77.99363,16.7660548],[77.9720422,16.7596124],[77.9679337,16.7449906],[77.9802307,16.7224827]]]}}]}', '1' FROM `regions` WHERE `name` = 'Mahabubnagar' AND NOT EXISTS (SELECT 1 FROM `region_bounds` WHERE `priority` = '1' AND `region_id` = (SELECT id FROM `regions` WHERE `name` = 'Mahabubnagar')); --> statement-breakpoint INSERT INTO `region_bounds` (`region_id`, `description`, `geojson`, `priority`) SELECT id, 'Mbnr-2', '{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"name":"Mbnr-2"},"geometry":{"type":"Polygon","coordinates":[[[77.9773739,16.7127921],[77.9950359,16.7080928],[78.0187929,16.70999],[78.0289444,16.7211582],[78.0570875,16.7502883],[78.0662922,16.7519867],[78.0652719,16.7684088],[78.0204341,16.7689639],[78.0023161,16.770186],[77.9984809,16.7850848],[77.983305,16.782843],[77.971574,16.7646028],[77.9686551,16.7454905],[77.9773739,16.7127921]]]}}]}', '2' FROM `regions` WHERE `name` = 'Mahabubnagar' AND NOT EXISTS (SELECT 1 FROM `region_bounds` WHERE `priority` = '2' AND `region_id` = (SELECT id FROM `regions` WHERE `name` = 'Mahabubnagar')); --> statement-breakpoint -- Bootstrap superadmin (password hash supplied by the product owner; stored as-is, never re-hashed). INSERT INTO `superadmins` (`username`, `password_hash`) SELECT 'superadmin', '$2a$12$pDL1ooXdvmdpCFpeXgEnB.7eRot4ygtL/Z9lSmW8ApjRLAhTiuOCu' WHERE NOT EXISTS (SELECT 1 FROM `superadmins` WHERE `username` = 'superadmin'); -- To add (or re-add) a superadmin manually, run: -- INSERT INTO `superadmins` (`username`, `password_hash`) -- VALUES ('superadmin', '$2a$12$pDL1ooXdvmdpCFpeXgEnB.7eRot4ygtL/Z9lSmW8ApjRLAhTiuOCu'); -- (password_hash is a bcrypt hash stored as-is, never re-hashed; username must be unique) --> statement-breakpoint -- Migration: rebuild the region-ownership FK subgraph with `region_id NOT NULL` -- pointing at the Mahabubnagar region created in 0006, and repair legacy orphan -- rows that were written before FK enforcement (they would fail the copy). -- -- Single pass — no ALTER ADD COLUMN phase. `region_id` is added by the rebuild -- itself and its value is computed at DB level in each copy SELECT -- ((SELECT id FROM regions WHERE name='Mahabubnagar')), never by app defaults. -- -- Follows docs/recreate-referenced-tables.md: create/copy parent-first, drop -- leaf-first, rename parent-first, recreate indexes last. D1 enforces FKs and -- ignores both FK pragmas, so the whole connected subgraph is rebuilt. -- -- NOTE: re-running without resetting the database will fail (tables already -- exist / columns already added). Reset the local D1 state and re-apply 0006 -- first when starting over. -- ===================================================================== -- Repair legacy orphan rows (must run before any copy: the rebuilt tables -- declare FKs, and inserting live orphan rows into them is a constraint -- violation). -- -- Live-DB findings this is sized for: -- * 5 orders whose address no longer exists (their dependents deleted too, -- per product-owner decision; purchase history for these is dropped). -- (`payments` / `refunds` orphans are irrelevant now: both tables are dropped -- in Phase 5, and no order was ever placed as an online payment.) -- ===================================================================== -- Detach coupon usage / complaints / incidents from the orphan orders before -- removing the orders themselves (columns are nullable; deleting usage rows -- entirely would also lose coupon history tied to surviving behavior). UPDATE `coupon_usage` SET `order_item_id` = NULL WHERE `order_item_id` IN (SELECT `oi`.`id` FROM `order_items` `oi` JOIN `orders` `o` ON `o`.`id` = `oi`.`order_id` WHERE `o`.`address_id` NOT IN (SELECT `id` FROM `addresses`)); --> statement-breakpoint UPDATE `coupon_usage` SET `order_id` = NULL WHERE `order_id` IN (SELECT `id` FROM `orders` WHERE `address_id` NOT IN (SELECT `id` FROM `addresses`)); --> statement-breakpoint UPDATE `complaints` SET `order_id` = NULL WHERE `order_id` IN (SELECT `id` FROM `orders` WHERE `address_id` NOT IN (SELECT `id` FROM `addresses`)); --> statement-breakpoint UPDATE `user_incidents` SET `order_id` = NULL WHERE `order_id` IN (SELECT `id` FROM `orders` WHERE `address_id` NOT IN (SELECT `id` FROM `addresses`)); --> statement-breakpoint -- Delete the orphan orders' remaining hard dependents (their copies into the -- rebuilt tables would otherwise fail first). DELETE FROM `order_status` WHERE `order_id` IN (SELECT `id` FROM `orders` WHERE `address_id` NOT IN (SELECT `id` FROM `addresses`)); --> statement-breakpoint DELETE FROM `order_items` WHERE `order_id` IN (SELECT `id` FROM `orders` WHERE `address_id` NOT IN (SELECT `id` FROM `addresses`)); --> statement-breakpoint DELETE FROM `orders` WHERE `id` IN (SELECT `id` FROM `orders` WHERE `address_id` NOT IN (SELECT `id` FROM `addresses`)) AND `address_id` NOT IN (SELECT `id` FROM `addresses`); --> statement-breakpoint -- Sanity: no more orphan rows against the tables we keep. -- (Not verifiable in plain SQL execution; validated post-migration with -- PRAGMA foreign_key_check and row counts.) -- ===================================================================== -- Rebuild phase. 31 tables: create `__new_*` (parents first), copy all -- columns, drop originals leaf-first, rename parents first, recreate indexes. -- ===================================================================== CREATE TABLE `__new_staff_users` ( `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, `name` text NOT NULL, `password` text NOT NULL, `staff_role_id` integer, `created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL, `region_id` integer NOT NULL, FOREIGN KEY (`staff_role_id`) REFERENCES `staff_roles`(`id`) ON UPDATE no action ON DELETE no action, FOREIGN KEY (`region_id`) REFERENCES `regions`(`id`) ON UPDATE no action ON DELETE no action ); --> statement-breakpoint INSERT INTO `__new_staff_users` (`id`,`name`,`password`,`staff_role_id`,`created_at`,`region_id`) SELECT `id`,`name`,`password`,`staff_role_id`,`created_at`,(SELECT `id` FROM `regions` WHERE `name` = 'Mahabubnagar') FROM `staff_users`; --> statement-breakpoint CREATE TABLE `__new_staff_notif_creds` ( `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, `token` text NOT NULL, `added_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL, `staff_user_id` integer NOT NULL, `last_verified` text, FOREIGN KEY (`staff_user_id`) REFERENCES `__new_staff_users`(`id`) ON UPDATE no action ON DELETE no action ); --> statement-breakpoint INSERT INTO `__new_staff_notif_creds` (`id`,`token`,`added_at`,`staff_user_id`,`last_verified`) SELECT `id`,`token`,`added_at`,`staff_user_id`,`last_verified` FROM `staff_notif_creds`; --> statement-breakpoint CREATE TABLE `__new_store_info` ( `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, `name` text NOT NULL, `description` text, `image_url` text, `created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL, `region_id` integer, `is_global` integer DEFAULT false NOT NULL, FOREIGN KEY (`region_id`) REFERENCES `regions`(`id`) ON UPDATE no action ON DELETE no action ); --> statement-breakpoint INSERT INTO `__new_store_info` (`id`,`name`,`description`,`image_url`,`created_at`,`region_id`,`is_global`) SELECT `id`,`name`,`description`,`image_url`,`created_at`,(SELECT `id` FROM `regions` WHERE `name` = 'Mahabubnagar'),false FROM `store_info`; --> statement-breakpoint CREATE TABLE `__new_product_info` ( `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, `name` text NOT NULL, `short_description` text, `long_description` text, `store_id` integer, `increment_step` real DEFAULT 1 NOT NULL, `created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL, `product_type` text DEFAULT 'item' NOT NULL, `region_id` integer, FOREIGN KEY (`store_id`) REFERENCES `__new_store_info`(`id`) ON UPDATE no action ON DELETE no action, FOREIGN KEY (`region_id`) REFERENCES `regions`(`id`) ON UPDATE no action ON DELETE no action ); --> statement-breakpoint INSERT INTO `__new_product_info` (`id`,`name`,`short_description`,`long_description`,`store_id`,`increment_step`,`created_at`,`product_type`,`region_id`) SELECT `id`,`name`,`short_description`,`long_description`,`store_id`,`increment_step`,`created_at`,`product_type`,(SELECT `id` FROM `regions` WHERE `name` = 'Mahabubnagar') FROM `product_info`; --> statement-breakpoint CREATE TABLE `__new_product_tag_info` ( `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, `tag_name` text NOT NULL, `tag_description` text, `image_url` text, `is_dashboard_tag` integer DEFAULT false NOT NULL, `related_stores` text, `sort_order` text DEFAULT '[]', `created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL, `region_id` integer NOT NULL, FOREIGN KEY (`region_id`) REFERENCES `regions`(`id`) ON UPDATE no action ON DELETE no action ); --> statement-breakpoint INSERT INTO `__new_product_tag_info` (`id`,`tag_name`,`tag_description`,`image_url`,`is_dashboard_tag`,`related_stores`,`sort_order`,`created_at`,`region_id`) SELECT `id`,`tag_name`,`tag_description`,`image_url`,`is_dashboard_tag`,`related_stores`,`sort_order`,`created_at`,(SELECT `id` FROM `regions` WHERE `name` = 'Mahabubnagar') FROM `product_tag_info`; --> statement-breakpoint CREATE TABLE `__new_product_group_info` ( `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, `group_name` text NOT NULL, `description` text, `created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL, `region_id` integer NOT NULL, FOREIGN KEY (`region_id`) REFERENCES `regions`(`id`) ON UPDATE no action ON DELETE no action ); --> statement-breakpoint INSERT INTO `__new_product_group_info` (`id`,`group_name`,`description`,`created_at`,`region_id`) SELECT `id`,`group_name`,`description`,`created_at`,(SELECT `id` FROM `regions` WHERE `name` = 'Mahabubnagar') FROM `product_group_info`; --> statement-breakpoint CREATE TABLE `__new_delivery_slot_info` ( `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, `delivery_time` text NOT NULL, `freeze_time` text NOT NULL, `is_active` integer DEFAULT true NOT NULL, `is_flash` integer DEFAULT false NOT NULL, `is_capacity_full` integer DEFAULT false NOT NULL, `delivery_sequence` text, `group_ids` text, `sku_ids` text, `region_id` integer NOT NULL, FOREIGN KEY (`region_id`) REFERENCES `regions`(`id`) ON UPDATE no action ON DELETE no action ); --> statement-breakpoint INSERT INTO `__new_delivery_slot_info` (`id`,`delivery_time`,`freeze_time`,`is_active`,`is_flash`,`is_capacity_full`,`delivery_sequence`,`group_ids`,`sku_ids`,`region_id`) SELECT `id`,`delivery_time`,`freeze_time`,`is_active`,`is_flash`,`is_capacity_full`,`delivery_sequence`,`group_ids`,`sku_ids`,(SELECT `id` FROM `regions` WHERE `name` = 'Mahabubnagar') FROM `delivery_slot_info`; --> statement-breakpoint CREATE TABLE `__new_vendor_snippets` ( `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, `snippet_code` text NOT NULL, `slot_id` integer, `is_permanent` integer DEFAULT false NOT NULL, `sku_ids` text NOT NULL, `valid_till` text, `created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL, `region_id` integer NOT NULL, FOREIGN KEY (`slot_id`) REFERENCES `__new_delivery_slot_info`(`id`) ON UPDATE no action ON DELETE no action, FOREIGN KEY (`region_id`) REFERENCES `regions`(`id`) ON UPDATE no action ON DELETE no action ); --> statement-breakpoint INSERT INTO `__new_vendor_snippets` (`id`,`snippet_code`,`slot_id`,`is_permanent`,`sku_ids`,`valid_till`,`created_at`,`region_id`) SELECT `id`,`snippet_code`,`slot_id`,`is_permanent`,`sku_ids`,`valid_till`,`created_at`,(SELECT `id` FROM `regions` WHERE `name` = 'Mahabubnagar') FROM `vendor_snippets`; --> statement-breakpoint CREATE TABLE `__new_home_banners` ( `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, `name` text NOT NULL, `image_url` text NOT NULL, `description` text, `sku_ids` text, `redirect_url` text, `serial_num` integer, `is_active` integer DEFAULT false NOT NULL, `created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL, `last_updated` text DEFAULT CURRENT_TIMESTAMP NOT NULL, `region_id` integer NOT NULL, FOREIGN KEY (`region_id`) REFERENCES `regions`(`id`) ON UPDATE no action ON DELETE no action ); --> statement-breakpoint INSERT INTO `__new_home_banners` (`id`,`name`,`image_url`,`description`,`sku_ids`,`redirect_url`,`serial_num`,`is_active`,`created_at`,`last_updated`,`region_id`) SELECT `id`,`name`,`image_url`,`description`,`sku_ids`,`redirect_url`,`serial_num`,`is_active`,`created_at`,`last_updated`,(SELECT `id` FROM `regions` WHERE `name` = 'Mahabubnagar') FROM `home_banners`; --> statement-breakpoint CREATE TABLE `__new_addresses` ( `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, `user_id` integer NOT NULL, `name` text NOT NULL, `phone` text NOT NULL, `address_line1` text NOT NULL, `address_line2` text, `city` text NOT NULL, `state` text NOT NULL, `is_default` integer DEFAULT false NOT NULL, `latitude` real, `longitude` real, `google_maps_url` text, `admin_latitude` real, `admin_longitude` real, `zone_id` integer, `created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL, `region_id` integer NOT NULL, `bound_id` integer, `vague_backfilled_coords` integer DEFAULT false NOT NULL, FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE no action, FOREIGN KEY (`region_id`) REFERENCES `regions`(`id`) ON UPDATE no action ON DELETE no action, FOREIGN KEY (`bound_id`) REFERENCES `region_bounds`(`id`) ON UPDATE no action ON DELETE no action ); --> statement-breakpoint -- Prefer the admin-pinned coordinates over the user's coordinates; fall back to -- the Mahabubnagar centre only when neither is available. `vague` is set only -- when a coordinate actually had to use that centre. INSERT INTO `__new_addresses` (`id`,`user_id`,`name`,`phone`,`address_line1`,`address_line2`,`city`,`state`,`is_default`,`latitude`,`longitude`,`google_maps_url`,`admin_latitude`,`admin_longitude`,`zone_id`,`created_at`,`region_id`,`bound_id`,`vague_backfilled_coords`) SELECT `id`,`user_id`,`name`,`phone`,`address_line1`,`address_line2`,`city`,`state`,`is_default`,COALESCE(`admin_latitude`, `latitude`, 16.750504),COALESCE(`admin_longitude`, `longitude`, 77.993621),`google_maps_url`,`admin_latitude`,`admin_longitude`,`zone_id`,`created_at`,(SELECT `id` FROM `regions` WHERE `name` = 'Mahabubnagar'),(SELECT `id` FROM `region_bounds` WHERE `region_id` = (SELECT `id` FROM `regions` WHERE `name` = 'Mahabubnagar') ORDER BY CAST(`priority` AS REAL) ASC LIMIT 1),CASE WHEN COALESCE(`admin_latitude`, `latitude`) IS NULL OR COALESCE(`admin_longitude`, `longitude`) IS NULL THEN 1 ELSE 0 END FROM `addresses`; --> statement-breakpoint -- Fold relation-table coupon targets into `coupons.sku_ids` before the rebuild -- copies that column. `coupon_applicable_products` is a leaf of -- coupons/product_skus, so it is dropped in the leaf-first drop block below. UPDATE `coupons` SET `sku_ids` = ( SELECT json_group_array(`sku`) FROM ( SELECT DISTINCT `sku` FROM ( SELECT CAST(je.`value` AS INTEGER) AS `sku` FROM json_each(CASE WHEN json_valid(`coupons`.`sku_ids`) THEN `coupons`.`sku_ids` ELSE '[]' END) AS je UNION SELECT cap.`sku_id` AS `sku` FROM `coupon_applicable_products` AS cap WHERE cap.`coupon_id` = `coupons`.`id` ) ) ) WHERE EXISTS ( SELECT 1 FROM `coupon_applicable_products` AS cap WHERE cap.`coupon_id` = `coupons`.`id` ); --> statement-breakpoint CREATE TABLE `__new_coupons` ( `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, `coupon_code` text NOT NULL, `is_user_based` integer DEFAULT false NOT NULL, `discount_percent` text, `flat_discount` text, `min_order` text, `sku_ids` text, `created_by` integer, `max_value` text, `is_apply_for_all` integer DEFAULT false NOT NULL, `valid_till` text, `max_limit_for_user` integer, `is_invalidated` integer DEFAULT false NOT NULL, `exclusive_apply` integer DEFAULT false NOT NULL, `is_first_order_only` integer DEFAULT false NOT NULL, `created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL, -- Nullable: NULL means the coupon is global (valid in every region, created by superadmin). `region_id` integer, FOREIGN KEY (`created_by`) REFERENCES `__new_staff_users`(`id`) ON UPDATE no action ON DELETE no action, FOREIGN KEY (`region_id`) REFERENCES `regions`(`id`) ON UPDATE no action ON DELETE no action ); --> statement-breakpoint INSERT INTO `__new_coupons` (`id`,`coupon_code`,`is_user_based`,`discount_percent`,`flat_discount`,`min_order`,`sku_ids`,`created_by`,`max_value`,`is_apply_for_all`,`valid_till`,`max_limit_for_user`,`is_invalidated`,`exclusive_apply`,`is_first_order_only`,`created_at`,`region_id`) SELECT `id`,`coupon_code`,`is_user_based`,`discount_percent`,`flat_discount`,`min_order`,`sku_ids`,`created_by`,`max_value`,`is_apply_for_all`,`valid_till`,`max_limit_for_user`,`is_invalidated`,`exclusive_apply`,`is_first_order_only`,`created_at`,(SELECT `id` FROM `regions` WHERE `name` = 'Mahabubnagar') FROM `coupons`; --> statement-breakpoint CREATE TABLE `__new_product_skus` ( `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, `product_id` integer NOT NULL, `name` text, `images` text, `is_combo_only` integer DEFAULT false NOT NULL, `is_deleted` integer DEFAULT false NOT NULL, `is_suspended` integer DEFAULT false NOT NULL, `created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL, FOREIGN KEY (`product_id`) REFERENCES `__new_product_info`(`id`) ON UPDATE no action ON DELETE no action ); --> statement-breakpoint INSERT INTO `__new_product_skus` (`id`,`product_id`,`name`,`images`,`is_combo_only`,`is_deleted`,`is_suspended`,`created_at`) SELECT `ps`.`id`,`ps`.`product_id`,`ps`.`name`,`ps`.`images`,`ps`.`is_combo_only`,`ps`.`is_deleted`,COALESCE((SELECT `ms`.`is_suspended` FROM `product_market_stats` `ms` WHERE `ms`.`sku_id` = `ps`.`id`), false),`ps`.`created_at` FROM `product_skus` `ps`; --> statement-breakpoint CREATE TABLE `__new_product_market_stats` ( `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, `sku_id` integer NOT NULL, `region_id` integer NOT NULL, `market_price` text, `our_price` text NOT NULL, `is_flash_available` integer DEFAULT false NOT NULL, `flash_price` text, `is_out_of_stock` integer DEFAULT false NOT NULL, `is_suspended_in_region` integer DEFAULT false NOT NULL, `is_offer` integer DEFAULT false NOT NULL, FOREIGN KEY (`sku_id`) REFERENCES `__new_product_skus`(`id`) ON UPDATE no action ON DELETE no action, FOREIGN KEY (`region_id`) REFERENCES `regions`(`id`) ON UPDATE no action ON DELETE no action ); --> statement-breakpoint INSERT INTO `__new_product_market_stats` (`id`,`sku_id`,`region_id`,`market_price`,`our_price`,`is_flash_available`,`flash_price`,`is_out_of_stock`,`is_suspended_in_region`,`is_offer`) SELECT ms.`id`,ms.`sku_id`,(SELECT `id` FROM `regions` WHERE `name` = 'Mahabubnagar'),ms.`market_price`,ms.`our_price`,ms.`is_flash_available`,ms.`flash_price`,ms.`is_out_of_stock`,false,COALESCE(ps.`is_offer`,false) FROM `product_market_stats` ms JOIN `product_skus` ps ON ps.`id` = ms.`sku_id`; --> statement-breakpoint CREATE TABLE `__new_sku_features` ( `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, `sku_id` integer NOT NULL, `feature_name` text, `feature_value` text NOT NULL, FOREIGN KEY (`sku_id`) REFERENCES `__new_product_skus`(`id`) ON UPDATE no action ON DELETE no action ); --> statement-breakpoint INSERT INTO `__new_sku_features` (`id`,`sku_id`,`feature_name`,`feature_value`) SELECT `id`,`sku_id`,`feature_name`,`feature_value` FROM `sku_features`; --> statement-breakpoint CREATE TABLE `__new_product_combos` ( `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, `combo_sku_id` integer NOT NULL, `sku_id` integer NOT NULL, FOREIGN KEY (`combo_sku_id`) REFERENCES `__new_product_skus`(`id`) ON UPDATE no action ON DELETE no action, FOREIGN KEY (`sku_id`) REFERENCES `__new_product_skus`(`id`) ON UPDATE no action ON DELETE no action ); --> statement-breakpoint INSERT INTO `__new_product_combos` (`id`,`combo_sku_id`,`sku_id`) SELECT `id`,`combo_sku_id`,`sku_id` FROM `product_combos`; --> statement-breakpoint CREATE TABLE `__new_special_deals` ( `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, `sku_id` integer NOT NULL, `quantity` text NOT NULL, `price` text NOT NULL, `valid_till` text NOT NULL, FOREIGN KEY (`sku_id`) REFERENCES `__new_product_skus`(`id`) ON UPDATE no action ON DELETE no action ); --> statement-breakpoint INSERT INTO `__new_special_deals` (`id`,`sku_id`,`quantity`,`price`,`valid_till`) SELECT `id`,`sku_id`,`quantity`,`price`,`valid_till` FROM `special_deals`; --> statement-breakpoint CREATE TABLE `__new_product_reviews` ( `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, `user_id` integer NOT NULL, `product_id` integer NOT NULL, `review_body` text NOT NULL, `image_urls` text, `review_time` text DEFAULT CURRENT_TIMESTAMP NOT NULL, `ratings` real NOT NULL, `admin_response` text, `admin_response_images` text, FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE no action, FOREIGN KEY (`product_id`) REFERENCES `__new_product_info`(`id`) ON UPDATE no action ON DELETE no action, CONSTRAINT "rating_check" CHECK(`ratings` >= 1 AND `ratings` <= 5) ); --> statement-breakpoint INSERT INTO `__new_product_reviews` (`id`,`user_id`,`product_id`,`review_body`,`image_urls`,`review_time`,`ratings`,`admin_response`,`admin_response_images`) SELECT `id`,`user_id`,`product_id`,`review_body`,`image_urls`,`review_time`,`ratings`,`admin_response`,`admin_response_images` FROM `product_reviews`; --> statement-breakpoint CREATE TABLE `__new_product_tags` ( `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, `product_id` integer NOT NULL, `tag_id` integer NOT NULL, `assigned_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL, FOREIGN KEY (`product_id`) REFERENCES `__new_product_skus`(`id`) ON UPDATE no action ON DELETE no action, FOREIGN KEY (`tag_id`) REFERENCES `__new_product_tag_info`(`id`) ON UPDATE no action ON DELETE no action ); --> statement-breakpoint INSERT INTO `__new_product_tags` (`id`,`product_id`,`tag_id`,`assigned_at`) SELECT `id`,`product_id`,`tag_id`,`assigned_at` FROM `product_tags`; --> statement-breakpoint CREATE TABLE `__new_product_group_membership` ( `product_id` integer NOT NULL, `group_id` integer NOT NULL, `added_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL, PRIMARY KEY (`product_id`,`group_id`), FOREIGN KEY (`product_id`) REFERENCES `__new_product_skus`(`id`) ON UPDATE no action ON DELETE no action, FOREIGN KEY (`group_id`) REFERENCES `__new_product_group_info`(`id`) ON UPDATE no action ON DELETE no action ); --> statement-breakpoint INSERT INTO `__new_product_group_membership` (`product_id`,`group_id`,`added_at`) SELECT `product_id`,`group_id`,`added_at` FROM `product_group_membership`; --> statement-breakpoint CREATE TABLE `__new_orders` ( `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, `user_id` integer NOT NULL, `address_id` integer NOT NULL, `slot_id` integer, `total_amount` text NOT NULL, `delivery_charge` text DEFAULT '0' NOT NULL, `discount_amount` text DEFAULT '0' NOT NULL, `readable_id` integer NOT NULL, `admin_notes` text, `user_notes` text, `order_group_id` text, `order_group_proportion` text, `is_flash_delivery` integer DEFAULT false NOT NULL, `created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL, `delivered_at` text, `items_json` text, `items_archived_at` text, `region_id` integer NOT NULL, FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE no action, FOREIGN KEY (`address_id`) REFERENCES `__new_addresses`(`id`) ON UPDATE no action ON DELETE no action, FOREIGN KEY (`slot_id`) REFERENCES `__new_delivery_slot_info`(`id`) ON UPDATE no action ON DELETE no action, FOREIGN KEY (`region_id`) REFERENCES `regions`(`id`) ON UPDATE no action ON DELETE no action ); --> statement-breakpoint WITH `archive_candidate` AS ( SELECT o.`id` AS `order_id`, (SELECT COUNT(*) FROM `order_items` `oi` WHERE `oi`.`order_id` = o.`id`) AS `source_count`, (SELECT json_group_array(json_object( 'id', `oi`.`id`, 'skuId', `oi`.`sku_id`, 'quantity', `oi`.`quantity`, 'price', `oi`.`price`, 'discountedPrice', `oi`.`discounted_price`, 'isPackaged', json(CASE WHEN `oi`.`is_packaged` = 1 THEN 'true' ELSE 'false' END), 'isPackageVerified', json(CASE WHEN `oi`.`is_package_verified` = 1 THEN 'true' ELSE 'false' END), 'packagedAt', `oi`.`packaged_at`, 'productName', `p`.`name`, 'skuName', `ps`.`name`, 'image', CASE WHEN json_valid(`ps`.`images`) THEN json_extract(`ps`.`images`, '$[0]') END, 'features', json(COALESCE(( SELECT json_group_array(json_object( 'featureName', `f`.`feature_name`, 'featureValue', `f`.`feature_value` )) FROM `sku_features` `f` WHERE `f`.`sku_id` = `oi`.`sku_id` ), '[]')) )) FROM `order_items` `oi` LEFT JOIN `product_skus` `ps` ON `ps`.`id` = `oi`.`sku_id` LEFT JOIN `product_info` `p` ON `p`.`id` = `ps`.`product_id` WHERE `oi`.`order_id` = o.`id`) AS `items_json` FROM `orders` o WHERE date(datetime(o.`created_at`), '+5 hours', '+30 minutes') < date(datetime('now'), '+5 hours', '+30 minutes', '-2 days') ), `archive_valid` AS ( SELECT c.*, (c.`source_count` >= 1 AND json_valid(c.`items_json`) AND json_array_length(c.`items_json`) = c.`source_count` AND (SELECT COUNT(DISTINCT CAST(json_extract(`je`.`value`, '$.id') AS INTEGER)) FROM json_each(c.`items_json`) `je`) = c.`source_count` AND NOT EXISTS ( SELECT 1 FROM `order_items` `oi` LEFT JOIN `product_skus` `ps` ON `ps`.`id` = `oi`.`sku_id` LEFT JOIN `product_info` `p` ON `p`.`id` = `ps`.`product_id` WHERE `oi`.`order_id` = c.`order_id` AND (`ps`.`id` IS NULL OR `p`.`name` IS NULL OR `p`.`name` = '' OR `oi`.`quantity` IS NULL OR `oi`.`quantity` = '' OR `oi`.`quantity` NOT GLOB '*[0-9]*' OR `oi`.`quantity` GLOB '*[^0-9.]*' OR `oi`.`quantity` GLOB '*.*.*' OR CAST(`oi`.`quantity` AS REAL) <= 0 OR `oi`.`price` IS NULL OR `oi`.`price` = '' OR `oi`.`price` NOT GLOB '*[0-9]*' OR `oi`.`price` GLOB '*[^0-9.]*' OR `oi`.`price` GLOB '*.*.*' OR CAST(`oi`.`price` AS REAL) < 0 OR (`oi`.`discounted_price` IS NOT NULL AND ( `oi`.`discounted_price` = '' OR `oi`.`discounted_price` NOT GLOB '*[0-9]*' OR `oi`.`discounted_price` GLOB '*[^0-9.]*' OR `oi`.`discounted_price` GLOB '*.*.*' OR CAST(`oi`.`discounted_price` AS REAL) < 0 )) OR (`oi`.`packaged_at` IS NOT NULL AND datetime(`oi`.`packaged_at`) IS NULL) ))) AS `ok` FROM `archive_candidate` c ) INSERT INTO `__new_orders` (`id`,`user_id`,`address_id`,`slot_id`,`total_amount`,`delivery_charge`,`discount_amount`,`readable_id`,`admin_notes`,`user_notes`,`order_group_id`,`order_group_proportion`,`is_flash_delivery`,`created_at`,`delivered_at`,`items_json`,`items_archived_at`,`region_id`) SELECT o.`id`,o.`user_id`,o.`address_id`,o.`slot_id`,o.`total_amount`,o.`delivery_charge`,'0',o.`readable_id`,o.`admin_notes`,o.`user_notes`,o.`order_group_id`,o.`order_group_proportion`,o.`is_flash_delivery`,o.`created_at`,o.`delivered_at`,CASE WHEN v.`ok` THEN v.`items_json` END,CASE WHEN v.`ok` THEN CURRENT_TIMESTAMP END,(SELECT `id` FROM `regions` WHERE `name` = 'Mahabubnagar') FROM `orders` o LEFT JOIN `archive_valid` v ON v.`order_id` = o.`id`; --> statement-breakpoint CREATE TABLE `__new_order_items` ( `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, `order_id` integer NOT NULL, `sku_id` integer NOT NULL, `quantity` text NOT NULL, `price` text NOT NULL, `discounted_price` text, `is_packaged` integer DEFAULT false NOT NULL, `is_package_verified` integer DEFAULT false NOT NULL, `packaged_at` text, FOREIGN KEY (`order_id`) REFERENCES `__new_orders`(`id`) ON UPDATE no action ON DELETE no action, FOREIGN KEY (`sku_id`) REFERENCES `__new_product_skus`(`id`) ON UPDATE no action ON DELETE no action ); --> statement-breakpoint INSERT INTO `__new_order_items` (`id`,`order_id`,`sku_id`,`quantity`,`price`,`discounted_price`,`is_packaged`,`is_package_verified`,`packaged_at`) SELECT `id`,`order_id`,`sku_id`,`quantity`,`price`,`discounted_price`,`is_packaged`,`is_package_verified`,`packaged_at` FROM `order_items`; --> statement-breakpoint -- Orders archived into `orders.items_json` keep no rows in the hot table. DELETE FROM `__new_order_items` WHERE `order_id` IN (SELECT `id` FROM `__new_orders` WHERE `items_json` IS NOT NULL); --> statement-breakpoint CREATE TABLE `__new_order_status` ( `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, `order_time` text DEFAULT CURRENT_TIMESTAMP NOT NULL, `user_id` integer NOT NULL, `order_id` integer NOT NULL, `is_packaged` integer DEFAULT false NOT NULL, `is_delivered` integer DEFAULT false NOT NULL, `is_cancelled` integer DEFAULT false NOT NULL, `cancel_reason` text, `is_cancelled_by_admin` integer, `cancellation_user_notes` text, `cancellation_admin_notes` text, `cancellation_reviewed` integer DEFAULT false NOT NULL, `cancellation_reviewed_at` text, FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE no action, FOREIGN KEY (`order_id`) REFERENCES `__new_orders`(`id`) ON UPDATE no action ON DELETE no action ); --> statement-breakpoint INSERT INTO `__new_order_status` (`id`,`order_time`,`user_id`,`order_id`,`is_packaged`,`is_delivered`,`is_cancelled`,`cancel_reason`,`is_cancelled_by_admin`,`cancellation_user_notes`,`cancellation_admin_notes`,`cancellation_reviewed`,`cancellation_reviewed_at`) SELECT `id`,`order_time`,`user_id`,`order_id`,`is_packaged`,`is_delivered`,`is_cancelled`,`cancel_reason`,`is_cancelled_by_admin`,`cancellation_user_notes`,`cancellation_admin_notes`,`cancellation_reviewed`,`cancellation_reviewed_at` FROM `order_status`; --> statement-breakpoint CREATE TABLE `__new_coupon_usage` ( `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, `user_id` integer NOT NULL, `coupon_id` integer NOT NULL, `order_id` integer, `order_item_id` integer, `used_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL, FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE no action, FOREIGN KEY (`coupon_id`) REFERENCES `__new_coupons`(`id`) ON UPDATE no action ON DELETE no action, FOREIGN KEY (`order_id`) REFERENCES `__new_orders`(`id`) ON UPDATE no action ON DELETE no action, FOREIGN KEY (`order_item_id`) REFERENCES `__new_order_items`(`id`) ON UPDATE no action ON DELETE no action ); --> statement-breakpoint INSERT INTO `__new_coupon_usage` (`id`,`user_id`,`coupon_id`,`order_id`,`order_item_id`,`used_at`) SELECT `id`,`user_id`,`coupon_id`,`order_id`,`order_item_id`,`used_at` FROM `coupon_usage`; --> statement-breakpoint CREATE TABLE `__new_coupon_applicable_users` ( `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, `coupon_id` integer NOT NULL, `user_id` integer NOT NULL, FOREIGN KEY (`coupon_id`) REFERENCES `__new_coupons`(`id`) ON UPDATE no action ON DELETE no action, FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE no action ); --> statement-breakpoint INSERT INTO `__new_coupon_applicable_users` (`id`,`coupon_id`,`user_id`) SELECT `id`,`coupon_id`,`user_id` FROM `coupon_applicable_users`; --> statement-breakpoint CREATE TABLE `__new_reserved_coupons` ( `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, `secret_code` text NOT NULL, `coupon_code` text NOT NULL, `discount_percent` text, `flat_discount` text, `min_order` text, `sku_ids` text, `max_value` text, `valid_till` text, `max_limit_for_user` integer, `exclusive_apply` integer DEFAULT false NOT NULL, `is_first_order_only` integer DEFAULT false NOT NULL, `is_redeemed` integer DEFAULT false NOT NULL, `redeemed_by` integer, `redeemed_at` text, `created_by` integer NOT NULL, `created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL, `region_id` integer NOT NULL, FOREIGN KEY (`redeemed_by`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE no action, FOREIGN KEY (`created_by`) REFERENCES `__new_staff_users`(`id`) ON UPDATE no action ON DELETE no action, FOREIGN KEY (`region_id`) REFERENCES `regions`(`id`) ON UPDATE no action ON DELETE no action ); --> statement-breakpoint INSERT INTO `__new_reserved_coupons` (`id`,`secret_code`,`coupon_code`,`discount_percent`,`flat_discount`,`min_order`,`sku_ids`,`max_value`,`valid_till`,`max_limit_for_user`,`exclusive_apply`,`is_first_order_only`,`is_redeemed`,`redeemed_by`,`redeemed_at`,`created_by`,`created_at`,`region_id`) SELECT `id`,`secret_code`,`coupon_code`,`discount_percent`,`flat_discount`,`min_order`,`sku_ids`,`max_value`,`valid_till`,`max_limit_for_user`,`exclusive_apply`,`is_first_order_only`,`is_redeemed`,`redeemed_by`,`redeemed_at`,`created_by`,`created_at`,(SELECT `id` FROM `regions` WHERE `name` = 'Mahabubnagar') FROM `reserved_coupons`; --> statement-breakpoint CREATE TABLE `__new_cart_items` ( `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, `user_id` integer NOT NULL, `sku_id` integer NOT NULL, `quantity` text NOT NULL, `added_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL, FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE no action, FOREIGN KEY (`sku_id`) REFERENCES `__new_product_skus`(`id`) ON UPDATE no action ON DELETE no action ); --> statement-breakpoint INSERT INTO `__new_cart_items` (`id`,`user_id`,`sku_id`,`quantity`,`added_at`) SELECT `id`,`user_id`,`sku_id`,`quantity`,`added_at` FROM `cart_items`; --> statement-breakpoint CREATE TABLE `__new_complaints` ( `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, `user_id` integer NOT NULL, `order_id` integer, `region_id` integer, `complaint_body` text NOT NULL, `images` text, `response` text, `is_resolved` integer DEFAULT false NOT NULL, `created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL, FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE no action, FOREIGN KEY (`order_id`) REFERENCES `__new_orders`(`id`) ON UPDATE no action ON DELETE no action, FOREIGN KEY (`region_id`) REFERENCES `regions`(`id`) ON UPDATE no action ON DELETE no action ); --> statement-breakpoint -- Backfill the complaint's region: every pre-existing complaint belongs to the -- region the whole dataset is being backfilled into (Mahabubnagar). Region-less -- is allowed going forward, so the column stays nullable. INSERT INTO `__new_complaints` (`id`,`user_id`,`order_id`,`region_id`,`complaint_body`,`images`,`response`,`is_resolved`,`created_at`) SELECT `id`,`user_id`,`order_id`,(SELECT `id` FROM `regions` WHERE `name` = 'Mahabubnagar'),`complaint_body`,`images`,`response`,`is_resolved`,`created_at` FROM `complaints`; --> statement-breakpoint CREATE TABLE `__new_user_incidents` ( `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, `user_id` integer NOT NULL, `order_id` integer, `date_added` text DEFAULT CURRENT_TIMESTAMP NOT NULL, `admin_comment` text, `added_by` integer, `negativity_score` integer, FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE no action, FOREIGN KEY (`order_id`) REFERENCES `__new_orders`(`id`) ON UPDATE no action ON DELETE no action, FOREIGN KEY (`added_by`) REFERENCES `__new_staff_users`(`id`) ON UPDATE no action ON DELETE no action ); --> statement-breakpoint INSERT INTO `__new_user_incidents` (`id`,`user_id`,`order_id`,`date_added`,`admin_comment`,`added_by`,`negativity_score`) SELECT `id`,`user_id`,`order_id`,`date_added`,`admin_comment`,`added_by`,`negativity_score` FROM `user_incidents`; --> statement-breakpoint -- Drop originals leaf-first (nothing references a table when it is dropped). -- `coupon_applicable_products` has no dependents and references coupons and -- product_skus, both of which are dropped below — so it goes first. DROP TABLE `coupon_applicable_products`; --> statement-breakpoint DROP TABLE `user_incidents`; --> statement-breakpoint DROP TABLE `complaints`; --> statement-breakpoint DROP TABLE `cart_items`; --> statement-breakpoint DROP TABLE `reserved_coupons`; --> statement-breakpoint DROP TABLE `coupon_applicable_users`; --> statement-breakpoint DROP TABLE `coupon_usage`; --> statement-breakpoint -- ===================================================================== -- Phase 5: online payments removed — the app is Cash on Delivery only. -- -- The rebuilt `orders` above already omits `is_cod`, `is_online_payment` and -- `payment_info_id`, and the rebuilt `order_status` omits `payment_state` and -- `refund_coupon_id`. Here the three payment tables go: `payments`/`refunds` -- are children of `orders` and are dropped before it (leaf-first, like every -- other table in this section); `payment_info` is the parent of the old -- `orders.payment_info_id`, so it is dropped right after `orders`. -- -- Nothing to migrate: no order was ever placed as an online payment (the -- checkout only ever offered the disabled "Coming Soon" option), and the only -- `refunds` rows were the 'na' rows written for cancelled COD orders. To confirm -- on a live DB before applying: -- SELECT COUNT(*) FROM `orders` WHERE `is_online_payment` = 1; -- expect 0 -- SELECT COUNT(*) FROM `payments`; -- expect 0 -- SELECT COUNT(*) FROM `refunds` WHERE `refund_status` <> 'na'; -- expect 0 -- ===================================================================== DROP TABLE `payments`; --> statement-breakpoint DROP TABLE `refunds`; --> statement-breakpoint DROP TABLE `order_status`; --> statement-breakpoint DROP TABLE `order_items`; --> statement-breakpoint DROP TABLE `orders`; --> statement-breakpoint -- `payment_info` (the old `orders.payment_info_id` parent) has no dependents left. DROP TABLE `payment_info`; --> statement-breakpoint DROP TABLE `product_group_membership`; --> statement-breakpoint DROP TABLE `product_tags`; --> statement-breakpoint DROP TABLE `product_reviews`; --> statement-breakpoint DROP TABLE `special_deals`; --> statement-breakpoint DROP TABLE `product_combos`; --> statement-breakpoint DROP TABLE `sku_features`; --> statement-breakpoint DROP TABLE `product_market_stats`; --> statement-breakpoint DROP TABLE `product_skus`; --> statement-breakpoint DROP TABLE `coupons`; --> statement-breakpoint DROP TABLE `addresses`; --> statement-breakpoint DROP TABLE `home_banners`; --> statement-breakpoint DROP TABLE `vendor_snippets`; --> statement-breakpoint DROP TABLE `delivery_slot_info`; --> statement-breakpoint DROP TABLE `product_group_info`; --> statement-breakpoint DROP TABLE `product_tag_info`; --> statement-breakpoint DROP TABLE `product_info`; --> statement-breakpoint DROP TABLE `store_info`; --> statement-breakpoint DROP TABLE `staff_notif_creds`; --> statement-breakpoint DROP TABLE `staff_users`; --> statement-breakpoint -- Promote replacements parent-first; SQLite rewrites child FK clauses on rename. ALTER TABLE `__new_staff_users` RENAME TO `staff_users`; --> statement-breakpoint ALTER TABLE `__new_staff_notif_creds` RENAME TO `staff_notif_creds`; --> statement-breakpoint ALTER TABLE `__new_store_info` RENAME TO `store_info`; --> statement-breakpoint ALTER TABLE `__new_product_info` RENAME TO `product_info`; --> statement-breakpoint ALTER TABLE `__new_product_tag_info` RENAME TO `product_tag_info`; --> statement-breakpoint ALTER TABLE `__new_product_group_info` RENAME TO `product_group_info`; --> statement-breakpoint ALTER TABLE `__new_delivery_slot_info` RENAME TO `delivery_slot_info`; --> statement-breakpoint ALTER TABLE `__new_vendor_snippets` RENAME TO `vendor_snippets`; --> statement-breakpoint ALTER TABLE `__new_home_banners` RENAME TO `home_banners`; --> statement-breakpoint ALTER TABLE `__new_addresses` RENAME TO `addresses`; --> statement-breakpoint ALTER TABLE `__new_coupons` RENAME TO `coupons`; --> statement-breakpoint ALTER TABLE `__new_product_skus` RENAME TO `product_skus`; --> statement-breakpoint ALTER TABLE `__new_product_market_stats` RENAME TO `product_market_stats`; --> statement-breakpoint ALTER TABLE `__new_sku_features` RENAME TO `sku_features`; --> statement-breakpoint ALTER TABLE `__new_product_combos` RENAME TO `product_combos`; --> statement-breakpoint ALTER TABLE `__new_special_deals` RENAME TO `special_deals`; --> statement-breakpoint ALTER TABLE `__new_product_reviews` RENAME TO `product_reviews`; --> statement-breakpoint ALTER TABLE `__new_product_tags` RENAME TO `product_tags`; --> statement-breakpoint ALTER TABLE `__new_product_group_membership` RENAME TO `product_group_membership`; --> statement-breakpoint ALTER TABLE `__new_orders` RENAME TO `orders`; --> statement-breakpoint ALTER TABLE `__new_order_items` RENAME TO `order_items`; --> statement-breakpoint ALTER TABLE `__new_order_status` RENAME TO `order_status`; --> statement-breakpoint ALTER TABLE `__new_coupon_usage` RENAME TO `coupon_usage`; --> statement-breakpoint ALTER TABLE `__new_coupon_applicable_users` RENAME TO `coupon_applicable_users`; --> statement-breakpoint ALTER TABLE `__new_reserved_coupons` RENAME TO `reserved_coupons`; --> statement-breakpoint ALTER TABLE `__new_cart_items` RENAME TO `cart_items`; --> statement-breakpoint ALTER TABLE `__new_complaints` RENAME TO `complaints`; --> statement-breakpoint ALTER TABLE `__new_user_incidents` RENAME TO `user_incidents`; --> statement-breakpoint -- Recreate indexes after original names are released. CREATE UNIQUE INDEX `staff_notif_creds_token_unique` ON `staff_notif_creds` (`token`); --> statement-breakpoint CREATE UNIQUE INDEX `product_tag_info_tag_name_unique` ON `product_tag_info` (`tag_name`); --> statement-breakpoint CREATE UNIQUE INDEX `vendor_snippets_snippet_code_unique` ON `vendor_snippets` (`snippet_code`); --> statement-breakpoint CREATE UNIQUE INDEX `coupons_coupon_code_unique` ON `coupons` (`coupon_code`); --> statement-breakpoint CREATE UNIQUE INDEX `product_market_stats_sku_region` ON `product_market_stats` (`sku_id`,`region_id`); --> statement-breakpoint CREATE UNIQUE INDEX `unique_sku_feature_name` ON `sku_features` (`sku_id`,`feature_name`); --> statement-breakpoint CREATE UNIQUE INDEX `unique_combo_sku_item` ON `product_combos` (`combo_sku_id`,`sku_id`); --> statement-breakpoint CREATE UNIQUE INDEX `unique_product_tag` ON `product_tags` (`product_id`,`tag_id`); --> statement-breakpoint CREATE UNIQUE INDEX `unique_coupon_user` ON `coupon_applicable_users` (`coupon_id`,`user_id`); --> statement-breakpoint CREATE UNIQUE INDEX `reserved_coupons_secret_code_unique` ON `reserved_coupons` (`secret_code`); --> statement-breakpoint CREATE UNIQUE INDEX `unique_user_sku` ON `cart_items` (`user_id`,`sku_id`); --> statement-breakpoint CREATE INDEX `idx_product_info_region` ON `product_info` (`region_id`); --> statement-breakpoint CREATE INDEX `idx_staff_users_region` ON `staff_users` (`region_id`); --> statement-breakpoint CREATE INDEX `idx_store_info_region` ON `store_info` (`region_id`); --> statement-breakpoint CREATE INDEX `idx_vendor_snippets_region` ON `vendor_snippets` (`region_id`); --> statement-breakpoint CREATE INDEX `idx_product_tag_info_region` ON `product_tag_info` (`region_id`); --> statement-breakpoint CREATE INDEX `idx_product_group_info_region` ON `product_group_info` (`region_id`); --> statement-breakpoint CREATE INDEX `idx_delivery_slot_info_region` ON `delivery_slot_info` (`region_id`); --> statement-breakpoint CREATE INDEX `idx_coupons_region` ON `coupons` (`region_id`); --> statement-breakpoint CREATE INDEX `idx_reserved_coupons_region` ON `reserved_coupons` (`region_id`); --> statement-breakpoint CREATE INDEX `idx_home_banners_region` ON `home_banners` (`region_id`); --> statement-breakpoint CREATE INDEX `idx_addresses_region` ON `addresses` (`region_id`); --> statement-breakpoint CREATE INDEX `idx_orders_region` ON `orders` (`region_id`); --> statement-breakpoint CREATE INDEX `idx_complaints_region` ON `complaints` (`region_id`); --> statement-breakpoint -- ===================================================================== -- Default address backfill (from the user's recent orders). -- -- Only users with NO default address are touched: a user-chosen default is -- never overridden. "Recent 3" = the 3 most recent non-cancelled orders -- (created_at desc, then id). The address used by the majority of those 3 -- becomes the default; ties fall back to the most recent order's address, -- then the newest address id. Votes only count addresses that still exist -- (the orphan-order repair above already removed the dead ones). -- ===================================================================== WITH `ranked_orders` AS ( SELECT `o`.`id`, `o`.`user_id`, `o`.`address_id`, ROW_NUMBER() OVER ( PARTITION BY `o`.`user_id` ORDER BY datetime(`o`.`created_at`) DESC, `o`.`id` DESC ) AS `rn` FROM `orders` `o` JOIN `order_status` `os` ON `os`.`order_id` = `o`.`id` WHERE `os`.`is_cancelled` = 0 ), `recent3` AS ( SELECT `user_id`, `address_id`, `rn` FROM `ranked_orders` WHERE `rn` <= 3 ), `votes` AS ( SELECT `r`.`user_id`, `r`.`address_id`, COUNT(*) AS `vote_count`, MIN(`r`.`rn`) AS `best_rank` FROM `recent3` `r` JOIN `addresses` `a` ON `a`.`id` = `r`.`address_id` GROUP BY `r`.`user_id`, `r`.`address_id` ), `winner` AS ( SELECT `user_id`, `address_id`, ROW_NUMBER() OVER ( PARTITION BY `user_id` ORDER BY `vote_count` DESC, `best_rank` ASC, `address_id` DESC ) AS `pick` FROM `votes` ), `no_default_users` AS ( SELECT `user_id` FROM `addresses` GROUP BY `user_id` HAVING SUM(`is_default`) = 0 ) UPDATE `addresses` SET `is_default` = 1 WHERE `id` IN (SELECT `address_id` FROM `winner` WHERE `pick` = 1) AND `user_id` IN (SELECT `user_id` FROM `no_default_users`); --> statement-breakpoint -- ===================================================================== -- Phase 3 (from 0008 + 0009): the three const tables, seeded directly. -- `region_cache_versions` is not created; its 1/1/1 seed is folded into the -- region_consts version counters below. `region_bound_settings` is not created; -- its per-bound and region-level rows are seeded straight into the final tables. -- ===================================================================== CREATE TABLE IF NOT EXISTS `global_consts` ( `key` text PRIMARY KEY NOT NULL, `value` text ); --> statement-breakpoint CREATE TABLE IF NOT EXISTS `region_consts` ( `region_id` integer NOT NULL, `key` text NOT NULL, `value` text, PRIMARY KEY (`region_id`, `key`), FOREIGN KEY (`region_id`) REFERENCES `regions`(`id`) ON UPDATE no action ON DELETE no action ); --> statement-breakpoint CREATE TABLE IF NOT EXISTS `region_bound_consts` ( `bound_id` integer NOT NULL, `region_id` integer NOT NULL, `key` text NOT NULL, `value` text, PRIMARY KEY (`bound_id`, `key`), FOREIGN KEY (`bound_id`) REFERENCES `region_bounds`(`id`) ON UPDATE no action ON DELETE no action, FOREIGN KEY (`region_id`) REFERENCES `regions`(`id`) ON UPDATE no action ON DELETE no action ); --> statement-breakpoint -- Global rows (from key_val_store, same key set as the former 0009). INSERT OR REPLACE INTO `global_consts` (`key`, `value`) SELECT `key`, `value` FROM `key_val_store` WHERE `key` IN ('versionNum','playStoreUrl','appStoreUrl','internalAppVersion'); --> statement-breakpoint -- Per-region version counters (was region_cache_versions seeded with 1/1/1). INSERT OR REPLACE INTO `region_consts` (`region_id`, `key`, `value`) SELECT `id`, 'products_version_num', '1' FROM `regions`; --> statement-breakpoint INSERT OR REPLACE INTO `region_consts` (`region_id`, `key`, `value`) SELECT `id`, 'availability_version_num', '1' FROM `regions`; --> statement-breakpoint INSERT OR REPLACE INTO `region_consts` (`region_id`, `key`, `value`) SELECT `id`, 'slots_version_num', '1' FROM `regions`; --> statement-breakpoint -- Region-level business keys. 0006 seeded these per bound and 0009 lifted them -- from each region's lowest-priority bound; both seeded bounds share the same -- values, so seed them once per region with those values. INSERT OR REPLACE INTO `region_consts` (`region_id`, `key`, `value`) SELECT `id`, 'popularItems', '[]' FROM `regions` WHERE `name` = 'Mahabubnagar'; --> statement-breakpoint INSERT OR REPLACE INTO `region_consts` (`region_id`, `key`, `value`) SELECT `id`, 'allItemsOrder', '[]' FROM `regions` WHERE `name` = 'Mahabubnagar'; --> statement-breakpoint INSERT OR REPLACE INTO `region_consts` (`region_id`, `key`, `value`) SELECT `id`, 'supportMobile', '8688182552' FROM `regions` WHERE `name` = 'Mahabubnagar'; --> statement-breakpoint INSERT OR REPLACE INTO `region_consts` (`region_id`, `key`, `value`) SELECT `id`, 'supportEmail', 'qushammohd@gmail.com' FROM `regions` WHERE `name` = 'Mahabubnagar'; --> statement-breakpoint INSERT OR REPLACE INTO `region_consts` (`region_id`, `key`, `value`) SELECT `id`, 'welcomeMessage', 'Hi! Thank you for your first order at Freshyo. We''re glad to have you.' FROM `regions` WHERE `name` = 'Mahabubnagar'; --> statement-breakpoint -- Fallback region-level values from the old global rows (same as 0009; only -- fills keys not already set above, e.g. tagsOrder). INSERT OR IGNORE INTO `region_consts` (`region_id`, `key`, `value`) SELECT r.`id`, kv.`key`, kv.`value` FROM `regions` r, `key_val_store` kv WHERE kv.`key` IN ('popularItems','allItemsOrder','tagsOrder','supportMobile','supportEmail','welcomeMessage'); --> statement-breakpoint -- Per-bound business keys (formerly seeded into region_bound_settings in 0006). INSERT OR REPLACE INTO `region_bound_consts` (`bound_id`, `region_id`, `key`, `value`) SELECT b.`id`, b.`region_id`, 'freeDeliveryThreshold', '300' FROM `regions` r JOIN `region_bounds` b ON b.`region_id` = r.`id` WHERE r.`name` = 'Mahabubnagar'; --> statement-breakpoint INSERT OR REPLACE INTO `region_bound_consts` (`bound_id`, `region_id`, `key`, `value`) SELECT b.`id`, b.`region_id`, 'deliveryCharge', '20' FROM `regions` r JOIN `region_bounds` b ON b.`region_id` = r.`id` WHERE r.`name` = 'Mahabubnagar'; --> statement-breakpoint INSERT OR REPLACE INTO `region_bound_consts` (`bound_id`, `region_id`, `key`, `value`) SELECT b.`id`, b.`region_id`, 'flashFreeDeliveryThreshold', '500' FROM `regions` r JOIN `region_bounds` b ON b.`region_id` = r.`id` WHERE r.`name` = 'Mahabubnagar'; --> statement-breakpoint INSERT OR REPLACE INTO `region_bound_consts` (`bound_id`, `region_id`, `key`, `value`) SELECT b.`id`, b.`region_id`, 'flashDeliveryCharge', '69' FROM `regions` r JOIN `region_bounds` b ON b.`region_id` = r.`id` WHERE r.`name` = 'Mahabubnagar'; --> statement-breakpoint -- "Enable Flash Delivery" is a BOUND-level key (each bound switches flash -- delivery on/off independently), so it is seeded per bound, not per region. -- Carried over from the pre-existing global value so the move changes nothing; -- normalised to 'true'/'false' (what the admin editors write) because the legacy -- key_val_store value was numeric ('1.0'). INSERT OR REPLACE INTO `region_bound_consts` (`bound_id`, `region_id`, `key`, `value`) SELECT b.`id`, b.`region_id`, 'isFlashDeliveryEnabled', CASE WHEN lower(COALESCE((SELECT `value` FROM `key_val_store` WHERE `key` = 'isFlashDeliveryEnabled'), 'false')) IN ('1', 'true', '1.0') THEN 'true' ELSE 'false' END FROM `regions` r JOIN `region_bounds` b ON b.`region_id` = r.`id` WHERE r.`name` = 'Mahabubnagar'; --> statement-breakpoint -- Bounding-box centre of each seeded bound, persisted so clients can focus a map -- on a region without loading its geometry. (The app recomputes this on every -- bound create/update; this covers the rows that exist before it runs.) UPDATE `region_bounds` SET `center_lat` = ( SELECT (MIN(CAST(json_extract(value, '$[1]') AS REAL)) + MAX(CAST(json_extract(value, '$[1]') AS REAL))) / 2 FROM json_each(`region_bounds`.`geojson`, '$.features[0].geometry.coordinates[0]') ), `center_lng` = ( SELECT (MIN(CAST(json_extract(value, '$[0]') AS REAL)) + MAX(CAST(json_extract(value, '$[0]') AS REAL))) / 2 FROM json_each(`region_bounds`.`geojson`, '$.features[0].geometry.coordinates[0]') ); --> statement-breakpoint -- Keep only the leftover keys in key_val_store (same set 0009 keeps). DELETE FROM `key_val_store` WHERE `key` IN ( 'versionNum','playStoreUrl','appStoreUrl','internalAppVersion', 'popularItems','allItemsOrder','tagsOrder','isFlashDeliveryEnabled','supportMobile','supportEmail','welcomeMessage', 'cache_version','availability_version_num','slots_version_num', 'minRegularOrderValue' ); --> statement-breakpoint -- ===================================================================== -- Phase 4 (from 0008): user_creds uniqueness. -- Collapse duplicate rows (keep the newest per user) before the unique index. -- ===================================================================== DELETE FROM `user_creds` WHERE `id` NOT IN (SELECT MAX(`id`) FROM `user_creds` GROUP BY `user_id`); --> statement-breakpoint CREATE UNIQUE INDEX IF NOT EXISTS `unique_user_creds_user` ON `user_creds` (`user_id`); --> statement-breakpoint -- ===================================================================== -- Phase 5: user <-> region associations + a nullable region on push creds. -- from_address 1 when the user has an address in that region, -- from_location 1 when the device location resolved to it. -- A row is dropped only once BOTH flags are false, so reconciling the -- address-derived rows never loses a location-derived association. -- notif_creds / unlogged_user_tokens get a NULLABLE region_id: the app sends -- its region with the push token, and a region captured while signed out is -- carried into notif_creds on login. -- ===================================================================== CREATE TABLE IF NOT EXISTS `user_regions` ( `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, `user_id` integer NOT NULL, `region_id` integer NOT NULL, `from_address` integer DEFAULT false NOT NULL, `from_location` integer DEFAULT false NOT NULL, `created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL, `updated_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL, FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE no action, FOREIGN KEY (`region_id`) REFERENCES `regions`(`id`) ON UPDATE no action ON DELETE no action ); --> statement-breakpoint CREATE UNIQUE INDEX IF NOT EXISTS `unique_user_region` ON `user_regions` (`user_id`,`region_id`); --> statement-breakpoint ALTER TABLE `notif_creds` ADD COLUMN `region_id` integer REFERENCES `regions`(`id`); --> statement-breakpoint ALTER TABLE `unlogged_user_tokens` ADD COLUMN `region_id` integer REFERENCES `regions`(`id`); --> statement-breakpoint -- Backfill one row per existing (user, region) pair from the addresses on file. INSERT OR IGNORE INTO `user_regions` (`user_id`, `region_id`, `from_address`, `from_location`) SELECT DISTINCT `user_id`, `region_id`, 1, 0 FROM `addresses` WHERE `region_id` IS NOT NULL; --> statement-breakpoint -- ===================================================================== -- Coupon product targets (from 0007_coupon_targets_json). -- -- The fold into `coupons.sku_ids` and the `coupon_applicable_products` drop -- now run before the rebuild: that table is a leaf of coupons/product_skus, -- so it must be dropped leaf-first (see the drop block above), and its rows -- must be folded before `__new_coupons` copies `sku_ids`. -- =====================================================================