
    j"                        d Z ddlmZ ddl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mZ ddlmZ ddlmZmZ ddlmZmZ d	Z ed
dh      Z G d de      Z edd       G d d             Z G d d      Zg dZy)z@Durable at-most-once customer notice after canonical activation.    )annotationsN)contextmanager)asdict	dataclassreplace)Path)IteratorMapping)AddressConfigurationError'parse_customer_private_delivery_addressu   고객 등록이 완료되었습니다.
코칭 시작일: {starts_on}
아침 체크인: 평일 {daily_time}
시작일의 해당 시간 이후 첫 체크인 안내를 보내드릴게요.sent_auditedunknownc                      e Zd ZdZy)ActivationNoticeErrorz7Activation notice state is malformed, stale, or unsafe.N)__name__
__module____qualname____doc__     k/home/cube/projects/richard/.worktrees/nutricoach-v140-impl/gateway/platforms/telegram_activation_notice.pyr   r      s    Ar   r   T)frozenslotsc                      e Zd ZU ded<   ded<   ded<   ded<   ded<   ded<   ded	<   ded
<   dZded<   dZded<   dZded<   dZded<   y)ActivationNoticeReceiptstrreservation_idcustomer_key	starts_on
daily_timebodydict[str, str]destinationauthority_digeststateNz
str | Noneprovider_receiptreasonr   intappend_sequenceFboolprovider_authority)r   r   r   __annotations__r&   r'   r)   r+   r   r   r   r   r       sX    NO
IJ#'j'FJOS$$r   r   c                      e Zd ZdZddZedd       Zedd       Z	 	 	 	 	 	 	 	 	 	 	 	 ddZ	ddZ
	 	 	 	 	 	 ddZddZ	 	 	 	 	 	 dd	Z	 	 	 	 	 	 	 	 	 	 dd
ZddZddZddZddZddZy)ActivationNoticeStorezGAppend-only reservation ledger for one completion notice per authority.c                    t        |      }|j                         rt        d      |j                  ddd       |dz  dz  | _        |dz  dz  | _        y )Nz%profile root symlinks are not allowedT  parentsexist_okmodedataz#activation-completion-notices.jsonlz"activation-completion-notices.lock)r   
is_symlinkr   mkdirpath	lock_path)selfprofile_rootroots      r   __init__zActivationNoticeStore.__init__3   sV    L!??'(OPP

4$U
;6M$II	)MMr   c              #  ,  K   | j                   j                  j                  ddd       | j                   j                  j                  d       | j                   j	                         s| j
                  j	                         rt        d      t        j                  | j
                  t        j                  t        j                  z  d      }	 t        j                  | j
                  d       t        j                  |dd      5 }t        j                  |j                         t        j                         d  t        j                  |j                         t        j                          d d d        y # 1 sw Y   y xY w# t"        $ r  w xY ww)	NTr0   r1   z"activation notice paths are unsafe  za+utf-8encoding)r8   parentr7   chmodr6   r9   r   osopenO_CREATO_RDWRfdopenfcntlflockfilenoLOCK_EXLOCK_UN	Exception)r:   fdlocks      r   _lockedzActivationNoticeStore._locked;   s    		tdG		u%99!T^^%>%>%@'(LMMWWT^^RZZ"))%;UC	HHT^^U+2tg6$DKKM5==9DKKM5==9 766  		sC   CF8F A)E:1F 9F:F?F FF FFc                    	 t        |       }t        |j                        t        |j
                        t        |j                        dS # t        $ r}t        t        |            |d }~ww xY w)N)user_idchat_idtopic_id)r   r   r   r   rT   rU   rV   )valuer#   excs      r   _validate_destinationz+ActivationNoticeStore._validate_destinationK   sj    	;A%HK ;../;../K001
 	
 ) 	;'C1s:	;s   A 	A/A**A/c               P   | j                  |      }|rt        |      dkD  rt        d      	 ddlm}m} |j                  |       |j                  |       t        |      dk7  st        d |D              rt        d      t        j                  ||d d	 
      }
t        j                  |||d d	 ||ddd      }t        j                  |j!                               j#                         }| j%                         5  | j'                         j)                  |      }||cd d d        S t+        ||||d d	 |
||dt        | j-                               dz   	      }| j/                  |       |cd d d        S # t        t        f$ r}	t        d      |	d }	~	ww xY w# 1 sw Y   y xY w)N   z%activation notice customer is invalidr   )datetimez%activation notice schedule is invalid@   c              3  $   K   | ]  }|d v 
 yw)0123456789abcdefNr   ).0cs     r   	<genexpr>z0ActivationNoticeStore.reserve.<locals>.<genexpr>j   s     -dScaa7I.IScs   z-activation notice authority digest is invalid   )r   r    )r   r   r    r#   r$   T,:)	sort_keys
separatorsprepared   )	r   r   r   r    r!   r#   r$   r%   r)   )rY   lenr   datetimer\   r]   fromisoformat	TypeError
ValueErroranyACTIVATION_COMPLETION_TEMPLATEformatjsondumpshashlibsha256encode	hexdigestrR   _latest_unlockedgetr   _rows_unlocked_append_unlocked)r:   r   r   r    r#   r$   destination_pinr\   r]   rX   r!   materialr   latestreceipts                  r   reservezActivationNoticeStore.reserveW   s    44[As<036'(OPP	Z+y)z*  B&#-dSc-d*d'(WXX-44!"1~ 5 
 :: ,&(!n.$4 !

 !(9:DDF\\^**,00@F! ^ .-)#%bq>+!1  #D$7$7$9 :Q >
G !!'*! ^) :& 	Z'(OPVYY	Z( ^s*   *E9 ?#F,AF9FFFF%c                ,    | j                  |ddd      S )Nrj   sendingTr+   _transitionr:   r   s     r   mark_sendingz"ActivationNoticeStore.mark_sending   s    YSWXXr   c               b    |rt        |      dkD  rt        d      | j                  |dd|      S )Nr[   z-activation notice provider receipt is invalidr   	delivered)r&   )rl   r   r   )r:   r   r&   s      r   mark_deliveredz$ActivationNoticeStore.mark_delivered   sD      3'7#83#>'(WXX-	   
 	
r   c                (    | j                  |dd      S )Nr   r   r   r   s     r   mark_auditedz"ActivationNoticeStore.mark_audited   s    nEEr   c               x    |j                   dvrt        d      | j                  ||j                   d|d d       S )N>   r   rj   z activation notice is not pendingr   r[   )r'   )r%   r   r   )r:   r   r'   s      r   mark_unknownz"ActivationNoticeStore.mark_unknown   sC     == 77'(JKK	&QURU,WWr   c                   | j                         5  | j                         j                  |j                        }||j                  |k7  s|t        |d      k7  rt        d|       t        |f|t        | j                               dz   t        |j                  dd            d|}| j                  |       |cd d d        S # 1 sw Y   y xY w)NFr   zactivation notice is not rk   r+   )r%   r)   r+   )rR   rz   r{   r   r%   r   r   rl   r|   r*   popr}   )r:   r   expectedtargetchangescurrentupdateds          r   r   z!ActivationNoticeStore._transition   s     \\^++-11'2H2HIG'--8";w'RYnsJt?t+.Gz,RSS #D$7$7$9 :Q >#'4H%(P#Q	
 G !!'* ^^s   B.C		Cc                    | j                         5  t        | j                               cd d d        S # 1 sw Y   y xY wN)rR   tupler|   r:   s    r   receiptszActivationNoticeStore.receipts   s&    \\^,,./ ^^s   4=c                    | j                         5  t        | j                         j                               cd d d        S # 1 sw Y   y xY wr   )rR   r   rz   valuesr   s    r   r   zActivationNoticeStore.latest   s/    \\^..0779: ^^s   'AAc                   | j                   j                         sg S | j                   j                         s| j                   j                         st	        d      g }	 | j                   j                  d      j                         D ]G  }t        j                  |      }t        |t              st        |j                  t        di |       I 	 |S # t        t        t        t        j                   f$ r}t	        d      |d }~ww xY w)Nz"activation notice ledger is unsafer@   rA   z#activation notice ledger is corruptr   )r8   existsr6   is_filer   	read_text
splitlinesrt   loads
isinstancedictrp   appendr   OSErrorro   JSONDecodeError)r:   rowslinerawrX   s        r   r|   z$ActivationNoticeStore._rows_unlocked   s    yy!I99!):):)<'(LMM.0	X		++W+=HHJjj&!#t,$$3:c:;	 K  J0D0DE 	X'(MNTWW	Xs   A4C #D
9DD
c                R    i }| j                         D ]  }|||j                  <    |S r   )r|   r   )r:   r   rows      r   rz   z&ActivationNoticeStore._latest_unlocked   s/    57&&(C),F3%%& )r   c           	        t        t        |d            }| j                  j                  dd      5 }|j	                  t        j                  |ddd      d	z          |j                          t        j                  |j                                d d d        | j                  j                  d
       y # 1 sw Y   %xY w)NFr   ar@   rA   Tre   )ensure_asciirh   ri   
r?   )r   r   r8   rF   writert   ru   flushrE   fsyncrL   rD   )r:   r   payloadledgers       r   r}   z&ActivationNoticeStore._append_unlocked   s    UCDYY^^C'^2fLLG%4\fgjnnoLLNHHV]]_% 3 				 32s   AB77C N)r;   z
Path | strreturnNone)r   zIterator[None])rW   Mapping[str, object]r   r"   )r   r   r   r   r    r   r#   r   r$   r   r   r   )r   r   r   r   )r   r   r&   r   r   r   )r   r   r'   r   r   r   )
r   r   r   r   r   r   r   objectr   r   )r   z#tuple[ActivationNoticeReceipt, ...])r   zlist[ActivationNoticeReceipt])r   z"dict[str, ActivationNoticeReceipt])r   r   r   r   )r   r   r   r   r=   r   rR   staticmethodrY   r   r   r   r   r   r   r   r   r|   rz   r}   r   r   r   r.   r.   0   s   QN   	
 	
5 5 	5
 5 *5 5 
!5nY

.

EH

	 

FX.X;>X	 X(  	
  
!*0; r   r.   )rr   r   r   r.   )r   
__future__r   rJ   rv   rt   rE   
contextlibr   dataclassesr   r   r   pathlibr   typingr	   r
   .gateway.platforms.telegram_nutrition_addressesr   r   rr   	frozenset_TERMINAL_STATESrp   r   r   r.   __all__r   r   r   <module>r      s    F "    	 % 2 2  $T  ni89 BJ B $d#% % $%p pfr   