-- 修复历史拼单：份数已拼满且所有参与者均已提交时，母工单应进入待验收。
UPDATE work_orders wo
SET
  status = 'pending_acceptance',
  submitted_at = COALESCE(
    wo.submitted_at,
    (
      SELECT MAX(wos.submitted_at)
      FROM work_order_shares wos
      WHERE wos.work_order_id = wo.id
        AND wos.status != 'cancelled'
    ),
    NOW()
  ),
  updated_at = NOW()
WHERE wo.status = 'open'
  AND wo.sharing_enabled = true
  AND COALESCE((
    SELECT SUM(wos.quantity)
    FROM work_order_shares wos
    WHERE wos.work_order_id = wo.id
      AND wos.status != 'cancelled'
  ), 0) >= wo.sharing_total_quantity
  AND NOT EXISTS (
    SELECT 1
    FROM work_order_shares wos
    WHERE wos.work_order_id = wo.id
      AND wos.status = 'joined'
  );
