Ë
    ¼vëj  ã                  óö   — d Z ddlmZ ddlZddlZddlZddlmZ ddlmZm	Z	 ddl
mZ  ej                  d«      ZdZ ed	¬
«       G d„ d«      «       Zdd„Zdd„Zdd„Z	 	 	 	 	 	 dd„Zdd„Zdd„Zddd„Zdd„Zy)a¦  What an organisation may spend this period, read from the platform's own records.

The subscription's snapshot (featureConfiguration, written at checkout) is the truth when it exists; the plan's
productFeatures when it does not. Effective AI capacity includes purchased recurring packs;
per-product token features are not read. The period is the subscription's; a yearly subscription gets monthly windows from its anchor.
é    )ÚannotationsN)Ú	dataclass)ÚdatetimeÚtimezone)ÚOptionalzgalaxiq.ai_creditsÚ	AI_TokensT)Úfrozenc                  ó@   — e Zd ZU ded<   ded<   ded<   ded<   ded	<   y
)ÚEntitlementÚstrÚorganisation_idzOptional[str]Úsubscription_idr   ÚstartÚendÚintÚ	allowanceN)Ú__name__Ú
__module__Ú__qualname__Ú__annotations__© ó    úc/var/www/html/strategist-ai/venv/lib/python3.12/site-packages/galaxiq_utils/ai_credits/allowance.pyr   r      s   … àÓØ"Ó"ØƒOØ	ƒMØ„Nr   r   c                ób   — | �| j                   r| S | j                  t        j                  ¬«      S )N)Útzinfo)r   Úreplacer   Úutc)Úds    r   Ú_awarer      s&   € Ø�	˜QŸXšXˆ1ÐI¨1¯9©9¼H¿L¹L¨9Ó+IÐIr   c                óê   — t        | j                  dz  | j                  z   dz
  |z   d«      \  }}| j                  ||dz   t	        | j
                  t        j                  ||dz   «      d   «      ¬«      S )Né   é   )ÚyearÚmonthÚday)Údivmodr#   r$   r   Úminr%   ÚcalendarÚ
monthrange)r%   Úmonthsr#   r$   s       r   Ú
add_monthsr+   "   sl   € Ü˜Ÿ™ B™¨¯©Ñ2°QÑ6¸Ñ?ÀÓD�K€Dˆ%Ø�;‰;˜D¨°©	´s¸3¿7¹7ÄH×DWÑDWÐX\Ð^cÐfgÑ^gÓDhÐijÑDkÓ7lˆ;ÓmÐmr   c                óÌ   — |j                   | j                   z
  dz  |j                  z   | j                  z
  }t        | |«      |kD  r|dz  }t        | |«      t        | |dz   «      fS )Nr!   r"   )r#   r$   r+   )ÚanchorÚnowr*   s      r   Úanniversary_windowr/   '   s`   € Ø�h‰h˜Ÿ™Ñ$¨Ñ*¨S¯Y©YÑ6¸¿¹ÑE€FÜ�&˜&Ó! CÒ'Ø�!‰ˆÜ�f˜fÓ%¤z°&¸&À1¹*Ó'EÐEÐEr   c                ó~  — t        | «      t        |«      t        |«      }}} |rw|j                  d«      dk(  rc|j                  d«      }|r.t        t        j                  |j	                  dd«      «      «      n| }t        |xs ||«      \  }}|r||kD  r|}||fS | r|r| |cxk  r|k  r| |fS  t        |xs ||«      S )zQThe same window the platform backend uses (subscriptionUsageService.usageWindow).ÚbillingCycleÚyearlyÚallowanceAnchorÚZz+00:00)r   Úgetr   Úfromisoformatr   r/   )	r   r   ÚcreatedÚsnapshotr.   Úanchor_textr-   Úwindow_startÚ
window_ends	            r   Úusage_windowr<   .   sÆ   € ô ! ›-¬°«´f¸W³o�ˆ3€EÙ�H—L‘L Ó0°HÒ<Ø—l‘lÐ#4Ó5ˆÙWb”œ×.Ñ.¨{×/BÑ/BÀ3ÈÓ/QÓRÔSÐhmˆÜ#5°f²mÀÀSÓ#IÑ ˆ�jÙ�: Ò#ØˆJØ˜ZÐ'Ð'Ù‘˜ #Ô+¨Ò+Ø�cˆzÐð ,ä˜gšn¨¨cÓ2Ð2r   c                ó–   — t        | �| nd«      j                  dd«      j                  «       }|j                  «       rt	        |«      S d S )NÚ ú,)r   r   ÚstripÚisdigitr   )ÚvalueÚtexts     r   Ú_wholerD   >   s@   € Ü˜Ð)‰u¨rÓ2×:Ñ:¸3ÀÓC×IÑIÓK€DØŸ™œŒ3ˆt‹9Ð0¨DÐ0r   c           	     ó˜  — t        | t        «      rt        j                  | «      n| xs g } g g }}| D �]Ñ  }t        |t        «      sŒ|j                  d«      dk(  }|j                  d«      xs g D �]�  }t        |t        «      r|j                  d«      t        k7  rŒ-|j                  d«      du r|r|j                  d«       ŒTt        |j                  d«      «      }t        |j                  d	«      «      }|j                  d
«      }t        |t        «      rt        |j                  d«      «      nd}	t        |j                  d«      «      }
|€Pt        |j                  d	d«      «      j                  «       j                  «       dv r|r|n|j                  d«       �Œ1|s|€|	€|
€�Œ;t        d„ |||	|
fD «       d«      }|€�ŒV|r|j                  |«       �Œk|€|dkD  r|
�t        ||
«      }|j                  |«       �Œ“ �ŒÔ |r|n|}|rd|v ryt        t        |«      «      dkD  rt        j!                  d|«       t        |«      S )a,  One platform allowance, never the sum of repeated product mappings.

    Plan-scope rows are authoritative. Legacy product rows can carry the same
    shared included total beside smaller per-product caps; preserve that floor,
    but never add those rows or their recurring quantities together.
    ÚfeatureScopeÚplanÚfeaturesÚ
featureKeyÚenabledFr   ÚeffectiveAllowanceTotalÚcappingValueÚaiTokenConfigurationÚAI_TokenNÚincludedAllowanceTotalr>   )Ú	unlimitedz-1c              3  ó&   K  — | ]	  }|€Œ|–— Œ y ­w©Nr   )Ú.0Úvs     r   ú	<genexpr>zai_allowance.<locals>.<genexpr>b   s   è ø€ ÒT ÀaÁmœ!ÑTùs   ‚Šr"   zKai credits: conflicting platform AI totals %s; using largest, not their sum)Ú
isinstancer   ÚjsonÚloadsÚdictr5   ÚAI_KEYÚappendrD   r@   ÚlowerÚnextÚmaxÚlenÚsetÚlogÚwarning)ÚproductsÚvaluesÚplan_valuesÚblockÚ
plan_scopeÚfeatureÚ	effectiveÚcapÚconfigÚshareÚbaserB   Úselecteds                r   Úai_allowancero   C   s  € ô (2°(¼CÔ'@Œt�z‰z˜(Ô#ÀxÂ~ÐSU€HØ˜bˆK€FØó  %ˆÜ˜%¤Ô&ØØ—Y‘Y˜~Ó.°&Ñ8ˆ
Ø—y‘y Ó,Ò2°ó 	%ˆGÜ˜g¤tÔ,°·±¸LÓ0IÌVÒ0SØØ�{‰{˜9Ó%¨Ñ.ÙØ×&Ñ& qÔ)ØÜ˜wŸ{™{Ð+DÓEÓFˆIÜ˜Ÿ™ ^Ó4Ó5ˆCØ—[‘[Ð!7Ó8ˆFÜ6@ÀÌÔ6N”F˜6Ÿ:™: jÓ1Ô2ÐTXˆEÜ˜'Ÿ+™+Ð&>Ó?Ó@ˆDØÐ ¤S¨¯©°^ÀRÓ)HÓ%I×%OÑ%OÓ%Q×%WÑ%WÓ%YÐ]pÑ%pÙ *‘°×>Ñ>¸tÔDÙá )Ð"3¸¸È$È,ÙÜÑT i°°e¸TÐ%BÔTÐVZÓ[ˆEØˆ}ÙÙØ×"Ñ" 5Ö)ð Ð$¨°ª°tÐ7GÜ  tÓ,�EØ—‘˜eÖ$ò9	%ð	 %ñB *‰{¨v€HÙ�t˜xÑ'ØÜ
Œ3ˆx‹=Ó˜AÒÜ�‰ÐaÐckÔlÜˆx‹=Ðr   c           	     óÐ  — |xs# t        j                  t        j                  «      }| j	                  dt        |«      j                  d«      f«      j                  «       }|sy|d   \  }}}}}}	t        | |«      }
|
r$|
j                  d«      du r|
j                  d«      n|	}t        ||||
|«      \  }}t        t        |«      |rt        |«      nd||t        |«      xs d«      S )zcThe organisation behind this tenant and what its newest live subscription allows. None without one.a5  SELECT o.id AS org, s.id AS sub, s."currentPeriodStart" AS starts, s."currentPeriodEnd" AS ends,        s."createdAt" AS created, p."productFeatures" AS plan_features FROM "Organisations" o JOIN "Subscriptions" s ON s."organisationId" = o.id LEFT JOIN "Plans" p ON p.id = s."planId" WHERE o."tenantId"::text = %s   AND (s."isActive" = TRUE OR lower(coalesce(s.status, '')) IN ('active', 'trial', 'trialing')        OR (s."trialStart" IS NOT NULL AND s."trialEnd" IS NOT NULL AND now() BETWEEN s."trialStart" AND s."trialEnd")) ORDER BY s."createdAt" DESC NULLS LASTÚorg_Nr   ÚactiveTÚproductFeatures)r   r.   r   r   Úexecuter   ÚremoveprefixÚfetchallÚ	_snapshotr5   r<   r   ro   )ÚconnÚ	tenant_idr.   ÚrowsÚorgÚsubÚstartsÚendsr7   Úplan_featuresr8   rc   r   r   s                 r   Úread_entitlementr€   u   sß   € à
Ò
+”—‘œhŸl™lÓ+€CØ�<‰<ð	1ô 
ˆY‹×	$Ñ	$ VÓ	,Ð.ó
0÷ 19±³
ð 	ñ ØØ59¸!±WÑ2€Cˆˆf�d˜G ]Ü˜˜sÓ#€HÙ2:¸x¿|¹|ÈHÓ?UÐY]Ñ?]ˆx�|‰|Ð-Ô.Ðcp€HÜ˜f d¨G°X¸sÓC�J€Eˆ3Ü”s˜3“x©S¤ S¤°d¸EÀ3ÌÐU]ÓH^ÒHcÐbcÓdÐdr   c                óè   — | j                  d«      j                  «       }|sy| j                  d|f«      j                  «       }|r|d   nd}t        |t        «      rt	        j
                  |«      S |S )z`The checkout snapshot, when the platform has that column (it does not yet on every environment).ztSELECT 1 FROM information_schema.columns WHERE table_name = 'Subscriptions' AND column_name = 'featureConfiguration'Nz@SELECT "featureConfiguration" FROM "Subscriptions" WHERE id = %sr   )rt   ÚfetchonerV   r   rW   rX   )rx   r   ÚhasÚrowrB   s        r   rw   rw   Œ   so   € à
�,‰,ð Bó CßCKÁ8Ã:ð áØØ
�,‰,ÐYÐ\kÐ[mÓ
n×
wÑ
wÓ
y€CÙˆC�ŠF˜t€EÜ *¨5´#Ô 6Œ4�:‰:�eÓÐA¸EÐAr   )r   úOptional[datetime]Úreturnr…   )r%   r   r*   r   r†   r   )r-   r   r.   r   r†   Útuple)r   r…   r   r…   r7   r…   r8   úOptional[dict]r.   r   r†   r‡   )r†   zOptional[int]rR   )ry   r   r.   r…   r†   zOptional[Entitlement])r†   rˆ   )Ú__doc__Ú
__future__r   r(   rW   ÚloggingÚdataclassesr   r   r   Útypingr   Ú	getLoggerra   rZ   r   r   r+   r/   r<   rD   ro   r€   rw   r   r   r   ú<module>r�      s�   ðñõ #ã Û Û Ý !ß 'Ý à€g×ÑÐ,Ó-€à	€ñ �$Ô÷ð ó ðóJónó
Fð3Ø)ð3Ø08ð3Ø=Bó3ó 1ó
/ôdeô.Br   