CREATE TABLE IF NOT EXISTS po_purchase_return (
  id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  return_no VARCHAR(50) NOT NULL,
  purchase_order_id BIGINT NOT NULL,
  warehouse_id BIGINT NOT NULL,
  return_date DATETIME NOT NULL,
  operator_user_id BIGINT NULL,
  logistics_waybill_no VARCHAR(100) NULL,
  logistics_freight_amount DECIMAL(18, 2) NULL,
  logistics_photo_url VARCHAR(255) NULL,
  reason VARCHAR(255) NULL,
  status VARCHAR(32) NOT NULL DEFAULT 'CONFIRMED',
  remark VARCHAR(255) NULL,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  UNIQUE KEY uk_po_purchase_return_no (return_no),
  KEY idx_po_purchase_return_order (purchase_order_id),
  KEY idx_po_purchase_return_warehouse (warehouse_id),
  KEY idx_po_purchase_return_operator_user (operator_user_id),
  CONSTRAINT fk_po_purchase_return_order FOREIGN KEY (purchase_order_id) REFERENCES po_purchase_order (id),
  CONSTRAINT fk_po_purchase_return_warehouse FOREIGN KEY (warehouse_id) REFERENCES wh_warehouse (id),
  CONSTRAINT fk_po_purchase_return_operator_user FOREIGN KEY (operator_user_id) REFERENCES sys_user (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='采购退货出库单';

CREATE TABLE IF NOT EXISTS po_purchase_return_item (
  id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  purchase_return_id BIGINT NOT NULL,
  line_no INT NOT NULL,
  purchase_order_item_id BIGINT NOT NULL,
  material_item_id BIGINT NOT NULL,
  lot_id BIGINT NOT NULL,
  return_weight_kg DECIMAL(18, 6) NOT NULL DEFAULT 0,
  unit_cost DECIMAL(18, 4) NOT NULL DEFAULT 0,
  amount DECIMAL(18, 2) NOT NULL DEFAULT 0,
  reason VARCHAR(255) NULL,
  status VARCHAR(32) NOT NULL DEFAULT 'CONFIRMED',
  remark VARCHAR(255) NULL,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  UNIQUE KEY uk_po_purchase_return_item_line (purchase_return_id, line_no),
  KEY idx_po_purchase_return_item_return (purchase_return_id),
  KEY idx_po_purchase_return_item_po_item (purchase_order_item_id),
  KEY idx_po_purchase_return_item_lot (lot_id),
  CONSTRAINT fk_po_purchase_return_item_return FOREIGN KEY (purchase_return_id) REFERENCES po_purchase_return (id),
  CONSTRAINT fk_po_purchase_return_item_po_item FOREIGN KEY (purchase_order_item_id) REFERENCES po_purchase_order_item (id),
  CONSTRAINT fk_po_purchase_return_item_material FOREIGN KEY (material_item_id) REFERENCES md_item (id),
  CONSTRAINT fk_po_purchase_return_item_lot FOREIGN KEY (lot_id) REFERENCES wh_stock_lot (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='采购退货出库明细';
