-- 2026-07-02 商机业绩归属地与数据授权区域范围升级脚本
--
-- 本次升级内容：
-- 1. 为 crm_opportunity 增加 project_ownership_location 字段。
-- 2. 将已有业绩归属地文本值尽量规范为 cnarea.level = 1 的 area_code。
-- 3. 为 sys_user_data_scope_user 增加商机业绩归属地授权范围字段。
-- 4. 旧授权默认保持“全部归属地”，不会收窄已有可见范围。

begin;

alter table if exists crm_opportunity
  add column if not exists project_ownership_location varchar(100);

comment on column crm_opportunity.project_ownership_location is '业绩归属地编码，对应 cnarea.area_code';

do $$
begin
  if to_regclass('public.cnarea') is not null then
    update crm_opportunity o
    set project_ownership_location = c.area_code
    from cnarea c
    where c.level = 1
      and coalesce(nullif(btrim(o.project_ownership_location), ''), '') <> ''
      and (
        o.project_ownership_location = c.short_name
        or o.project_ownership_location = c.name
      )
      and o.project_ownership_location is distinct from c.area_code;
  end if;
end $$;

alter table if exists sys_user_data_scope_user
  add column if not exists area_scope_type varchar(20) not null default 'ALL';

alter table if exists sys_user_data_scope_user
  add column if not exists area_codes varchar(100)[] not null default '{}'::varchar[];

update sys_user_data_scope_user
set area_scope_type = 'ALL',
    area_codes = '{}'::varchar[]
where area_scope_type is null
   or area_scope_type = '';

comment on column sys_user_data_scope_user.area_scope_type is '商机业绩归属地范围：ALL全部归属地/CUSTOM指定归属地';
comment on column sys_user_data_scope_user.area_codes is '指定可见的商机业绩归属地编码列表，对应 cnarea.area_code';

commit;
