-- 采购付款分离改造：数据库迁移脚本
-- 创建时间：2026-03-25

-- ============================================
-- 表1：采购申请表 (purchase_requests)
-- ============================================
CREATE TABLE IF NOT EXISTS purchase_requests (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  request_code TEXT UNIQUE NOT NULL,
  project_id INTEGER NOT NULL,
  applicant TEXT NOT NULL,
  request_date DATE NOT NULL,
  supplier_id INTEGER,
  supplier_name TEXT,
  expense_category TEXT NOT NULL,
  total_amount REAL NOT NULL DEFAULT 0,
  currency TEXT DEFAULT 'CNY',
  status TEXT DEFAULT 'pending',
  remark TEXT,
  attachments TEXT,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  FOREIGN KEY (project_id) REFERENCES projects(id),
  FOREIGN KEY (supplier_id) REFERENCES suppliers(id)
);

-- ============================================
-- 表2：采购明细表 (purchase_request_items)
-- ============================================
CREATE TABLE IF NOT EXISTS purchase_request_items (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  purchase_request_id INTEGER NOT NULL,
  product_id INTEGER,
  product_name TEXT NOT NULL,
  specification TEXT,
  unit TEXT,
  quantity REAL NOT NULL DEFAULT 0,
  unit_price REAL NOT NULL DEFAULT 0,
  total_price REAL NOT NULL DEFAULT 0,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  FOREIGN KEY (purchase_request_id) REFERENCES purchase_requests(id) ON DELETE CASCADE,
  FOREIGN KEY (product_id) REFERENCES products(id)
);

-- ============================================
-- 表3：库存记录表 (inventory_records)
-- ============================================
CREATE TABLE IF NOT EXISTS inventory_records (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  record_type TEXT NOT NULL,
  project_id INTEGER,
  purchase_request_id INTEGER,
  product_id INTEGER NOT NULL,
  quantity REAL NOT NULL DEFAULT 0,
  unit_price REAL,
  total_amount REAL,
  record_date DATE NOT NULL,
  operator TEXT,
  remark TEXT,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  FOREIGN KEY (project_id) REFERENCES projects(id),
  FOREIGN KEY (purchase_request_id) REFERENCES purchase_requests(id),
  FOREIGN KEY (product_id) REFERENCES products(id)
);

-- ============================================
-- 修改：为付款申请表添加采购单关联字段
-- ============================================
ALTER TABLE payment_requests ADD COLUMN purchase_request_id INTEGER;
ALTER TABLE payment_requests ADD COLUMN payment_type TEXT DEFAULT 'company';

-- 创建索引
CREATE INDEX IF NOT EXISTS idx_purchase_requests_project ON purchase_requests(project_id);
CREATE INDEX IF NOT EXISTS idx_purchase_requests_status ON purchase_requests(status);
CREATE INDEX IF NOT EXISTS idx_purchase_request_items_request ON purchase_request_items(purchase_request_id);
CREATE INDEX IF NOT EXISTS idx_inventory_records_product ON inventory_records(product_id);
CREATE INDEX IF NOT EXISTS idx_inventory_records_project ON inventory_records(project_id);
