
    z+jD                    B   d dl mZ d dlmZmZmZ d dlmZ d dlmZm	Z	 d dl
mZ d dlmZ d dlmZ dd	lmZ dd
lmZmZmZmZmZmZmZmZ d9dZd:dZd;dZdddddddd<d$Zd=d&Zdd'd>d*Z dd'd?d,Z!dd'd@d.Z"dd'dAd0Z#dd'dBd2Z$dd'dCd4Z%dd'dDd6Z&dd'dEd8Z'dS )F    )annotations)datedatetimetimezone)Decimal)AnyMapping)UUID)sql)Jsonb   )connect)PartyIn	ProductInSourceFileInPurchaseOrderInStockMovementInShipmentSignoffInValidationIssueInReconciliationRunInprefixstrreturnc                n    |  dt          j        t          j                                      d           S )N-z%Y%m%d%H%M%S%f)r   nowr   utcstrftime)r   s    app/write_service.py	_now_coder       s1    NNx|HL11::;KLLNNN    valuer   c                   t          | t                    rt          |           S t          | t                    rt          |           S t          | t          t
          f          r|                                 S t          | t                    rd |                                 D             S t          | t                    rd | D             S | S )Nc                4    i | ]\  }}|t          |          S  _to_jsonable.0kvs      r   
<dictcomp>z _to_jsonable.<locals>.<dictcomp>   s$    ===tq!<??===r!   c                ,    g | ]}t          |          S r%   r&   )r)   r+   s     r   
<listcomp>z _to_jsonable.<locals>.<listcomp>    s    ///AQ///r!   )

isinstancer
   r   r   r   r   	isoformatdictitemslist)r"   s    r   r'   r'      s    % 5zz%!! 5zz%(D)** !   % >==u{{}}====% 0//////Lr!   tabledataMapping[str, Any]c                   d |                                 D             }|st          d          d |D             }g }|                                D ]d}t          |t                    st          |t
                    r#|                    t          |                     O|                    |           et          j	        d          
                    t          j        |          t          j	        d                              |          t          j	        d                              d |D                                 }|                     ||           t          |                                 d                   S )	Nc                    i | ]
\  }}|||S Nr%   r(   s      r   r,   z_insert.<locals>.<dictcomp>%   s    <<<daamQmmmr!   zempty insert payloadc                6    g | ]}t          j        |          S r%   r   
Identifierr)   r*   s     r   r.   z_insert.<locals>.<listcomp>(   s"    ---!CN1---r!   zAINSERT INTO {table} ({cols}) VALUES ({placeholders}) RETURNING id, c              3  <   K   | ]}t          j                    V  d S r9   r   Placeholderr)   _s     r   	<genexpr>z_insert.<locals>.<genexpr>2   s*      'H'Ha(9(9'H'H'H'H'H'Hr!   )r4   colsplaceholdersid)r2   
ValueErrorvaluesr/   r1   r3   appendr   r   SQLformatr<   joinexecuter   fetchone)curr4   r5   cleanrE   valsr+   qs           r   _insertrT   $   sW   <<djjll<<<E 1/000--u---DD\\^^  a 	*Q"5"5 	KKa!!!!KKNNNNSTT[[nU##WT]]%%WT]]'''H'H4'H'H'HHH 	\ 	 	A
 KK4s||~~d#$$$r!   N)target_table	target_idpayload
validationerror_messageidempotency_keyactor_profile	tool_name	operationstatusrU   
str | NonerV   rW   dict[str, Any] | NonerX   rY   rZ   c       
           t          d          ||||
t          t          |pi                     t          t          |pi                     ||||	|dk    rt          j        t
          j                  nd d}d |                                D             }t          j	        d          
                    t          j	        d                              d |D                       t          j	        d                              d |D                       	          }|                     |t          |                                                     t          |                                 d
                   }|                     d|||dv r|nd||t          t          |pi                     |dk    rdnd|	p|f           |S )NWRapplied)request_coder[   r\   r]   rZ   request_payloadvalidation_resultr^   rU   rV   rY   
applied_atc                    i | ]
\  }}|||S r9   r%   r(   s      r   r,   z_audit.<locals>.<dictcomp>I   s    @@@da!-Q---r!   zDINSERT INTO api_write_requests ({cols}) VALUES ({vals}) RETURNING idr>   c              3  >   K   | ]}t          j        |          V  d S r9   r;   r=   s     r   rD   z_audit.<locals>.<genexpr>K   s,      AAaq 1 1AAAAAAr!   c              3  <   K   | ]}t          j                    V  d S r9   r@   rB   s     r   rD   z_audit.<locals>.<genexpr>L   s*      AAa 1 1AAAAAAr!   )rE   rR   rG   z
        INSERT INTO agent_write_audit(agent_profile, tool_name, operation, target_table, target_id, request_payload, result_status, result_message)
        VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
        >   createimportupdatecomputedelete_requestrk   successneeds_review)r    r   r'   r   r   r   r   r2   r   rK   rL   rM   rN   r3   rI   r   rO   )rP   r[   r\   r]   r^   rU   rV   rW   rX   rY   rZ   req_datarQ   rS   req_ids                  r   _auditrt   8   s    "$&* gm!<!<=="<
0@b#A#ABB$&4:i4G4Ghl8<000T H A@hnn..@@@EVWW^^WT]]AA5AAAAAWT]]AA5AAAAA 	_ 	 	A KK4''(((%&&FKK	 
		=t0t0t99  {C	y%W](C(C"D"DSY]fSfSfiilz  }J  }T  NT	U   Mr!   keyc                    |sd S |                      d|f           |                                 }|rt          |          nd S )NzjSELECT id, status, target_table, target_id, error_message FROM api_write_requests WHERE idempotency_key=%s)rN   rO   r1   )rP   ru   rows      r   _check_idempotencyrx   [   s[     tKK|  @C  E  F  F  F
,,..C%4999%r!   )rZ   r   dict[str, Any]c                  t                      5 }|                                5 }t          ||          }|rddi|cd d d            cd d d            S |                     dd          }|                    dt          d                     t          |d|          }t          ||dd	d
d|||	  	         |                                 d|icd d d            cd d d            S # 1 swxY w Y   	 d d d            d S # 1 swxY w Y   d S )N
idempotentTpythonexclude_nonemode
party_codePTpartiescreate_partyrk   rc   r[   r\   r]   r^   rU   rV   rW   rZ   rG   )	r   cursorrx   
model_dump
setdefaultr    rT   rt   commitrW   r[   rZ   connrP   existingr5   rV   s           r   r   r   c   s   	 
%d[[]] 		%c)#??H 8$d7h7		% 		% 		% 		% 		% 		% 		%
% 
% 
% 
% 
% 
% 
% 
%
 %%4h%GGDOOL)D//:::Y55I3m~Yajs  CL  Xa  ko  AP  Q  Q  Q  QKKMMM)$		% 		% 		% 		% 		% 		% 		%
% 
% 
% 
% 
% 
% 
% 
%		% 		% 		% 		% 		% 		% 		% 		% 		%
% 
% 
% 
% 
% 
% 
% 
% 
% 
% 
% 
% 
% 
% 
% 
% 
% 
%s@   DC(DA:C(D(C,	,D/C,	0DDDr   c                  t                      5 }|                                5 }t          ||          }|rddi|cd d d            cd d d            S |                     dd          }|                    dt          d                     t          |d|          }|                    d          r/|d         |d	         k    rt          |d
||d         dddd           t          ||dddd|||	  	         |	                                 d|icd d d            cd d d            S # 1 swxY w Y   	 d d d            d S # 1 swxY w Y   d S )Nr{   Tr|   r}   sku_codeSKUproductsraw_name_defaultstandard_nameproduct_aliasesraw_nameg?pending)
product_id
alias_name
alias_type
confidenceverification_statuscreate_productrk   rc   r   rG   )
r   r   rx   r   r   r    rT   getrt   r   r   s           r   r   r   q   sl   	 %d[[]] 	%c)#??H 8$d7h7	% 	% 	% 	% 	% 	% 	%% % % % % % % %
 %%4h%GGDOOJ	%(8(8999Z66Ixx*++ 5G0HDQ`La0a0a."+"&'9":","%+41 1    3m?O[clu  EO  [d  nr  DS  T  T  T  TKKMMM)$#	% 	% 	% 	% 	% 	% 	%% % % % % % % %	% 	% 	% 	% 	% 	% 	% 	% 	%% % % % % % % % % % % % % % % % % %s@   ED,EB>D,E,D0	0E3D0	4EE	E	r   c                  t                      5 }|                                5 }t          ||          }|rddi|cd d d            cd d d            S |                     dd          }|                    dd           t          |d|          }t          |d|t          d	          |                    d
          |                    d          |                    d          |                    d          |                    d          |                    d          |                    d          |                    d          d
           t          ||dddd|||	  	         |	                                 d|icd d d            cd d d            S # 1 swxY w Y   	 d d d            d S # 1 swxY w Y   d S )Nr{   Tr|   r}   extraction_statusr   source_filesfile_receiptsFRsource_platformuploaderreceived_atsource_cache_pathoriginal_source_pathreceived_statusfile_existsnotes)
source_file_idreceipt_coder   sender_namer   r   r   receive_statusr   r   register_source_filerk   rc   r   rG   )
r   r   rx   r   r   rT   r    r   rt   r   r   s           r   r   r      s   	 %d[[]] 	%c)#??H 8$d7h7	% 	% 	% 	% 	% 	% 	%% % % % % % % %
 %%4h%GGDOO/;;;^T::IC"+ )$#'88,=#>#>#xx
33#xx66%)XX.A%B%B(,1G(H(H"&((+<"="=#xx66'**+ +    3m?Uair{  KY  en  x|  N]  ^  ^  ^  ^KKMMM)$+	% 	% 	% 	% 	% 	% 	%% % % % % % % %	% 	% 	% 	% 	% 	% 	% 	% 	%% % % % % % % % % % % % % % % % % %s@   F5FF5D.FF5F 	 F5#F 	$F55F9<F9r   c                  | j         st          d          t                      5 }|                                5 }t	          ||          }|rddi|cd d d            cd d d            S |                     dhdd          }t          d          |d<   |                    d	          @|                    d
          r+|                    d          r|d
          d|d          |d	<   t          |d|          }g }g }	t          | j         d          D ]U\  }
}|                    dhdd          }|
                    ||
dd           |                    d          |d         |d<   t          |d|          }|                    |           |j        D ]}|                    dd          }||d<   |                    d          |                    dd          |d<   |                    d          Jt          |                    dd                    t          |                    dd                    z   |d<   |	                    t          |d|                     АWt          ||dddd||                     d !          t          |          t          |	          d"|#
  
         |                                 |||	d$cd d d            cd d d            S # 1 swxY w Y   	 d d d            d S # 1 swxY w Y   d S )%Nz)purchase order requires at least one liner{   Tlinesr|   excluder~   r   PO
order_codeexpected_arrival_textexpected_arrival_startexpected_arrival_end~purchase_ordersr   startchannel_allocationsr   )order_idline_nor   delivery_quantityquantityorder_linesr}   order_line_idplanned_quantityoriginal_quantityr   confirmed_quantityadjustment_quantitycreate_purchase_orderrk   rc   jsonr   )
line_countallocation_count	r[   r\   r]   r^   rU   rV   rW   rX   rZ   )rG   line_idsallocation_ids)r   rH   r   r   rx   r   r    r   rT   	enumeraterm   rJ   r   floatrt   lenr   )rW   r[   rZ   r   rP   r   
order_datar   r   r   idxline	line_dataline_idalloc
alloc_datas                   r   r   r      s   = FDEEE	 \d[[]] 	\c)#??H 8$d7h7	\ 	\ 	\ 	\ 	\ 	\ 	\\ \ \ \ \ \ \ \
 !++WIDW_+``J'0J|$~~566>>>":;; I
Oe@f@f I=GH`=a  ;I  ;Idn  pF  eG  ;I  ;IJ67s$5zBBH"$H(*N&w}A>>> [ [	T OO5J4KZ^emOnn	  h3_h!i!ijjj==!455=5>z5JI12!#}i@@(((!5 [ [E!&!1!1t(!1!S!SJ29J/!~~&899A9CH[]^9_9_
#56!~~&:;;C;@PcefAgAg;h;hkpq{qq  AV  XY  rZ  rZ  l[  l[  <[
#78"))'#7Lj*Y*YZZZZ[ 3m?Vbjs|  L]  iq  {B  {M  {M  SY  {M  {Z  {Z  vy  zB  vC  vC  Y\  ]k  Yl  Yl  gm  gm  N  O  O  O  OKKMMM"N[[;	\ 	\ 	\ 	\ 	\ 	\ 	\\ \ \ \ \ \ \ \	\ 	\ 	\ 	\ 	\ 	\ 	\ 	\ 	\\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \sA   LK)L+I%K)L)K-	-L0K-	1LL	Lr   c                  |                      dd          }t          d          |d<   |d         |d<   t                      5 }|                                5 }t	          ||          }|rddi|cd d d            cd d d            S |d         d	k    r|                    d
|d         f           |                                }|r|d         nd}|||d         k     rt          |dddd|d         dd| d|d          dd          }	t          ||dddd|	|dt          |          id|           |
                                 d|	dcd d d            cd d d            S t          |d|          }
t          ||dddd|
||	  	         |
                                 d |
icd d d            cd d d            S # 1 swxY w Y   	 d d d            d S # 1 swxY w Y   d S )!NTr|   r}   MVmovement_codemovement_nor{   	directionoutzCSELECT current_quantity FROM v_current_stock WHERE stock_item_id=%sstock_item_idcurrent_quantityr   r   validation_issuesnegative_stockerrorstock_itemsu   库存不足：当前 u   ，申请出库 open)
issue_typeseverityrelated_table
related_id
field_namemessager^   add_stock_movementrk   rejectedu   库存不足)
r[   r\   r]   r^   rU   rV   rW   rX   rY   rZ   )r   validation_issue_idstock_movementsrc   r   rG   )r   r    r   r   rx   rN   rO   rT   rt   r   r   )rW   r[   rZ   r5   r   rP   r   rw   currentissue_idrV   s              r   r   r      s   4h??D%dOOD/D	 %d[[]] 	%c)#??H 8$d7h7	% 	% 	% 	% 	% 	% 	%% % % % % % % %
 K E))adhixdyc{|||llnn58?#011a&7T*5E+E+E&s,?&6G^k&*?&;:#gG#g#gUYZdUe#g#gsyB B    H
 3mG[go  yC  Re  qy  CG  Ug  il  mt  iu  iu  Tv  FT  fu  v  v  v  vKKMMM(,XNN!	% 	% 	% 	% 	% 	% 	%% % % % % % % %$  %6==I3m?S_gpy  IZ  fo  y}  O^  _  _  _  _KKMMM)$)	% 	% 	% 	% 	% 	% 	%% % % % % % % %	% 	% 	% 	% 	% 	% 	% 	% 	%% % % % % % % % % % % % % % % % % %sP   GF>0G	CF>G%A F>%G>G	GG	GGGr   c                  t                      5 }|                                5 }t          ||          }|rddi|cd d d            cd d d            S |                     dhdd          }t	          d          |d<   t          |d|          }g }t          | j        d	
          D ]\  }	}
|
                    dd          }|                    ||	d           |	                    d          |d         |d<   |	                    d          &|	                    d          dk    r|d         nd|d<   |
                    t          |d|                     t          ||dddd||                     d          dt          |          i|
  
         |                                 ||dcd d d            cd d d            S # 1 swxY w Y   	 d d d            d S # 1 swxY w Y   d S )Nr{   Tr   r|   r   SOsignoff_codeshipment_signoffsr   r   r}   )
signoff_idr   shipped_quantityr   signed_quantitysign_statussignedr   shipment_signoff_linescreate_shipment_signoffrk   rc   r   r   r   r   )rG   r   )r   r   rx   r   r    rT   r   r   rm   r   rJ   rt   r   r   )rW   r[   rZ   r   rP   r   r5   r   r   r   r   r   s               r   r   r      s:   	 <d[[]] 	<c)#??H 8$d7h7	< 	< 	< 	< 	< 	< 	<< < < < < < < <
 %%widQY%ZZD#,T??D  &94@@J"$H&w}A>>> S S	T OOHOMM	  
s!K!KLLL==!344<4=j4II01==!233;LUMMZgLhLhltLtLt9Z3H3Hz{I/0-Ey Q QRRRR3m?Xdlu~  Na  mw  AH  AS  AS  Y_  AS  A`  A`  nz  |  @H  |I  |I  mJ  \k  l  l  l  lKKMMM$(;;%	< 	< 	< 	< 	< 	< 	<< < < < < < < <	< 	< 	< 	< 	< 	< 	< 	< 	<< < < < < < < < < < < < < < < < < <s@   G#G
G#EG
1G#
G	G#G	G##G'*G'r   c                  t                      5 }|                                5 }t          ||          }|rddi|cd d d            cd d d            S |                     dd          }|                    dd           t          |d|          }t          ||dd	d
d|||	  	         |                                 d|icd d d            cd d d            S # 1 swxY w Y   	 d d d            d S # 1 swxY w Y   d S )Nr{   Tr|   r}   r^   r   r   create_validation_issuerk   rc   r   rG   )r   r   rx   r   r   rT   rt   r   r   s           r   r   r      s   	 
%d[[]] 		%c)#??H 8$d7h7		% 		% 		% 		% 		% 		% 		%
% 
% 
% 
% 
% 
% 
% 
%
 %%4h%GGDOOHf---%8$??I3m?Xdlu~  Na  mv  @D  Ve  f  f  f  fKKMMM)$		% 		% 		% 		% 		% 		% 		%
% 
% 
% 
% 
% 
% 
% 
%		% 		% 		% 		% 		% 		% 		% 		% 		%
% 
% 
% 
% 
% 
% 
% 
% 
% 
% 
% 
% 
% 
% 
% 
% 
% 
%s@   C4CC4A-CC4C	C4"C	#C44C8;C8r   c                  |                      dd          }|                    d          }t                      5 }|                                5 }t	          ||          }|rddi|cddd           cddd           S t          d          |dd	d|rt          |          ndid
|                    d          d}t          |d|          }	|	|d}
d}|                    d| d|
           |j	        }t          ||dddd|	|d|i|
  
         |                                 |	|dcddd           cddd           S # 1 swxY w Y   	 ddd           dS # 1 swxY w Y   dS )zNCreate an auditable reconciliation snapshot from the live reconciliation view.Tr|   r}   
project_idr{   NRCsupplier_vs_upstream_demandzv1-live-shortage	completedr   )run_coder   reconciliation_typepolicy_versioninput_scope
run_statusr   reconciliation_runs)run_idr   zIwhere (%(project_id)s::uuid is null or project_id = %(project_id)s::uuid)aX  
                INSERT INTO reconciliation_lines(
                    run_id, product_id, product_name_standard_draft,
                    supplier_purchase_quantity_total, upstream_demand_quantity_total,
                    formal_order_quantity_total, supplement_demand_quantity_total,
                    difference_supplier_minus_demand, self_stock_candidate_qty, shortage_qty,
                    difference_status, raw_payload
                )
                SELECT
                    %(run_id)s::uuid, product_id, product_name,
                    supplier_purchase_quantity_total, upstream_demand_quantity_total,
                    formal_order_quantity_total, supplement_demand_quantity_total,
                    difference_supplier_minus_demand, self_stock_candidate_qty, shortage_qty,
                    CASE
                        WHEN shortage_qty > 0 THEN 'shortage'
                        WHEN difference_supplier_minus_demand > 0 THEN 'surplus'
                        ELSE 'balanced'
                    END,
                    jsonb_build_object(
                        'project_id', project_id,
                        'product_name', product_name,
                        'generated_from', 'v_supplier_vs_upstream_reconciliation_live'
                    )
                FROM v_supplier_vs_upstream_reconciliation_live
                z
            run_reconciliationrn   rc   r   r   )rG   r   )r   r   r   r   rx   r    r   rT   rN   rowcountrt   r   )rW   r[   rZ   r5   r   r   rP   r   run_datar	  paramsproject_filterr   s                r   r
  r
    s   4h??D,''J	 2<d[[]] 1	<c)#??H 8$d7h71	< 1	< 1	< 1	< 1	< 1	< 1	<2< 2< 2< 2< 2< 2< 2< 2< &dOO('D"4 ,.Uc*oooQUV)'** H S"7BBF &jAAFhNKK 0  1  2 3  4 J=<P\e /DPV,
)CUd   
 KKMMM 
;;c1	< 1	< 1	< 1	< 1	< 1	< 1	<2< 2< 2< 2< 2< 2< 2< 2<1	< 1	< 1	< 1	< 1	< 1	< 1	< 1	< 1	<2< 2< 2< 2< 2< 2< 2< 2< 2< 2< 2< 2< 2< 2< 2< 2< 2< 2<sB   EE(EB)E*EE	E
E	EE #E )r   r   r   r   )r"   r   r   r   )r4   r   r5   r6   r   r   )r[   r   r\   r   r]   r   r^   r   rU   r_   rV   r_   rW   r`   rX   r`   rY   r_   rZ   r_   r   r   )ru   r_   r   r`   )rW   r   r[   r   rZ   r_   r   ry   )rW   r   r[   r   rZ   r_   r   ry   )rW   r   r[   r   rZ   r_   r   ry   )rW   r   r[   r   rZ   r_   r   ry   )rW   r   r[   r   rZ   r_   r   ry   )rW   r   r[   r   rZ   r_   r   ry   )rW   r   r[   r   rZ   r_   r   ry   )rW   r   r[   r   rZ   r_   r   ry   )(
__future__r   r   r   r   decimalr   typingr   r	   uuidr
   psycopgr   psycopg.types.jsonr   dbr   modelsr   r   r   r   r   r   r   r   r    r'   rT   rt   rx   r   r   r   r   r   r   r   r
  r%   r!   r   <module>r     s   " " " " " " - - - - - - - - - -                           $ $ $ $ $ $                         O O O O   % % % %( pt#'$tx'+4           F& & & & Y] % % % % % % ]a % % % % % %, fj % % % % % %4 jn !\ !\ !\ !\ !\ !\H gk % % % % % %8 nr < < < < < <. nr % % % % % % ko 6< 6< 6< 6< 6< 6< 6< 6<r!   