CREATE TABLE IF NOT EXISTS qipai_business_daily_summaries (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
  tenant_id BIGINT UNSIGNED NOT NULL,
  store_id BIGINT UNSIGNED NOT NULL,
  business_date DATE NOT NULL,
  timezone VARCHAR(64) NOT NULL,
  order_count BIGINT UNSIGNED NOT NULL DEFAULT 0,
  customer_count BIGINT UNSIGNED NOT NULL DEFAULT 0,
  used_minutes BIGINT UNSIGNED NOT NULL DEFAULT 0,
  capacity_minutes BIGINT UNSIGNED NOT NULL DEFAULT 0,
  room_gross_cents BIGINT UNSIGNED NOT NULL DEFAULT 0,
  room_refund_cents BIGINT UNSIGNED NOT NULL DEFAULT 0,
  product_gross_cents BIGINT UNSIGNED NOT NULL DEFAULT 0,
  product_refund_cents BIGINT UNSIGNED NOT NULL DEFAULT 0,
  cleaning_cost_cents BIGINT NOT NULL DEFAULT 0,
  wechat_net_cents BIGINT NOT NULL DEFAULT 0,
  balance_net_cents BIGINT NOT NULL DEFAULT 0,
  package_net_cents BIGINT NOT NULL DEFAULT 0,
  group_buy_net_cents BIGINT NOT NULL DEFAULT 0,
  other_net_cents BIGINT NOT NULL DEFAULT 0,
  source_checksum CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
  calculated_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  updated_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3)
    ON UPDATE CURRENT_TIMESTAMP(3),
  CONSTRAINT fk_qipai_business_daily_summary_tenant
    FOREIGN KEY (tenant_id) REFERENCES qipai_tenants(id),
  CONSTRAINT fk_qipai_business_daily_summary_store
    FOREIGN KEY (tenant_id, store_id) REFERENCES qipai_stores(tenant_id, id),
  CONSTRAINT chk_qipai_business_daily_summary_usage CHECK (
    used_minutes <= capacity_minutes
  ),
  UNIQUE KEY uq_qipai_business_daily_summary_date
    (tenant_id, store_id, business_date),
  KEY idx_qipai_business_daily_summary_tenant_date
    (tenant_id, business_date, store_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

INSERT IGNORE INTO qipai_permissions (code, name, category) VALUES
  ('report.read', '查看经营报表', 'report'),
  ('report.export', '导出经营报表', 'report'),
  ('report.manage', '重算经营日汇总', 'report');

INSERT IGNORE INTO qipai_role_permissions (tenant_id, role_id, permission_id)
SELECT r.tenant_id, r.id, p.id
FROM qipai_roles r
INNER JOIN qipai_permissions p
  ON (r.code = 'STORE_ADMIN' AND p.code IN ('report.read', 'report.export'))
  OR (r.code IN ('TENANT_ADMIN', 'PLATFORM_ADMIN')
      AND p.code IN ('report.read', 'report.export', 'report.manage'))
WHERE r.status = 'ACTIVE' AND r.deleted_at IS NULL;

INSERT IGNORE INTO qipai_schema_migrations (version, name)
VALUES ('2026081111', 'm10b_business_reports');
