Ë
    ¼vëjÝ!  ã                  óæ   — d Z ddlmZ ddl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mZmZ d	Zd
Zdd„Zdd„Zddd„Zdd„Z	 	 	 	 	 	 	 	 dd„Z	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd„Zdd„Zdd„Zdd„Zy)a„  The pool: one row per organisation per period in the tenant's own ai_credit_periods, moved only here, under
a row lock. The rate a call is priced at is looked up in the platform's master DB by the caller and passed in.

    open_period     the row for now, created from the entitlement when it is the first call of the period
    reserve         hold an estimate before the model runs; refused when the pool cannot cover it
    settle          price what really ran, write the ledger row, release the hold, note marks crossed
    release         let a hold go when nothing ran
    expire_holds    let go of holds whose call never reported back
é    )ÚannotationsN)ÚdatetimeÚ	timedeltaÚtimezone)ÚOptionalÚTupleé   )ÚEntitlement)ÚMARKSÚChargeÚPeriodÚRateé   zSid, organisation_id, period_start, period_end, allowance, purchased, used, reservedc                ó   — d| › d|› �S )Nú"z".© )ÚschemaÚtables     ú^/var/www/html/strategist-ai/venv/lib/python3.12/site-packages/galaxiq_utils/ai_credits/pool.pyÚ_tr      s   € Øˆvˆh�b˜˜Ð Ð ó    c                óz   — t        t        | d   «      t        | d   «      | d   | d   | d   | d   | d   | d   «      S )	Nr   r	   é   é   é   é   é   é   )r   Ústr)Úrows    r   Ú_periodr!      sG   € Ü”#�c˜!‘f“+œs 3 q¡6›{¨C°©F°C¸±F¸CÀ¹FÀCÈÁFÈCÐPQÉFÐTWÐXYÑTZÓ[Ð[r   c           	     ód  — | j                  dt        |d«      › dt        › �|j                  |j                  |j
                  |j                  |j                  f«      j                  «       }|r9| j                  dt        › dt        |d«      › d�|d   f«      j                  «       }t        |«      S )NúINSERT INTO Úai_credit_periodsa   (organisation_id, subscription_id, period_start, period_end, allowance) VALUES (%s, %s, %s, %s, %s) ON CONFLICT (organisation_id, period_start) DO UPDATE SET allowance = EXCLUDED.allowance, subscription_id = EXCLUDED.subscription_id, updated_at = now() RETURNING zSELECT z FROM z WHERE id = %s FOR UPDATEr   )
Úexecuter   Ú_PERIOD_COLUMNSÚorganisation_idÚsubscription_idÚstartÚendÚ	allowanceÚfetchoner!   )Úconnr   ÚentitlementÚlockr    s        r   Úopen_periodr0      s¼   € Ø
�,‰,Ø
”r˜&Ð"5Ó6Ð7ð 8ô %Ð%ð	'ð 
×	$Ñ	$ k×&AÑ&AÀ;×CTÑCTÐVa×VeÑVeØ	×	Ñ	ð	 ó!÷ "*¡£ð ñ Ø�l‰l˜W¤_Ð$5°V¼B¸vÐGZÓ<[Ð;\Ð\uÐvØ ™F˜9ó&ß&.¡h£jð 	ä�3‹<Ðr   c                ó¼   — | j                  «       5  | j                  dt        |d«      › d�|||f«      j                  «       }ddd«       |duS # 1 sw Y   duS xY w)z¸Marks `mark` as told for this period; False when it already was. So a refusal tells the owners
    "used up" exactly once, and a later charge crossing the same mark tells nobody again.úUPDATE r$   zz SET notices_sent = notices_sent || to_jsonb(%s::int) WHERE id = %s AND NOT notices_sent @> to_jsonb(%s::int) RETURNING idN©Útransactionr%   r   r,   )r-   r   Ú	period_idÚmarkr    s        r   Ú	tell_oncer7   -   sŠ   € ð 
×	Ñ	Ó	ñ HØ�l‰l˜W¤R¨Ð0CÓ%DÐ$Eð Fbð cØeiÐktÐvzÐd{ó}÷ ~Fñ  ~Fó  ~Hð 	÷Hð �dˆ?Ð÷Hð �dˆ?Ðús   ‘2AÁAc
                ó@  — | j                  «       5  t        | ||d¬«      }
|€dd|
dfcddd«       S |j                  |d|	«      }|
j                  |k  rd||
dfcddd«       S |dk(  rdd|
dfcddd«       S | j	                  dt        |d	«      › d
�|
j                  |||||t        j                  t        j                  «      t        t        ¬«      z   f«      j                  «       d   }| j	                  dt        |d«      › d�||
j                  f«       t        |
j                  |
j                  |
j                   |
j"                  |
j$                  |
j&                  |
j(                  |
j*                  |z   «      }t-        |«      ||dfcddd«       S # 1 sw Y   yxY w)zm(reservation id, estimate, period, reason). The id is None when refused or nothing was held; reason says why.T©r/   Nr   Úno_rateÚused_upÚ r#   Úai_credit_reservationszv (period_id, product, feature, type, model_key, estimate, expires_at) VALUES (%s, %s, %s, %s, %s, %s, %s) RETURNING id)Úminutesr2   r$   z? SET reserved = reserved + %s, updated_at = now() WHERE id = %s)r4   r0   ÚpriceÚ	remainingr%   r   Úidr   Únowr   Úutcr   ÚHOLD_MINUTESr,   r   r'   r)   r*   r+   Ú	purchasedÚusedÚreservedr   )r-   r   r.   ÚrateÚproductÚfeatureÚtypeÚ	model_keyÚinput_estimateÚoutput_estimateÚperiodÚestimateÚholdÚafters                 r   ÚreserverS   6   s   € ð 
×	Ñ	Ó	ñ .Ü˜T 6¨;¸TÔBˆØˆ<Ø˜˜F IÐ-÷.ñ .ð —:‘:˜n¨a°ÓAˆØ×Ñ˜hÒ&Ø˜ 6¨9Ð4÷.ñ .ð �qŠ=Ø˜˜F BÐ&÷.ñ .ð �|‰|Øœ2˜fÐ&>Ó?Ð@ð A?ð @à�Y‰Y˜ ¨$°	¸8Ü�\‰\œ(Ÿ,™,Ó'¬)¼LÔ*IÑIðKóL÷ MUÉHËJÐWXñ	Zˆð
 	�‰�wœr &Ð*=Ó>Ð?Ð?~ÐØ §	¡	Ð*ô	,ä�v—y‘y &×"8Ñ"8¸&¿,¹,ÈÏ
É
ÐTZ×TdÑTdØ×'Ñ'¨¯©°f·o±oÈÑ6PóRˆä�4‹y˜( E¨2Ð-÷%.÷ .ò .ús   ‘F²'FÁ#
FÁ7DFÆFc                óø  — | j                  «       5  | j                  dt        |d«      › d�|f«      j                  «       }t	        | ||d¬«      }|r%t        |d   |j                  dd¬«      cddd«       S |€t        d	|	› d
|› d|› �«      ‚|j                  |
||«      }d}|r8| j                  dt        |d«      › d�|f«      j                  «       }|r|d   nd}| j                  dt        |d«      › d�||j                  |j                  ||||	|j                  |
|||j                  |j                  ||j                  f«       |j                  }| j                  dt        |d«      › d�||||||j                  f«      j                  «       }|\  }}}|j                   |j"                  z   }t$        D �cg c]+  }|dkD  sŒ	|dz  ||z  cxk  r	|dz  k  sŒn n||xs g vsŒ*|‘Œ- }}|ra| j                  dt        |d«      › d�t'        j(                  t+        t-        |xs g «      t-        |«      z  «      «      |j                  f«       t        |||z
  |z
  ||¬«      cddd«       S c c}w # 1 sw Y   yxY w)z]Prices what ran and takes it off the pool. A call_id seen before changes nothing and says so.zSELECT tokens FROM Úai_usagez WHERE call_id = %sTr9   r   N)Úrepeatedzno enabled rate for z / z and no '*' fallback for r2   r=   zP SET status = 'settled' WHERE id = %s AND status = 'reserved' RETURNING estimater#   a   (call_id, organisation_id, period_id, product, feature, type, model_key, rate_model_key,  input_units, cached_input_units, output_units, input_tokens_per_unit, output_tokens_per_unit, tokens, flagged) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)r$   a   SET used = used + %s, reserved = GREATEST(0, reserved - %s),  used_by_type = used_by_type || jsonb_build_object(%s::text, coalesce((used_by_type ->> %s::text)::bigint, 0) + %s::bigint),  updated_at = now() WHERE id = %s RETURNING used, reserved, notices_sentéd   z$ SET notices_sent = %s WHERE id = %s)Úmarks_crossed)r4   r%   r   r,   r0   r   r@   ÚLookupErrorr?   r'   rA   rL   Úinput_tokens_per_unitÚoutput_tokens_per_unitÚfallbackrF   r+   rE   r   ÚjsonÚdumpsÚsortedÚset)r-   r   r.   rH   Úreservation_idÚcall_idrI   rJ   rK   rL   Úinput_unitsÚcached_input_unitsÚoutput_unitsÚseenrO   ÚtokensÚheldr    ÚbeforerF   rG   ÚtoldÚlimitÚmÚcrosseds                            r   Úsettlern   N   sÄ  € ð 
×	Ñ	Ó	ñ  TØ�|‰|Ð1´"°V¸ZÓ2HÐ1IÐI\Ð]Ð`gÐ_iÓj×sÑsÓuˆÜ˜T 6¨;¸TÔBˆÙÜ˜$˜q™' 6×#3Ñ#3°TÀDÔI÷	 Tñ  Tð
 ˆ<ÜÐ 4°Y°K¸sÀ4À&ÐHaÐbfÐagÐhÓiÐiØ—‘˜KÐ);¸\ÓJˆØˆÙØ—,‘, ¬¨FÐ4LÓ)MÐ(Nð OZð  [Ø]kÐ\móoßowÑowÓoyð á �3�q’6 aˆDØ�‰Øœ2˜f jÓ1Ð2ð 3Rð Sð �f×,Ñ,¨f¯i©i¸À'È4ÐQZÐ\`×\jÑ\jØÐ,¨l¸D×<VÑ<VÐX\×XsÑXsØ�T—]‘]ð$ô		%ð —‘ˆØ�l‰lØ”b˜Ð!4Ó5Ð6ð 7Wð Xð �T˜4  v¨v¯y©yÐ9ó	;÷ <D¹8»:ð	 	ð
  #Ñˆˆh˜Ø× Ñ  6×#3Ñ#3Ñ3ˆÜ#Öv˜ u¨q£y°V¸c±\ÀEÈAÁIÔ5[ÐQUÐX[ÑQ[Ö5[Ð`aÐjnÒjtÐrtÒ`u’1ÐvˆÐvÙØ�L‰L˜7¤2 fÐ.AÓ#BÐ"CÐCgÐhÜŸ*™*¤V¬C°²
¸«O¼cÀ'»lÑ,JÓ%KÓLÈfÏiÉiÐXôZä�f˜e d™l¨XÑ5°tÈ7ÔS÷A Tñ  Tùò8 w÷9 Tð  Tús8   ‘AI0Á7EI0Æ8
I+ÇI+ÇI+Ç$I+Ç(A9I0É+I0É0I9c                ó   — | j                  «       5  | j                  dt        |d«      › d�|f«      j                  «       }|r(| j                  dt        |d«      › d�|d   |d   f«       d d d «       y # 1 sw Y   y xY w)Nr2   r=   z\ SET status = 'released' WHERE id = %s AND status = 'reserved' RETURNING period_id, estimater$   úL SET reserved = GREATEST(0, reserved - %s), updated_at = now() WHERE id = %sr	   r   r3   )r-   r   ra   r    s       r   Úreleaserq   u   s�   € Ø	×	Ñ	Ó	ñ =Ø�l‰l˜W¤R¨Ð0HÓ%IÐ$Jð Kað bØdrÐctóvßv~Ñv~ó  wAð 	áØ�L‰L˜7¤2 fÐ.AÓ#BÐ"Cð D)ð *Ø,/°©F°C¸±FÐ+;ô=÷	=÷ =ñ =ús   ‘AA4Á4A=c           	     ó  — | j                  «       5  | j                  dt        |d«      › d�«      j                  «       }|D ]'  \  }}| j                  dt        |d«      › d�||f«       Œ) t	        |«      cddd«       S # 1 sw Y   yxY w)zVHolds whose call never reported back within HOLD_MINUTES are let go. Returns how many.r2   r=   zf SET status = 'expired' WHERE status = 'reserved' AND expires_at < now() RETURNING period_id, estimater$   rp   N)r4   r%   r   ÚfetchallÚlen)r-   r   Úrowsr5   rP   s        r   Úexpire_holdsrv   ~   s¨   € à	×	Ñ	Ó	ñ Ø�|‰|˜g¤b¨Ð1IÓ&JÐ%Kð Lmð nó oßowÑowÓoyð 	à#'ò 	BÑˆI�xØ�L‰L˜7¤2 fÐ.AÓ#BÐ"Cð D)ð *Ø,4°iÐ+@õBð	Bô �4‹y÷÷ ò ús   ‘A$A?Á?Bc           	     ó>  — t        | ||«      }| j                  dt        |d«      › d�|j                  f«      j	                  «       d   }|j
                  |j                  |j                  |j                  |j                  |xs i |j                  |j                  dœS )NzSELECT used_by_type FROM r$   z WHERE id = %sr   )r+   rE   rF   rG   r@   Úused_by_typeÚperiod_startÚ
period_end)r0   r%   r   rA   r,   r+   rE   rF   rG   r@   r)   r*   )r-   r   r.   rO   Úby_types        r   Úsummaryr|   ‰   s¯   € Ü˜˜v {Ó3€FØ�l‰lÐ6´r¸&ÐBUÓ7VÐ6WÐWeÐfÐio×irÑirÐhtÓu×~Ñ~ó  Að  BCñ  D€GØ×)Ñ)¸×8HÑ8HÐRX×R]ÑR]Ðkq×kzÑkzØ×)Ñ)¸7º=ÀbÐZ`×ZfÑZfÐv|÷  wAñ  wAñBð Br   )r   r   r   r   Úreturnr   )r}   r   )F)r   r   r.   r
   r/   Úboolr}   r   )r   r   r5   r   r6   Úintr}   r~   )r   r   r.   r
   rH   úOptional[Rate]rI   r   rJ   r   rK   r   rL   r   rM   r   rN   r   r}   z&Tuple[Optional[str], int, Period, str])r   r   r.   r
   rH   r€   ra   zOptional[str]rb   r   rI   r   rJ   r   rK   r   rL   r   rc   r   rd   r   re   r   r}   r   )r   r   ra   r   r}   ÚNone)r   r   r}   r   )r   r   r.   r
   r}   Údict)Ú__doc__Ú
__future__r   r]   r   r   r   Útypingr   r   r+   r
   Útypesr   r   r   r   rD   r&   r   r!   r0   r7   rS   rn   rq   rv   r|   r   r   r   ú<module>r‡      sÇ   ðñõ #ã ß 2Ñ 2ß "å "ß .Ó .à€Øg€ó!ó\ôóð.Øð.Ø,/ð.ØBEð.ØJpó.ð0$TØð$TØ"%ð$TØ-0ð$TØ=@ð$TØORð$TØhkð$Tàð$Tà!'ó$TóN=óôBr   