
    vg?              !       4	   d Z ddlZddlZddlmZ ddlmZ ddlmZ ddl	m
Z
mZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZmZ ddlmZ ddlmZ ddlmZm Z  ddl!m"Z" ddl#m$Z$ ddl%m&Z& ddl'm(Z( ddl)m*Z* ddl+m,Z, ddl-m.Z. ddl/m0Z1 ddl2m3Z3 ddl4m5Z5 ddl6m7Z7 ejp                   e
jr                  ddi      ejt                   e
jv                  ddd      ejx                   e
jv                  ddd      ejz                   e
j|                  dd d!d"      ej~                   e
j                  ddi      ej                   e
j                  ddi      ej                   e
j                  ddi      ej                   e
j                  ddi      ej                   e
j                  d#dd      ej                   e
j                  d#dd      ej                   e
j                  d$dd      ej                   e
j                  dd%i      ej,                   e
j                  dd%i      ej                   e
j                  dd&i      ej                   e
j                  dd%i      iZPejp                  e
jp                  ejz                  e
jp                  ej~                  e
j~                  ej                  e
j                  ej                  e
j                  ejt                  e
jx                  ejx                  e
jx                  ej                  e
j                  ej                  e
j                  ej                  e
j                  ej                  e
j                  ej                  e
j                  ej,                  e
j                  ej                  e
j                  ej                  e
j                  iZSd'ZTd( ZUd) ZVeUd*        ZWeUd+ej                  fd,       ZYd- ZZd. Z[ e$j                  d/0      d1        Z]d2e^fd3Z_	 	 	 dSd4e`d5e^d6e`d7ead2e`f
d8ZbdTd9ZcdUd:ead;e`fd<Zdd=eed>e^d?eefd@Zf G dA dB      ZgdCej                  dDe`fdEZh	 dVdGe`dFe`dHeifdIZjdJ Zkd+ej                  dKe`d2eefdLZld+ej                  dMemd2e^fdNZndO ZodPeedCemd2efdQZpdR Zqy)Wz
horilla/cbv_methods.py
    N)Any)	urlencode)logger)formstemplate)messages)cache)	Paginator)models)
ForeignKey)ForwardManyToOneDescriptorReverseOneToOneDescriptor)HttpResponse)	get_token)redirectrender)loader)register)render_to_string)reverse)lazy)format_html)
SafeString)gettext_lazy)settings)_thread_locals)getattributeclasszoh-input w-100)attrsfile)typer      (   )r   rowscolsdatetimezoh-select oh-select-2 w-100z/oh-select oh-select-2 select2-hidden-accessible)) z
----------)TYes)FNoc                       fd}|S )z
    Decorator that allows decorators to accept arguments and keyword arguments.

    Args:
        decorator (function): The decorator function to be wrapped.

    Returns:
        function: The wrapper function.

    c                        fd}|S )a  
        Wrapper function that captures the arguments and keyword arguments.

        Args:
            *args: Variable length argument list.
            **kwargs: Arbitrary keyword arguments.

        Returns:
            function: The inner wrapper function.

        c                      | gi S )z
            Inner wrapper function that applies the decorator to the function.

            Args:
                func (function): The function to be decorated.

            Returns:
                function: The decorated function.

             )funcargs	decoratorkwargss    -/var/www/horilla/horilla_views/cbv_methods.pyinner_wrapperz@decorator_with_arguments.<locals>.wrapper.<locals>.inner_wrapper|   s     T3D3F33    r.   )r0   r2   r4   r1   s   `` r3   wrapperz)decorator_with_arguments.<locals>.wrappero   s    	4 r5   r.   )r1   r6   s   ` r3   decorator_with_argumentsr7   c   s    8 Nr5   c                       fd}|S )z2
    Decorator to check authenticity of users
    c                    t        t        d      }t        | dd       s|| _        |j                  }|j	                  dd      d   j                         j                  dd      j                         }|dk(  rd}||j                  d	<   |d
k(  s|dk(  rdj                         |j                  d	<   |j                  j                  sFt        d      }t        |j                        }| d|j                   }|r|d| z  }t        |      S 	  | |g|i |}	|	S # t        $ rL}
t!        j"                  |
       t$        j&                  st)        |d      cY d }
~
S  | g|i |cY d }
~
S d }
~
ww xY w)Nrequest/r"      - PMSPerformancetitler(   	Dashboardloginz?next=&zwent_wrong.html)getattrr   r:   pathsplit
capitalizereplaceuppersessionuseris_authenticatedr   r   GETr   	Exceptionr   	exceptionr   DEBUGr   )selfr0   r2   r:   rF   res	login_urlparamsurlr/   e	view_funcs              r3   wrapped_viewz$login_required.<locals>.wrapped_view   s_   .)4tY-"DL||jja #..088cBHHJ%<C#& 2:'2'8'8':GOOG$||,,(Iw{{+FKvgll^4C6(|#C= 	4T7<T<V<D   	4Q>>g'899T3D3F33		4s*   D 	E1%0E,E1E,&E1,E1r.   )rX   rY   s   ` r3   login_requiredrZ      s    
6 r5   c                       fd}|S )z0
    Decorator to validate user permissions
    c                 t   t        t        d      }t        | dd       s|| _        |j                  j	                        r | g|i |S t        j                  |d       |j                  j                  dd      }d}||j                  j                         v rt        |d      S d| d}t        |      S )	Nr:   zYou dont have permission.HTTP_REFERERr;   HTTP_HX_REQUESTdecorator_404.html <script>window.location.href = "
"</script>)rE   r   r:   rL   has_permr   infoMETAgetkeysr   r   )	rR   r0   r2   r:   previous_urlkeyscriptfunctionperms	          r3   	_functionz&permission_required.<locals>._function   s    .)4tY-"DL<<  &D242622MM'#>?"<<++NC@L#Cgll''))g';<<7~ZPF''r5   r.   )rj   rk   rl   s   `` r3   permission_requiredrm      s    (  r5   model_classc                       fd}|S )z?
    Decorator for check feature enabled in singlton model
    c                 \   j                   j                         }t        |	d      }|r 
| |g|i |S t        j                  |t        d             |j                  j                  dd      }d}||j                  j                         v rt        |d      S d| d}t        |      S )	NFz&Feature is not enabled on the settingsr]   r;   r^   r_   r`   ra   )objectsfirstrE   r   rc   _transrd   re   rf   r   r   )rR   r:   r0   r2   general_settingenabledrg   rh   ri   feature_namerj   rn   s            r3   rl   z(check_feature_enabled.<locals>._function   s    %--335/<?D';D;F;;gv&NOP||''<',,##%%'#7883L>LF##r5   r.   )rj   rv   rn   rl   s   ``` r3   check_feature_enabledrw      s    $ r5   c                       fd}|S )z>
    Decorator method that only allow HTMX metod to enter
    c                 p    d}|| j                   j                         vrt        | d      S  | g|i |S )Nr^   z405.html)rd   rf   r   )r:   r0   r2   rh   rj   s       r3   rl   z&hx_request_required.<locals>._function   s?    gll''))':..1$1&11r5   r.   )rj   rl   s   ` r3   hx_request_requiredrz      s    
2 r5   c                 ,    t        dt        |             S )Nz;<input type="hidden" name="csrfmiddlewaretoken" value="{}">)r   r   )r:   s    r3   
csrf_inputr|      s    E' r5   T)takes_contextc                 ~    	 | d   }t        t        t        t
              } ||      S #  t        t        d      }Y 5xY w)z@
    to access csrf token inside the render_template method
    r:   )rE   r   r   r|   r   str)contextr:   csrf_input_lazys      r3   
csrf_tokenr      s?    
5)$ :z37O7##5.)4s   ( <returnc                 .   t        | dd      }i }t        j                  d   d   d   D ]J  }|j                  dd      \  }}t	        ||g      }t        ||      } ||       }|j                  |       L t        |      |d	<   || _        | j                  S )
zI
    This method will return dictionary format of context processors
    all_context_variablesNr   OPTIONScontext_processors.r<   )fromlistr   )rE   r   	TEMPLATESrsplit
__import__updater   r   )r:   r   processor_pathmodule_path	func_namemoduler/   r   s           r3   get_all_context_variablesr     s     w/6> "&003I>?ST 	2N%3%:%:3%B"KykBF69-D7mG!((1	2 /99N.Ol+(=%(((r5   rF   r   decodingstatusc                 p   t        t        dd      }|j                  t        |             t	        j
                  |       }|j                  j                  }t        j                  |      }t        j                  |      }	|j                  |	      }
t        |
|      j                  j                  |      S )z?
    This method is used to render HTML text with context.
    r:   N)r   )rE   r   r   r   r   get_templater   sourceTemplateContextr   r   contentdecode)rF   r   r   r   _usingr:   template_loadertemplate_bodytemplate_bdycontext_instancerendered_contents              r3   render_templater     s     ni6GNN,W56))$/O#,,33M$$]3L''0#**+;<(8@@GGQQr5   c                 @    t        | |      }|j                  |      } | S )z2
    This method is used to paginate queryset
    )r
   get_page)qrysetpage_numberrecords_per_page	paginators       r3   paginator_qryr   (  s&     &"23I,FMr5   lengthprefixc                     t        t        j                         j                        }|t        |d|        j	                  dd      z   S )z&
    Short uuid generating method
    Nr=   r(   )r   uuiduuid4hexrI   )r   r   uuid_strs      r3   get_short_uuidr   1  s>     4::<##$HC&)*223;;;r5   r:   r	   viewc                    |j                  | j                  j                  dz         r:|j                  | j                  j                  dz         j                  |i i       y |j	                  | j                  j                  dz   |i i       y )Ncbv)re   rK   session_keyr   set)r:   r	   r   s      r3   update_initial_cacher   9  sn    yy,,u45		'//--56==tRjI	IIgoo))E1D":>
r5   c                   6    e Zd ZU dZeed<   dZeed<   defdZy)ReverseTr   r(   pager   c                 ,    t        | j                        S )N)r   r   )rR   s    r3   __str__zReverse.__str__F  s    4<<  r5   N)	__name__
__module____qualname__r   bool__annotations__r   r   r   r.   r5   r3   r   r   B  s!    GTD#N! !r5   r   valueattrc                    | }|j                  d      }|D ]  }t        ||      r4t        ||      }t        |t              s,|j
                  j                  }Ct        |d      rFt        |j
                  t              r,t        |j
                  j                  j                  |d      }t        |d      st        |t              st        |j                  j                  |d      } |S )zL
    Gets an attribute of a model dynamically, handling related fields.
    __fieldNrelated)rG   hasattrrE   
isinstancer   r   related_modelr   remote_fieldmodelr   r   )r   r   resultr   s       r3   getmodelattributer   J  s     FJJtE 
G64 VT*F&"<=33VW%*V\\:*NV\\66<<dDIFVY'J--
 V^^994FF
G Mr5   r   rh   is_first_sortc                 4   t        t        dd      }| |   t        j                  |j                  j
                  dz         st        j                  |j                  j
                  dz   t                      | j                  |      sdn| j                  |      t        j                  |j                  j
                  dz         _        t        j                  |j                  j
                  dz         }|j                  }g g }|j                  }	t        |	      }
t        |
t        j                        }|sE |j                  di  ddi}t!        |j#                  dd            |j%                  	      }fd
}| }| j                  |      }|s|r| }|j                  |k(  r|s| }||_        	 t'        |||      }||_	        |rd}t!        |      t!        |      z   }nt!        |      t!        |      z   }d}t+        |d|       t+        |d       t        j                  |j                  j
                  dz   |       |S # t(        $ r< t!        |j                  	            }t'        |j%                  	      ||      }Y w xY w)z:
    New simplified method to sort the queryset/lists
    r:   N	cbvsortby1__isnullTid)flat)id__inc                 \    t        |       }|j                  | j                         |S )N)r   )r   appendpk)objectr   none_idssort_keys     r3   _sortbyzsortby.<locals>._sortbyw  s)    f84>OOFII&r5   )rh   r   ascdesc
sort_orderr   r.   )rE   r   CACHEre   rK   r   r   r   r   r   r   r   r   typesFunctionTypefilterlistvalues_listexcludesorted	TypeErrorsetattr)
query_dictquerysetrh   r   r   r:   reverse_objectr   none_querysetr   
model_attr	is_methodr   ordercurrent_pager   r   s                  @@r3   sortbyr   ^  sP    ni6G#H99W__00;>?		'//--;WYG!~~d+C1E 			'//--;<A YYw::[HIN$$GHMNNE"5(3J:u'9'9:I'HhZx+@$*GH11$T1BC##8#4 KE>>$'L}	,.}IE*Y(?
 #N>D$77&h7G\5)GZ*	IIgoo))K7HO  YX__H_=>(**(*;RWXYs   ?I AJJc                    |j                  | j                  j                  | j                  z   dz         r]|j                  | j                  j                  | j                  z   dz         j	                  | j                  | j
                  d       |S |j                  | j                  j                  | j                  z   dz   | j                  | j
                  d       |S )z(
    Method to save filter on cache
    r   )rF   r   )re   rK   r   rF   r   rN   r   )r:   r	   s     r3   update_saved_filter_cacher     s     yy,,w||;eCD		'//--<uDELL%kk	
 	II##gll2U:LL!++	
 Lr5   
field_namec                     d|v rD|j                  dd      }t        | |d         j                  j                  }t	        ||d         S t        | |      }|S )z:
    Recursion function to execute nested field logic
    r   r<   r   )rG   r   r   r   get_nested_fieldr   )rn   r   splitsrelated_model_classr   s        r3   r   r     se     z!!$*/1I
 '-- 	   3VAY??j1ELr5   bulk_update_fieldsc                 N    i }|D ]  }t        | |      }|j                  ||<    |S )z
    Returns a dictionary mapping field names to their corresponding field classes
    for a given model class, including related fields(one-to-one).
    )r   r   )rn   r   field_class_mapr   r   s        r3   get_field_class_mapr     s:    
 O( 2
 j9&+kk
#2 r5   c                 J    t        t        dd      }| |d}t        d|      }|S )zK
    Render the form fields as HTML table rows with Bootstrap styling.
    r:   N)formr:   zgeneric/form.html)rE   r   r   )rR   r:   r   
table_htmls       r3   
structuredr    s4     ni6GG ""5w?Jr5   r   c           	         ddl m} t        | t        j                        r|D cg c]  }t        |       c}S t        | t        j                  t        j                  t        j                  t        j                  t        j                  t        j                  f      r|d   }|S  |t        |d               }|S c c}w )z;
    return value according to the format of the field
    r   )eval_validate)base.methodsr  r   r   ManyToManyFieldint	DateFieldDateTimeField	CharField
EmailField	TextField	TimeFieldr   )r   r   r  vals       r3   value_to_fieldr    s     +%//0$)*SC**	  	


 a#eAh-(EL +s   B=c                     | j                         }|j                         D ]N  \  }}||v r@|j                         D ],  \  }}|||   v r||   |   j                  |       %|||   |<   . J|||<   P |S )z#
    Method to merge two dicts
    )copyitemsextend)dict1dict2merged_dictrh   r   rn   	instancess          r3   merge_dictsr    s     **,Kkkm %
U+*/++- >&Y+c"22$[188C4=K$[1	>  %K% r5   )zutf-8NN)2   )hlv)r   F)r__doc__r   r   typingr   urllib.parser   venvr   djangor   r   django.contribr   django.core.cacher	   r   django.core.paginatorr
   	django.dbr   django.db.models.fields.relatedr   +django.db.models.fields.related_descriptorsr   r   django.httpr   django.middleware.csrfr   django.shortcutsr   r   django.templater   django.template.defaultfiltersr   django.template.loaderr   django.urlsr   django.utils.functionalr   django.utils.htmlr   django.utils.safestringr   django.utils.translationr   rs   horillar   horilla.horilla_middlewaresr   3horilla_views.templatetags.generic_template_filtersr   r
  	TextInput
ImageField	FileInput	FileFieldr  TextareaIntegerFieldNumberInput
FloatFieldDecimalFieldr  
EmailInputr  	DateInputr	  DateTimeInputr  	TimeInputBooleanFieldSelectr  SelectMultipleOneToOneFieldFIELD_WIDGET_MAPModelChoiceFieldModelMultipleChoiceFieldMODEL_FORM_FIELD_MAPBOOLEAN_CHOICESr7   rZ   rm   Modelrw   rz   r|   
simple_tagr   dictr   r   r  r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r.   r5   r3   <module>rM     s      "  " # , +  6 % , - " 3 3  ( ) . ;  6 L oeooW6F,GH
u(89 oeoo(89 nenn%	
 ***';K1LM
(u((9I/JK
***';K1LM
'u''w8H.IJ
oeoo(89 -%--(89 oeoo(89 w0M&NO
|u||W.K$LM
0E00IJ ,%,,1N'OPC" J eoo
eoo
++
u''
++
u
eoo
u''
eoo
%--
eoo
++
u--
E::
%00 &(V F  0 v||  * 4(	$ )	$)$ )( R
RR R 	R 	R*<3 < <&  V ! !V\\  * OT6"6*-6GK6r0&,, C F 	V\\ 	t 	PT 	
&  # 2r5   