سامانه صدور فاکتور و حسابداری

Archive production migration office_slice_c7_fulltext_ocr_provenance

davoodmehraban89 committed Oct 1, 2026 at 00:29 UTC cd6e0fff0bacf2d91600c7d44b69c7a425a2ca4b
1 file changed +276
supabase/migrations/20260930205309_office_slice_c7_fulltext_ocr_provenance.sql new
+276
@@ -0,0 +1,276 @@
1 +
2 +-- Office Slice C7: ranked full-text archive search + OCR-text provenance/correction.
3 +-- C7 connects no OCR provider and makes no OCR accuracy claim; real Persian OCR accuracy remains unverified.
4 +
5 +create or replace function private.office_record_ocr_text_impl(
6 + p_organization_id uuid,
7 + p_correspondence_id text,
8 + p_mode text,
9 + p_raw_text text,
10 + p_corrected_text text,
11 + p_source_engine text,
12 + p_source_ref text,
13 + p_confidence numeric
14 +) returns text
15 +language plpgsql security definer set search_path=''
16 +as $$
17 +declare
18 + v_uid uuid := (select auth.uid());
19 + v_source public.records%rowtype;
20 + v_latest public.records%rowtype;
21 + v_event_id text;
22 + v_version integer := 1;
23 + v_raw_text text;
24 + v_corrected_text text;
25 + v_engine text;
26 + v_source_ref text;
27 + v_confidence numeric;
28 + v_previous_id text;
29 +begin
30 + if v_uid is null then raise exception 'authentication required' using errcode='42501'; end if;
31 + if p_mode not in ('provider_output','human_correction') then raise exception 'invalid OCR evidence mode' using errcode='22023'; end if;
32 + if not private.organization_has_module_entitlement(p_organization_id,'office_automation',true)
33 + or not (private.has_org_capability(p_organization_id,'office_automation','archive')
34 + or private.has_org_capability(p_organization_id,'office_automation','configure'))
35 + then raise exception 'archive permission required' using errcode='42501'; end if;
36 +
37 + select * into v_source from public.records r
38 + where r.organization_id=p_organization_id and r.collection='correspondence' and r.id=p_correspondence_id;
39 + if not found or not private.can_access_record(p_organization_id,'correspondence',v_source.owner_id,v_source.data,'read')
40 + then raise exception 'correspondence not found or not readable' using errcode='42501'; end if;
41 +
42 + perform pg_catalog.pg_advisory_xact_lock(
43 + pg_catalog.hashtextextended(p_organization_id::text||':office-ocr:'||p_correspondence_id,0)
44 + );
45 +
46 + select * into v_latest from public.records a
47 + where a.organization_id=p_organization_id and a.collection='correspondenceAudit'
48 + and a.data->>'event'='ocr_text_recorded' and a.data->>'correspondenceId'=p_correspondence_id
49 + order by coalesce(nullif(a.data->>'version','')::integer,0) desc,
50 + nullif(a.data->>'at','')::timestamptz desc
51 + limit 1;
52 +
53 + if found then
54 + v_version:=coalesce(nullif(v_latest.data->>'version','')::integer,0)+1;
55 + v_previous_id:=v_latest.id;
56 + end if;
57 +
58 + if p_mode='provider_output' then
59 + v_raw_text:=trim(coalesce(p_raw_text,''));
60 + v_corrected_text:=null;
61 + v_engine:=trim(coalesce(p_source_engine,''));
62 + v_source_ref:=trim(coalesce(p_source_ref,''));
63 + v_confidence:=p_confidence;
64 + if v_raw_text='' then raise exception 'provider OCR raw text required' using errcode='22023'; end if;
65 + if v_engine='' then raise exception 'OCR source engine required' using errcode='22023'; end if;
66 + if p_confidence is not null and (p_confidence<0 or p_confidence>1)
67 + then raise exception 'OCR confidence must be between 0 and 1' using errcode='22023'; end if;
68 + else
69 + if not found then raise exception 'prior OCR evidence required for human correction' using errcode='22023'; end if;
70 + v_corrected_text:=trim(coalesce(p_corrected_text,''));
71 + if v_corrected_text='' then raise exception 'corrected OCR text required' using errcode='22023'; end if;
72 + v_raw_text:=coalesce(v_latest.data->>'rawText','');
73 + v_engine:=coalesce(v_latest.data->>'sourceEngine','');
74 + v_source_ref:=coalesce(v_latest.data->>'sourceRef','');
75 + begin v_confidence:=nullif(v_latest.data->>'confidence','')::numeric; exception when others then v_confidence:=null; end;
76 + end if;
77 +
78 + if length(v_raw_text)>250000 or length(coalesce(v_corrected_text,''))>250000
79 + then raise exception 'OCR text too long' using errcode='22023'; end if;
80 + if length(v_engine)>120 or length(v_source_ref)>500
81 + then raise exception 'OCR provenance field too long' using errcode='22023'; end if;
82 +
83 + v_event_id:='OCR_'||replace(gen_random_uuid()::text,'-','');
84 + insert into public.records(organization_id,owner_id,collection,id,data)
85 + values(
86 + p_organization_id,v_uid,'correspondenceAudit',v_event_id,
87 + jsonb_build_object(
88 + 'event','ocr_text_recorded',
89 + 'correspondenceId',p_correspondence_id,
90 + 'version',v_version,
91 + 'sourceKind',p_mode,
92 + 'rawText',v_raw_text,
93 + 'correctedText',v_corrected_text,
94 + 'effectiveText',coalesce(v_corrected_text,v_raw_text),
95 + 'sourceEngine',v_engine,
96 + 'sourceRef',v_source_ref,
97 + 'confidence',v_confidence,
98 + 'previousOcrEventId',v_previous_id,
99 + 'providerVerified',false,
100 + 'accuracyVerified',false,
101 + 'actorUserId',v_uid,
102 + 'at',clock_timestamp()
103 + )
104 + );
105 + return v_event_id;
106 +end $$;
107 +revoke all on function private.office_record_ocr_text_impl(uuid,text,text,text,text,text,text,numeric) from public,anon;
108 +grant execute on function private.office_record_ocr_text_impl(uuid,text,text,text,text,text,text,numeric) to authenticated;
109 +
110 +create or replace function public.office_record_ocr_text(
111 + p_organization_id uuid,
112 + p_correspondence_id text,
113 + p_mode text,
114 + p_raw_text text default null,
115 + p_corrected_text text default null,
116 + p_source_engine text default null,
117 + p_source_ref text default null,
118 + p_confidence numeric default null
119 +) returns text
120 +language sql security invoker set search_path=''
121 +as $$
122 + select private.office_record_ocr_text_impl(
123 + p_organization_id,p_correspondence_id,p_mode,p_raw_text,p_corrected_text,p_source_engine,p_source_ref,p_confidence
124 + )
125 +$$;
126 +revoke all on function public.office_record_ocr_text(uuid,text,text,text,text,text,text,numeric) from public,anon;
127 +grant execute on function public.office_record_ocr_text(uuid,text,text,text,text,text,text,numeric) to authenticated;
128 +
129 +create or replace function private.office_latest_ocr_text_impl(p_organization_id uuid,p_correspondence_id text)
130 +returns table(
131 + event_id text,version integer,source_kind text,raw_text text,corrected_text text,effective_text text,
132 + source_engine text,source_ref text,confidence numeric,recorded_at timestamptz,recorded_by uuid
133 +)
134 +language sql stable security definer set search_path=''
135 +as $$
136 + select
137 + a.id,
138 + coalesce(nullif(a.data->>'version','')::integer,0),
139 + a.data->>'sourceKind',
140 + coalesce(a.data->>'rawText',''),
141 + nullif(a.data->>'correctedText',''),
142 + coalesce(nullif(a.data->>'correctedText',''),a.data->>'rawText',''),
143 + coalesce(a.data->>'sourceEngine',''),
144 + coalesce(a.data->>'sourceRef',''),
145 + case when nullif(a.data->>'confidence','') is null then null else (a.data->>'confidence')::numeric end,
146 + nullif(a.data->>'at','')::timestamptz,
147 + nullif(a.data->>'actorUserId','')::uuid
148 + from public.records c
149 + join lateral (
150 + select x.*
151 + from public.records x
152 + where x.organization_id=p_organization_id and x.collection='correspondenceAudit'
153 + and x.data->>'event'='ocr_text_recorded' and x.data->>'correspondenceId'=p_correspondence_id
154 + order by coalesce(nullif(x.data->>'version','')::integer,0) desc,
155 + nullif(x.data->>'at','')::timestamptz desc
156 + limit 1
157 + ) a on true
158 + where c.organization_id=p_organization_id and c.collection='correspondence' and c.id=p_correspondence_id
159 + and private.organization_has_module_entitlement(p_organization_id,'office_automation',false)
160 + and private.can_access_record(p_organization_id,'correspondence',c.owner_id,c.data,'read')
161 +$$;
162 +revoke all on function private.office_latest_ocr_text_impl(uuid,text) from public,anon;
163 +grant execute on function private.office_latest_ocr_text_impl(uuid,text) to authenticated;
164 +
165 +create or replace function public.office_latest_ocr_text(p_organization_id uuid,p_correspondence_id text)
166 +returns table(
167 + event_id text,version integer,source_kind text,raw_text text,corrected_text text,effective_text text,
168 + source_engine text,source_ref text,confidence numeric,recorded_at timestamptz,recorded_by uuid
169 +)
170 +language sql stable security invoker set search_path=''
171 +as $$ select * from private.office_latest_ocr_text_impl(p_organization_id,p_correspondence_id) $$;
172 +revoke all on function public.office_latest_ocr_text(uuid,text) from public,anon;
173 +grant execute on function public.office_latest_ocr_text(uuid,text) to authenticated;
174 +
175 +create or replace function private.office_archive_full_text_search_impl(
176 + p_organization_id uuid,
177 + p_query text,
178 + p_folder text,
179 + p_classification_code text,
180 + p_related_to text
181 +) returns table(
182 + correspondence_id text,register_number text,subject text,counterparty text,status text,
183 + folder text,classification_code text,tags text[],related_count bigint,
184 + search_rank real,ocr_state text,ocr_version integer,ocr_source_engine text
185 +)
186 +language sql stable security definer set search_path=''
187 +as $$
188 + with params as (
189 + select case
190 + when nullif(trim(coalesce(p_query,'')),'') is null then null::tsquery
191 + else websearch_to_tsquery('simple',trim(p_query))
192 + end as tsq
193 + ),
194 + source as (
195 + select
196 + c.*,cls.data classification_data,ocr.data ocr_data,
197 + (
198 + setweight(to_tsvector('simple',concat_ws(' ',coalesce(c.data->>'registerNumber',''),coalesce(c.data->>'subject',''))),'A') ||
199 + setweight(to_tsvector('simple',concat_ws(' ',coalesce(c.data->>'counterparty',''),coalesce(c.data->>'externalNumber',''))),'B') ||
200 + setweight(to_tsvector('simple',coalesce(c.data->>'body','')),'C') ||
201 + setweight(to_tsvector('simple',concat_ws(' ',
202 + coalesce(cls.data->>'folder',''),coalesce(cls.data->>'classificationCode',''),coalesce((cls.data->'tags')::text,''),
203 + coalesce(ocr.data->>'effectiveText',ocr.data->>'correctedText',ocr.data->>'rawText','')
204 + )),'D')
205 + ) as search_document
206 + from public.records c
207 + left join lateral (
208 + select a.data from public.records a
209 + where a.organization_id=p_organization_id and a.collection='correspondenceAudit'
210 + and a.data->>'event'='archive_classified' and a.data->>'correspondenceId'=c.id
211 + order by nullif(a.data->>'at','')::timestamptz desc limit 1
212 + ) cls on true
213 + left join lateral (
214 + select a.data from public.records a
215 + where a.organization_id=p_organization_id and a.collection='correspondenceAudit'
216 + and a.data->>'event'='ocr_text_recorded' and a.data->>'correspondenceId'=c.id
217 + order by coalesce(nullif(a.data->>'version','')::integer,0) desc,
218 + nullif(a.data->>'at','')::timestamptz desc limit 1
219 + ) ocr on true
220 + where c.organization_id=p_organization_id and c.collection='correspondence'
221 + and private.can_access_record(p_organization_id,'correspondence',c.owner_id,c.data,'read')
222 + )
223 + select
224 + s.id,s.data->>'registerNumber',s.data->>'subject',s.data->>'counterparty',s.data->>'status',
225 + coalesce(s.classification_data->>'folder',''),coalesce(s.classification_data->>'classificationCode',''),
226 + coalesce(array(select jsonb_array_elements_text(coalesce(s.classification_data->'tags','[]'::jsonb))),array[]::text[]),
227 + (select count(*) from public.records rel
228 + where rel.organization_id=p_organization_id and rel.collection='correspondenceAudit'
229 + and rel.data->>'event'='relation_created'
230 + and (rel.data->>'sourceId'=s.id or rel.data->>'targetId'=s.id)),
231 + case when p.tsq is null then 0::real else ts_rank_cd(s.search_document,p.tsq) end,
232 + case
233 + when s.ocr_data is null then 'none'
234 + when s.ocr_data->>'sourceKind'='human_correction' then 'corrected'
235 + else 'provider_output'
236 + end,
237 + coalesce(nullif(s.ocr_data->>'version','')::integer,0),
238 + coalesce(s.ocr_data->>'sourceEngine','')
239 + from source s cross join params p
240 + where private.organization_has_module_entitlement(p_organization_id,'office_automation',false)
241 + and (p.tsq is null or s.search_document @@ p.tsq)
242 + and (nullif(trim(coalesce(p_folder,'')),'') is null or s.classification_data->>'folder'=trim(p_folder))
243 + and (nullif(trim(coalesce(p_classification_code,'')),'') is null or s.classification_data->>'classificationCode'=trim(p_classification_code))
244 + and (nullif(trim(coalesce(p_related_to,'')),'') is null or s.id=p_related_to or exists(
245 + select 1 from public.records rel
246 + where rel.organization_id=p_organization_id and rel.collection='correspondenceAudit'
247 + and rel.data->>'event'='relation_created'
248 + and ((rel.data->>'sourceId'=p_related_to and rel.data->>'targetId'=s.id)
249 + or (rel.data->>'targetId'=p_related_to and rel.data->>'sourceId'=s.id))
250 + ))
251 + order by
252 + case when p.tsq is null then 0::real else ts_rank_cd(s.search_document,p.tsq) end desc,
253 + coalesce(s.data->>'registeredAt',s.data->>'createdAt','') desc
254 +$$;
255 +revoke all on function private.office_archive_full_text_search_impl(uuid,text,text,text,text) from public,anon;
256 +grant execute on function private.office_archive_full_text_search_impl(uuid,text,text,text,text) to authenticated;
257 +
258 +create or replace function public.office_archive_full_text_search(
259 + p_organization_id uuid,
260 + p_query text default null,
261 + p_folder text default null,
262 + p_classification_code text default null,
263 + p_related_to text default null
264 +) returns table(
265 + correspondence_id text,register_number text,subject text,counterparty text,status text,
266 + folder text,classification_code text,tags text[],related_count bigint,
267 + search_rank real,ocr_state text,ocr_version integer,ocr_source_engine text
268 +)
269 +language sql stable security invoker set search_path=''
270 +as $$
271 + select * from private.office_archive_full_text_search_impl(
272 + p_organization_id,p_query,p_folder,p_classification_code,p_related_to
273 + )
274 +$$;
275 +revoke all on function public.office_archive_full_text_search(uuid,text,text,text,text) from public,anon;
276 +grant execute on function public.office_archive_full_text_search(uuid,text,text,text,text) to authenticated;