o
    ÞÙ$iŽ  ã                   @   s¾   d dl mZmZmZ d dlmZ deeef dedefdd„Zdeeef dee fd	d
„Zdeeef dee fdd„Z	deeef defdd„Z
deeef deeeef  fdd„ZdS )é    )ÚDictÚAnyÚOptional)Úlookup_abn_basicÚdÚpathÚreturnc                 G   s,   | }|D ]}t |tƒs dS | |¡}q|S )zy
    Helper sencillo para navegar dicts anidados.
    _get_nested(extracted, "invoice", "seller", "abn", "computed")
    N)Ú
isinstanceÚdictÚget)r   r   ÚcurrentÚkey© r   úF/var/www/html/flask_server/apps/wp_invoices/integrations/tax_lookup.pyÚ_get_nested   s   
r   Úfieldc                 C   s:   t | tƒsdS |  d¡p|  d¡}|sdS t|ƒ ¡ pdS )u˜   
    Con tu estructura tÃ­pica:
    {
      "verbatim": "...",
      "computed": "...",
      ...
    }
    Tomamos prioridad: computed > verbatim.
    NÚcomputedÚverbatim)r	   r
   r   ÚstrÚstrip)r   Úvaluer   r   r   Ú_extract_best_value   s   

r   Ú	extractedc                 C   sž   |   d¡pi }|   d¡pi }|  d¡}|  d¡}|rt|ƒnd}|s/|  d¡}|r-t|ƒnd}|s3dS | dd¡ ¡ }| d	d¡ ¡ }td
ƒ t|ƒ |pNdS )uÀ   
    Intenta obtener el ABN del proveedor desde 'extracted'.

    Ajusta las rutas segÃºn tu JSON real. Dejo varias opciones tÃ­picas:
    - invoice.seller.abn
    - invoice.seller.tax_id
    ÚinvoiceÚheaderÚsupplierÚabnNÚtax_idú Ú zABN#zbusiness extracted?)r   r   Úreplacer   Úprint)r   r   r   r   Ú	abn_fieldr   Útax_id_fieldr   r   r   Ú_get_seller_abn_from_extracted&   s   


r$   c                 C   sN   |   d¡pi }|  d¡pi }|  d¡}|rt|ƒnd}|sdS t|ƒ ¡ p&dS )u]   
    Intenta obtener el paÃ­s del proveedor. Si no encuentra nada, usa 'AU' por defecto.
    r   ÚsellerÚcountryNÚAU)r   r   r   r   )r   r   r%   Úcountry_fieldr&   r   r   r   Ú"_get_seller_country_from_extractedF   s   
r)   c                 C   s”   t | ƒ}| ¡ dvrdS t| ƒ}|sdS t|ƒ}| dd¡| dd¡| dd¡| d	d
¡| d|¡t| d¡ƒt| d¡ƒt| d¡ƒ| d¡dœ	S )u»   
    Ejecuta el lookup bÃ¡sico (V0) si la factura tiene un ABN de Australia.
    Devuelve un dict listo para meterse en checks["tax_lookup_basic"],
    o None si no se debe ejecutar.
    )r'   ÚAUSÚ	AUSTRALIANÚserviceÚ
abn_lookupÚversionr   r&   r'   Útax_id_typeÚABNr   Ú
abn_existsÚ	is_activeÚgst_registeredÚentity_name)	r,   r.   r&   r/   r   r1   r2   r3   r4   )r)   Úupperr$   r   r   Úbool)r   r&   r   Úbasicr   r   r   Úrun_basic_tax_lookupU   s"   




÷r8   N)Útypingr   r   r   Úapps.abn_lookup_app.corer   r   r   r   r$   r)   r8   r   r   r   r   Ú<module>   s    *