-- calculate_salary.sql
-- Per-clerk salary statistics for completed orders in a time range
-- Data model references:
--   - play_order_info: per order fields including commission amount/ratio
--   - play_clerk_user_info: clerk profile (nickname)
--
-- Usage:
--   1) Replace YOUR_TENANT_ID_HERE with your tenant id (or SET it below)
--   2) Adjust @start_time and @end_time to the desired window
--   3) Run against the MySQL database

-- Hardcoded parameters for compatibility (no CTE/SET required)
-- tenant_id: wwi22qfjt
-- time range: 2025-09-15 00:00:00 to 2025-09-22 23:59:59

-- Per-clerk statistics for completed, non-refunded normal orders in range
SELECT
  cu.id                                    AS clerk_id,
  cu.nickname                              AS clerk_nickname,
  COUNT(*)                                 AS total_orders,
  SUM(oi.final_amount)                     AS total_final_amount,
  SUM(oi.estimated_revenue)                AS total_salary,
  ROUND(100 * SUM(oi.estimated_revenue) / NULLIF(SUM(oi.final_amount), 0), 2) AS effective_percentage,
  ROUND(AVG(oi.estimated_revenue_ratio), 2) AS avg_percentage,
  MIN(oi.estimated_revenue_ratio)           AS min_percentage,
  MAX(oi.estimated_revenue_ratio)           AS max_percentage
FROM play_order_info oi
JOIN play_clerk_user_info cu
  ON cu.id = oi.accept_by
 AND cu.tenant_id = 'wwi22qfjt'
WHERE
      oi.tenant_id = 'wwi22qfjt'
  AND oi.order_status = '3'               -- completed
  AND oi.order_type = '2'                 -- normal order; excludes recharge/withdraw
  AND oi.refund_type = '0'                -- exclude refunded
  AND oi.accept_by IS NOT NULL
  AND oi.order_end_time BETWEEN '2025-09-15 00:00:00' AND '2025-09-22 23:59:59'
GROUP BY cu.id, cu.nickname
ORDER BY total_salary DESC;
