-- v4.0.1：合伙人关联码 + 用户关联 + 账单明细

ALTER TABLE `partner_account`
  ADD COLUMN `assoc_qrcode_id` VARCHAR(64) DEFAULT NULL AFTER `managed_warehouse_id`,
  ADD COLUMN `assoc_qrcode_resource_id` BIGINT UNSIGNED DEFAULT NULL AFTER `assoc_qrcode_id`,
  ADD UNIQUE KEY `uk_partner_account_assoc_qrcode` (`assoc_qrcode_id`);

ALTER TABLE `user_user`
  ADD COLUMN `assoc_partner_account_id` BIGINT UNSIGNED DEFAULT NULL AFTER `referrer_user_id`,
  ADD COLUMN `assoc_bound_at` DATETIME(3) DEFAULT NULL AFTER `assoc_partner_account_id`,
  ADD KEY `idx_user_user_assoc_partner` (`assoc_partner_account_id`);

ALTER TABLE `user_user`
  ADD CONSTRAINT `fk_user_user_assoc_partner`
  FOREIGN KEY (`assoc_partner_account_id`) REFERENCES `partner_account`(`id`) ON DELETE SET NULL;

CREATE TABLE IF NOT EXISTS `partner_bill_item` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  `partner_bill_id` BIGINT UNSIGNED NOT NULL,
  `kind` VARCHAR(16) NOT NULL COMMENT 'ORDER|REDEEM',
  `ref_id` BIGINT UNSIGNED NOT NULL,
  `ref_no` VARCHAR(32) NOT NULL,
  `title` VARCHAR(128) DEFAULT NULL,
  `extra` VARCHAR(128) DEFAULT NULL,
  `base_amount` DECIMAL(10,2) NOT NULL,
  `rate` DECIMAL(5,4) NOT NULL,
  `commission` DECIMAL(10,2) NOT NULL,
  `occurred_at` DATETIME(3) NOT NULL,
  `created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_partner_bill_item_kind_ref` (`kind`, `ref_id`),
  KEY `idx_partner_bill_item_bill` (`partner_bill_id`),
  CONSTRAINT `fk_partner_bill_item_bill` FOREIGN KEY (`partner_bill_id`) REFERENCES `partner_bill`(`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='合伙人账单明细';
