-- 诊断 SQL：检查 hss_service_orders 的 order_no 字段
-- 在 Supabase SQL Editor 中执行

-- 1. 检查表结构是否有 order_no 列
SELECT column_name, data_type, is_nullable, column_default
FROM information_schema.columns
WHERE table_schema = 'public' 
  AND table_name = 'hss_service_orders'
  AND column_name IN ('order_no', 'task_no')
ORDER BY ordinal_position;

-- 2. 检查 order_no 字段的实际值
SELECT 
    id,
    order_no,
    status,
    current_staff_id,
    created_at,
    -- 检查 order_no 是否为空
    CASE 
        WHEN order_no IS NULL THEN 'NULL'
        WHEN order_no = '' THEN 'EMPTY_STRING'
        ELSE 'HAS_VALUE: ' || order_no
    END AS order_no_status
FROM public.hss_service_orders
WHERE deleted_at IS NULL
ORDER BY created_at DESC
LIMIT 20;

-- 3. 检查 RPC 函数返回的 orderNo 字段
SELECT 
    id,
    order_no,
    public.delivery_build_order_json(to_jsonb(o), '[]'::jsonb, '[]'::jsonb, '[]'::jsonb, NULL, 'legacy') ->> 'orderNo' AS orderNo_from_rpc
FROM public.hss_service_orders o
WHERE deleted_at IS NULL
ORDER BY created_at DESC
LIMIT 10;
