o
    pj8M                     @   s$  d dl Z d dlZd dlmZ d dlmZ d dlmZmZm	Z	 d dl
mZmZ d dlmZ d dlmZmZ d dlmZmZ d d	lmZ ed
Zed
dddeddddg dddiddiddiddiddddeddddg ddddddg d iddd!dd"d#ddd$d%giddid&ddg d'd(d)dd)d*d+d,d-
ed.d/ddg ddddddg d iddd!dd"d#ddd$d%giddid&ddg d0d(d)dd)d*d+d,d-
ed1d2ddd3gd3dd4d5iddg d6d(d+d7d8ed9d:ddd3d;gdd4d5dd"d#ddg d<idd=d5dd=d5dd=d5d>ddg d?d(d)dd)d+d@dAdB
edCdDeeejdE  dd3dFgd(d)d)d+dGdHdIe	dJdKdLdMdNdOdPdQZdRdS ZdTdU ZdVdW ZdXe fdYdZZ!d[d\ Z"dod]d^Z#d_d` Z$dadb Z%dcdd Z&dedf Z'dge dXe(fdhdiZ)dXefdjdkZ*dle+e ef dXe dB fdmdnZ,dS )p    N)Path)Any)ActionContractAppManifestWordPressPackageContract)error_envelopesuccess_envelope)call_app)get_platform_loggerlog_structured)StorageQuotaExceededwrite_bytes)QuotaExceededwp_invoiceszInvoice Processorz1.1.6z<Extract and validate normalized data from invoice documents.zplatform.healthz:Report local invoice processor readiness without using AI.objectFhealthy
ai_checkedapp_versionextractor_versiontypebooleanstring)r   additionalPropertiesrequired
properties )
capabilitydescriptionoutput_schemaerrorszinvoice.document.submitz;Submit one PDF or image invoice for synchronous extraction.)filenamecontent_typefile_bytes_base64idempotency_key      )r   	minLength	maxLengthenum)zapplication/pdfz
image/jpegz	image/pngz
image/webp)r   r'         minithinking)r!   r"   r#   r$   engineforce_uncached)
invoice_idstatusresult	artifacts)r   r   Ti,  
restricted)invalid_inputunsupported_document_typedocument_too_largestorage_quota_exceededai_quota_exceededextraction_failed)
r   r   input_schemar   side_effects
idempotentidempotency_key_requiredtimeout_secondsdata_classificationr    invoice.document.submit_trustedzOSubmit one invoice through unified extraction and deterministic quality review.)r0   r1   r2   r3   supplier_profileinvoice.result.readzGRead one tenant-isolated canonical invoice result by opaque invoice ID.r0   z^inv_[a-f0-9]{32}$)r   pattern)r0   r1   r2   )r5   invoice_not_found)r   r   r;   r   r@   r    invoice.diagnostics.runzdRun restricted OCR and recovery-schema smoke tests without processing the stored invoice through AI.r$   )all
ocr_layoutrecovery_schemaforced_fullaudit_reportz^[a-f0-9-]{36}$)r0   r$   testocr_smoke_request_idrecovery_smoke_request_idread_request_id)pipeline_version
ocr_passedrecovery_schema_passedartifact_root   )r5   r:   )
r   r   r;   r   r<   r=   r>   r@   r?   r     invoice.supplier_profile.confirmzRActivate allowlisted supplier-layout corrections after explicit user confirmation.z1contracts/supplier-profile-confirm.v1.schema.jsonrB   )r5   confirmation_identity_requiredrE   supplier_profile_not_found)r   r   r;   r   r<   r=   r@   r    )	health_v1	submit_v1submit_trusted_v1	result_v1smoke_diagnostics_v1confirm_supplier_profile_v1wp_invoices_wpz	1.1.6-devzwordpress-pack/wp-invoices-wpzwp-invoices-wp.phpz!wp-invoices-wp/wp-invoices-wp.php)rA   rC   rU   rF   )
package_idversionsource_directory
entrypointplugin_filecapabilities)app_iddisplay_namer   r   actionswordpress_packagec                 C   s   ddl m} | | d S )Nr%   )bp)api.v1.blueprintri   register_blueprint)appbp_v1r   r   7/var/www/html/flask_server/apps/wp_invoices/__init__.pyregister_blueprints   s   ro   c                 C   s   |dkrt | S |dkrt| S |dkrt| ddS |dkr"t| S |dkr*t| S |dkr2t| S |d	kr@d
d| d d dS |dkrHt| S |dr[ttj	|t
| ddddfS dd| ddfS )NrX   rY   rZ   T)
trusted_v2r[   r\   r]   rL   okr   tenant	tenant_id)r1   rl   rr   process_v1action_not_foundz&The requested action is not supported.re   action
request_idcodemessage  errorzUnknown action: r1   r{   )_health_submit_result_smoke_diagnostics_confirm_supplier_profile_handle_processendswithr   APP_MANIFESTre   _request_id)contextrx   r   r   rn   handle_request   s<   

r   c              	   C   sT   t tdt| t| p
i dpi dpddd ttjdt| dd	tjd
ddS )Nwp_invoices_health_checkedrr   rs    r   )ry   rs   outcomerX   TFzunified-v2.3-ocr-layoutr   re   rx   ry   data)	r   LOGGERr   strgetr   r   re   r   r   r   r   rn   r      s"   r   returnc                 C   s   t | pi dp	dS )Nry   r   )r   r   r   r   r   rn   r      s   r   c              
   C   s   ddl m} z|| }W n- ty#   ttjdt| ddddf Y S  ty9   ttjdt| dd	dd
f Y S w ttjdt| |dS )Nr   )run_smoke_testsr\   r5   z"The smoke-test request is invalid.rw     r:   z'The smoke tests could not be completed.  r   )	+apps.wp_invoices.services.smoke_diagnosticsr   
ValueErrorr   r   re   r   	Exceptionr   )r   r   r   r   r   rn   r      s*   r   c                 C   s  ddl m}m} z
|r|n|| }W n tyP } z2t|dv r$t|nd}dddd}ttj|r3d	nd
t| ||| d|dkrCdndfW  Y d }~S d }~w t	yw } zttj|r^d	nd
t| ddd|j
iddfW  Y d }~S d }~w ty   ttj|rd	nd
t| dddddf Y S  ty   ttdt| t| pi dpi dpdddd ttj|rd	nd
t| ddd dd!f Y S w ttd"t| t| pi dpi dpd|d# d$d% ttj|rd	nd
t| |d&d'id(S ))Nr   )submit_invoicesubmit_invoice_v2>   r5   r7   r6   r5   z"The invoice submission is invalid.z5Only PDF, JPEG, PNG, and WebP invoices are supported.z6The invoice document exceeds the maximum allowed size.)r5   r6   r7   rZ   rY   rw   r7     r   r8   z5The tenant storage quota does not allow this invoice.requested_bytes)re   rx   ry   rz   r{   detailsr9   zBThe tenant AI allowance is not sufficient to process this invoice.F)re   rx   ry   rz   r{   	retryablei  wp_invoices_submission_failedrr   rs   r   failedr:   )ry   rs   r   
error_codez#The invoice could not be processed.Tr    wp_invoices_submission_completedr0   	completed)ry   rs   r0   r   processing_modesynchronous)re   rx   ry   r   meta)$apps.wp_invoices.services.submissionr   r   r   r   r   r   re   r   r   r   r   r   r   r   r   r   )r   rp   r   r   r   excrz   messagesr   r   rn   r      s   




r   c              	   C   sr   ddl m} z|| }W n! ty   t| dddd Y S  ty-   t| dddd	 Y S w ttjdt| |d
S )Nr   )read_invoice_resultr[   r5   zThe invoice ID is invalid.r   rE   z!The invoice result was not found.r|   r   )	r   r   r   _contract_errorLookupErrorr   r   re   r   )r   r   r   r   r   rn   r   #  s   r   c              
   C   s   ddl m} z|| }W nD ty   t| dddd Y S  ty-   t| dddd	 Y S  tyP } zt|d
kr<d
nd}t| d|ddW  Y d }~S d }~ww ttj	dt
| |dS )Nr   ) confirm_invoice_supplier_profiler]   rV   z+A signed-in user must confirm this profile.i  r5   z"The profile correction is invalid.r   rE   rW   z,The supplier profile could not be confirmed.r|   r   )r   r   PermissionErrorr   r   r   r   r   r   re   r   )r   r   r   r   rz   r   r   rn   r   .  s   r   c                 C   s   t tj|t| ||d|fS )Nrw   )r   r   re   r   )r   rx   rz   r{   r1   r   r   rn   r   <  s   r   c              
   C   s  ddl m} ddlm} ddlm} | dpi }t|dp d }t|dp+d }|s8d	d
ddfS |sAd	dddfS zt	|}W n t
yc } zd	d| ddfW  Y d }~S d }~ww t|dpkd}	|d}
|dpxi }t| }|d t| dpd }|d }|jddd |jddd zt| d d dtdt| dpd | |d}W n  ty } zd	dt||j ddfW  Y d }~S d }~ww ||||	|
| d }|d!pi }t|d"pi }||}d }|d#du r!t|}|rt| d$d%d&|id'}nd	d$d(d)}t|tr!||d#< |d* }|d+ }|jtj|d,d-d.d/d0 |jtj|d,d-d.d/d0 |d urW|d1 jtj|d,d-d.d/d0 ||t|||d2}d3| d d dd4|||t|d5d6S )7Nr   )analyze)create_invoice_revision_pdf)process_invoice_bytespayloadr!   r   r#   r}   zMissing filenamer~   r   zMissing file_bytes_base64zInvalid file_bytes_base64: r"   zapplication/octet-streamr.   optionsstagingry   request	revisionsT)parentsexist_okrr   rs   r   )rs   re   relative_pathr   r8   )r1   rz   r{   storager   )
file_bytesr!   r"   r.   r   	extractedchecks
tax_lookupabn_lookup_applookupabn)r   rl   rx   r   zABN not found)r1   rl   r{   zextracted.jsonzanalysis.jsonF   )ensure_asciiindentzutf-8)encodingztax_lookup.json)r   
output_diroriginal_filenamer   rq   rt   )r   analysisr   pdf)r1   rr   rl   rx   r2   )"apps.wp_invoices.services.analyzerr   .apps.wp_invoices.services.invoice_revision_pdfr   "apps.wp_invoices.services.pipeliner   r   r   strip_decode_file_bytesr   _resolve_app_storagemkdirr   r   r   snapshotto_dictdict_extract_abn_for_lookupr	   
isinstance
write_textjsondumps)r   r   r   r   r   r!   r#   r   r   r"   r.   r   app_storage_rootstaging_dirrevisions_diroriginal_pathpipeline_resultr   r   r   tax_lookup_resultr   extracted_pathanalysis_pathpdf_pathr   r   rn   r   @  s    




r   encodedc                 C   sD   |   }d|v r|ddd dr|ddd }tj|ddS )N,r%   r   zdata:T)validate)r   split
startswithbase64	b64decode)r   rawr   r   rn   r     s   r   c                 C   s@   t t jd }t t| dpd}| s|| }|d S )Nr   r   zstorage/tenants/unknownr   )r   __file__resolver   r   r   is_absolute)r   base_dirstorage_rootr   r   rn   r     s
   r   r   c                 C   s   |  dpi }| dpi }dD ]/}| |pi }t|tsq| dp(| d}|r?t|dddd }|r?|  S qd S )	Nheadersupplier)r   tax_idcomputedverbatim r   zABN#)r   r   r   r   replacer   )r   r   r   keyfieldvalue
normalizedr   r   rn   r     s   
r   )F)-r   r   pathlibr   typingr   bridge_platform.apps.contractsr   r   r   bridge_platform.apps.envelopesr   r   bridge_platform.interapp.clientr	   'bridge_platform.logging.platform_loggerr
   r   bridge_platform.storage.servicer   r   bridge_platform.quotas.servicer   r   loadsr   parent	read_textr   ro   r   r   r   r   r   r   r   r   r   r   bytesr   r   r   r   r   r   r   rn   <module>   s   


$






iy 
Ie"