
    vg0                       d 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m	Z	 ddl
Z
ddlmZ ddlmZ ddlmZ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$m%Z% ddl&m'Z'm(Z( ddl)m*Z*m+Z+ ddl,m-Z-m.Z.m/Z/m0Z0 ddl1m2Z2 ddl3m4Z4 ddl5m6Z6 ddl7m8Z8 ddl9m:Z:m;Z;m<Z<m=Z=m>Z> ddl?m@Z@mAZAmBZB  ej                  eD      ZEd ZFd ZGdSdZHd ZI G d d e      ZJ G d! d"e      ZK G d# d$      ZLe/e. e0d%      d&                      ZMe/e. e0d'      d(                      ZNe/e.e- e0d'      d)                             ZOe/e.e- e0d*      d+                             ZPe/e.e- e0d'      d,                             ZQe/e.e- e0d'      d-                             ZRe/e.e- e0d.      d/                             ZSe/e.e- e0d%      d0                             ZTe/e.e- e0d*      d1                             ZUd2 ZVd3 ZWd4 ZXd5 ZYe/e. e0d6      d7                      ZZe/e.e- e0d6      d8                             Z[e/e. e0d9      d:                      Z\e/e. e0d;      d<                      Z]e/e.e- e0d;      d=                             Z^e/e. e0d9      d>                      Z_e/e. e0d9      d?                      Z`e/e. e0d9      d@                      Zae/e.e- e0dA      dB                             Zbe/e.e- e0d'      dC                             ZcdD ZddE ZedF Zf	 e@j                  j                         j                  dGH      Zje@j                  j                  dIJ      D ]  Zlels eFelj                        dkD  selj                  dKk(  r= e       Zoeoj                  dL dM eFelj                        N       eoj                          ielj                  dOk(  r= e       Zoeoj                  dP dM eFelj                        N       eoj                          elj                  dQk(  r> e       Zoeoj                  dR dM eFelj                        N       eoj                           y#  Y yxY w)Ta  
Module for managing biometric devices and employee attendance.

Includes classes and functions for adding, editing, and deleting biometric devices,
as well as scheduling attendance capture. Also provides views for managing employees,
registered on biometric devices.
    N)datetime)EventThread)parse_qsunquote)BackgroundScheduler)messages)HttpResponseJsonResponse)redirectrender)timezone)gettext)gettext_lazy)ZK)	exception)Request)clock_in	clock_out)get_key_instancesget_pagination)EmployeeEmployeeWorkInformation)hx_request_requiredinstall_requiredlogin_requiredpermission_required)HorillaPaginator)BIO_DEVICE_THREADS   )COSECBiometric)BiometricDeviceFilter)BiometricDeviceFormBiometricDeviceSchedulerFormCosecUserAddFormCOSECUserFormEmployeeBiometricAddForm)BiometricDevicesBiometricEmployeesCOSECAttendanceArgumentsc                 |    g d}t        d t        |t        t        | j	                  d                  D              S )z
    this method is used reconvert time in H:M formate string back to seconds and return it
    args:
        time : time in H:M format
    )i  <   r    c              3   ,   K   | ]  \  }}||z    y wN ).0abs      #/var/www/horilla/biometric/views.py	<genexpr>z#str_time_seconds.<locals>.<genexpr>=   s     EAq1uEs   :)sumzipmapintsplit)timeftrs     r3   str_time_secondsr=   5   s0     CES#c4::c?*C!DEEE    c                 P    t        | t                     }|j                  |      } | S )z3
    This method is used to paginate query set
    )r   r   get_page)qrysetpage_number	paginators      r3   paginator_qryrD   @   s(     !)9:I,FMr>   c                     |dz
  |z  }||z  }i }| || |d<   t        |       }||z   dz
  |z  }|dkD  }||k  }	||r|dz
  nd|	r|dz   nd|||	d|d<   |S )zC
    This function is used to paginate a list of dictionaries.
    r    usersN)numberprevious_page_numbernext_page_number	num_pageshas_previoushas_nextrC   )len)
	data_listrB   per_pagestart_index	end_indexpaginated_datatotal_itemstotal_pagesrK   rL   s
             r3   biometric_paginator_qryrU   I   s     ?h.Kh&IN'I>N7i.K)A-(:K?L[(H 3?aT/7K!OT $#N; r>   c                 N    t        j                         }| j                  |       y)z
    Sets the time on the biometric device using the provided connection.

    Parameters:
    - conn: The connection to the biometric device.

    Returns:
    None
    N)r   todayset_time)connnew_times     r3   biometric_set_timer[   b   s     ~~HMM(r>   c                   .     e Zd ZdZ fdZd Zd Z xZS )ZKBioAttendancea8  
    Represents a thread for capturing live attendance data from a ZKTeco biometric device.

    Attributes:
    - machine_ip: The IP address of the ZKTeco biometric device.
    - port_no: The port number for communication with the ZKTeco biometric device.
    - conn: The connection object to the ZKTeco biometric device.
    - _stop_event: Event flag to signal thread termination.

    Methods:
    - run(): Overrides the run method of the Thread class to capture live attendance data.
    - stop(): Sets the _stop_event to signal the thread to stop gracefully.
    c                     t         |           || _        || _        t	        |      | _        t               | _        d | _        y r.   )	super__init__
machine_ipport_nor9   passwordr   _stop_eventrY   )selfra   rb   rc   	__class__s       r3   r`   zZKBioAttendance.__init__   s8    $H 7	r>   c           	      L   	 t        | j                  | j                  d| j                  dd      }|j	                         }|| _        |rt        j                  j                  | j                  | j                        j                         }|rj|j                  r\| j                  j                         s@|j                         }|D ]  }|r|j                  }|j                  }t!        j"                  |j$                        }|j'                         }	|j)                         }
|	|_        |
|_        |j/                          t0        j                  j                  |      j                         }|s|dv r.	 t3        t5        |j6                  j8                  |	|
|             	 tA        t5        |j6                  j8                  |	|
|              | j                  j                         s?y y y y y # t:        $ r!}t<        j?                  d|       Y d }~Wd }~ww xY w# t:        $ r!}t<        j?                  d	|       Y d }~d }~ww xY w# tB        $ rC}tE        | j                  | j                  | j                        jG                          Y d }~y d }~ww xY w)
N   Fporttimeoutrc   	force_udp
ommit_ping)ra   rj   user_id   r         userdater;   r   zGot an error in clock_in %szGot an error in clock_out)$r   ra   rb   rc   connectrY   r(   objectsfilterfirstis_liverd   is_setlive_capturero   punchdjango_timezone
make_aware	timestampru   r;   last_fetch_datelast_fetch_timesaver)   r   r   employee_idemployee_user_id	Exceptionloggererrorr   ConnectionResetErrorr]   start)re   	zk_devicerY   deviceattendances
attendancero   
punch_code	date_timeru   r;   bio_idr   s                r3   runzZKBioAttendance.run   s\   E	R\\ I $$&DDI)1188#T\\ 9 %'  fnn"..557&*&7&7&9*5 1)J)*4*<*<-7-=-=
,;,F,F$.$8$8-"	 (1~~'7'0~~'79= 69= 6 &);)C)C)J)J,3 *K *""'%' !' $*'1Y'>)5,4079?9K9K9\9\9=9==F	12-.)5,5079?9K9K9\9\9=9==F	12-. !)c1) #..5577 -6	 D 09 )5,2LL0Mu-. -5)5  09 )5,2LL0KU-. -5	)5 $ 	RDOOT\\4==IOOQQ	Rsr   E5I 8I =,G=)I +,H*I =	H'H"I "H''I *	I3I	I II 	J# 9JJ#c                 &    d| j                   _        y)z To stop the ZK live capture modeTN)rY   end_live_capturere   s    r3   stopzZKBioAttendance.stop   s    %)		"r>   __name__
__module____qualname____doc__r`   r   r   __classcell__rf   s   @r3   r]   r]   p   s    FRP*r>   r]   c                   .     e Zd ZdZ fdZd Zd Z xZS )COSECBioAttendanceThreadaG  
    A thread class that handles the real-time retrieval and processing of
    biometric attendance data from a COSEC biometric device.

    Attributes:
        device_id (int): The ID of the biometric device to interact with.
        _stop_event (threading.Event): An event to signal when to stop the thread.

    Methods:
        run():
            Continuously fetches attendance data from the COSEC device, processes
            it, and updates the last fetched sequence and rollover count.

        stop():
            Signals the thread to stop by setting the _stop_event.
    c                 N    t         |           || _        t               | _        y r.   )r_   r`   	device_idr   rd   )re   r   rf   s     r3   r`   z!COSECBioAttendanceThread.__init__   s    " 7r>   c           	      |   	 t         j                  j                  | j                        }|j                  sy t
        j                  j                  |      j                         }|rt        |j                        nd}|rt        |j                        nd}t        |j                  |j                  |j                  |j                  d      }| j                   j#                         s|j%                  |t        |      dz         }t'        |t(              s| j                   j+                  d       e|D ]  }|d   }t,        j                  j                  |	      j                         }	|	s9|d
   }
|d   }t/        j0                  |
d      j3                         }t/        j0                  |d      j5                         }t/        j6                  ||      }|d   }t9        |	j:                  j<                  ||t?        j@                  |            }	 |dv rtC        |       n|dv rtE        |        |r3|d   }|d   }|d   }t
        j                  jM                  |||d       | j                   j+                  d       | j                   j#                         sy y # tF        $ r!}tH        jK                  d|       Y d }~d }~ww xY w# tF        $ ra}t         j                  j                  | j                        }d|_        |jO                          tH        jK                  d|       Y d }~y d }~ww xY w)Nidr   r   r    
   rk   rh   detail-1ref_user_idru   r;   %d/%m/%Y%H:%M:%Sdetail-2rs   135790246810Error processing attendance: seq-Noroll-over-countlast_fetch_roll_ovr_countlast_fetch_seq_numberr   defaults   Fz#Error in COSECBioAttendanceThread: )(r(   rw   getr   rz   r*   rx   ry   r9   r   r   r!   ra   rj   cosec_usernamecosec_passwordrd   r{   get_attendance_events
isinstancelistwaitr)   r   strptimeru   r;   combiner   r   r   r~   r   r   r   r   r   r   update_or_creater   )re   r   device_argsr   r   cosecr   r   r   employeedate_strtime_strattendance_dateattendance_timeattendance_datetimer   request_datar   last_attendances                      r3   r   zCOSECBioAttendanceThread.run   s   O	G%--11T^^1DF>>2::AA  B eg  ?JK99:q & ;FK5561 " #!!%%%%E &&--/#99-s3H/IA/M "+t4$$))!,"- MJ",Z"8K199@@$/  A  eg  $ )&1H)&1H&.&7&7*&M&R&R&TO&.&7&7*&M&R&R&TO*2*:*:'+' ",J!7J#*%11BB,,!0!;!;<O!P	$LM%)GG$\2'+EE%l37M> &1"oO,;H,E)0?@Q0R-,44EE"(9R5J" F    %%a(g &&--//H % M%DeLLM"  	G%--11T^^1DF"FNKKMLL>FF		GsI   6K GK J$4A,K $	K-K	K 	KK 	L;AL66L;c                 8    | j                   j                          y)z;Set the stop event to signal the thread to stop gracefully.N)rd   setr   s    r3   r   zCOSECBioAttendanceThread.stop=  s    r>   r   r   s   @r3   r   r      s    "#
PGdr>   r   c                   (    e Zd ZdZd Zd Zd Zd Zy)AnvizBiometricDeviceManagerzJManages communication with Anviz biometric devices for attendance records.c                 j    t         j                  j                  |      | _        d| _        d| _        y)z
        Initializes the AnvizBiometricDeviceManager.

        :param device_id: The Object ID of the biometric device.
        r   N)r(   rw   r   r   
begin_timeend_time)re   r   s     r3   r`   z$AnvizBiometricDeviceManager.__init__E  s-     '..22i2@r>   c                 .   t        j                         }| j                  j                  rT| j                  j                  r>t        j
                  | j                  j                  | j                  j                        n|j                  dddd      | _        || _        | j                  j                         dz   }| j                  j                         dz   }ddd| j                  j                  ddd	| j                  j                  d
||dddddS )z
        Constructs the payload for retrieving attendance records.

        :return: A dictionary containing the payload.
        r   )hourminutesecondmicrosecondz+00:00zattendance.record	getrecord1.02022-10-21T07:39:07+00:00	nameSpace
nameActionversion	requestIdr   token)typer   ascr   100)r   r   orderpagerO   )header	authorizepayload)r   utcnowr   r   r   r   replacer   r   	isoformatanviz_request_id	api_token)re   current_utc_timebegin_time_strend_time_strs       r3   get_attendance_payloadz2AnvizBiometricDeviceManager.get_attendance_payloadO  s     $??, {{**t{{/J/J T[[88$++:U:UV!))q1RS)T 	
 )224x?}}..08; 1) ![[998  ..
 -(!
 	
r>   c                    ddd| j                   j                  dd| j                   j                  | j                   j                  dd}t	        j
                  | j                   j                  |d	      }|j                         }|d
   d   }|d
   d   }|| j                   _        || j                   _	        | j                   j                          y)z
        Refreshes the API token for the device.

        This method sends a request to the API to refresh the token.
        authorize.tokenr   r   r   r   api_key
api_secretr   r      jsonrk   r   expiresN)r   r   r  r  requestspostapi_urlr  r   api_expiresr   )re   token_payloadresponseapi_responser   r  s         r3   refresh_api_tokenz-AnvizBiometricDeviceManager.refresh_api_tokens  s     /% ![[998  ;;.."kk44
 ==!4!4=RTU}}Y'0y))4 %")r>   c                    ddddddd}| j                         }t        j                  | j                  j                  |d      }|j                         }||k(  r\| j                          | j                         }t        j                  | j                  j                  |d      }|j                         }|j                         d	   d
   }|dkD  r|d	   d   }t        d|dz         D ]  }t        |      |d	   d<   t        j                  | j                  j                  |d      }|j                         |k(  rL| j                          | j                         }t        j                  | j                  j                  |d      }|j                         j                  d	i       j                  dg       }|d	   d   j                  |        | j                  j                         | j                  j                         c| j                  _        | j                  _        | j                  j!                          |S )z
        Retrieves attendance records from the biometric device.

        :return: A dictionary containing the attendance records.
        Systemr   r   nameTOKEN_EXPIRESr   messager  r  r  r   	pageCountr    r   r   r   )r   r	  r
  r   r  r  r  rangestrr   extendr   ru   r;   r   r   r   )re   token_expireattendance_payloadr  r  
page_countr   page_recordss           r3   get_attendance_recordsz2AnvizBiometricDeviceManager.get_attendance_records  s     %-kB /OL
 "88:==KK&8"
  }}<'""$!%!<!<!>}}##*<bH $==?L]]_Y/<
>%i08Daa0 E8;D	"9-f5#==KK''.@" ==?l2**,)-)D)D)F&'}}++2Db H  (}}229bAEEfbQY'/66|DE MM MM  	A#T[[%@ 	r>   N)r   r   r   r   r`   r   r  r   r/   r>   r3   r   r   B  s    T"
H6+r>   r   zbiometric.view_biometricdevicesc                     t               }t               }t        j                  j	                  d      j                  d      }t        || j                  j                  d            }d}|||d}t        | ||      S )a#  
    Renders a page displaying a list of active biometric devices.

    Parameters:
    - request: The HTTP request object.

    Returns:
    - HttpResponse: The rendered HTML page displaying the list of biometric devices.

    Template:
    - "biometric/view_biometric_devices.html"

    Context:
    - biometric_form (BiometricDeviceForm): Form for adding new biometric devices.
    - devices (QuerySet): Queryset of active biometric devices, ordered by creation date.
    - f (BiometricDeviceFilter): Form for filtering biometric devices.

    T	is_active-created_atr   z%biometric/view_biometric_devices.html)biometric_formdevicesf)
r#   r"   r(   rw   rx   order_byrD   GETr   r   )requestr%  filter_formbiometric_devicestemplatecontexts         r3   biometric_devices_viewr/    s    , )*N')K(0077$7GPP &&79PQ6H($G
 '8W--r>   z!biometric.change_biometricdevicesc                     t         j                  j                  |      dj                  i}t	        |      }||d}| j
                  dk(  rt	        | j                        }|j                         rj                  dk(  r	 j                  }j                  }j                  }d}t        ||dt        |      d	d	
      }	|	j                         }|j                  d       | j                  j                  d      }
t         j                  j                  |      |
_        d_        d	_        j%                          t'               }|j)                  fddt+        j                               |j-                          t/        d      S j                  dk(  r| j                  j                  d      }
d_        |
_        j%                          t'               }|j)                  fddt+        j                               |j-                          t/        d      S | j                  j                  d      }
d_        d	_        |
_        j%                          t'               }t7        j                  j8                        }|r!|j;                          t6        j8                  = |j)                  fddt+        j                               |j-                          t/        d      S ||d<   t=        | d|      }t/        |j>                  jA                  d      dz         S t=        | d|      S # t0        $ r-}t2        j5                  d|       d}t/        |      cY d}~S d}~ww xY w)aX  
    Handles scheduling of attendance capture from a biometric device.

    Parameters:
    - request (HttpRequest): The HTTP request object.
    - device_id (uuid): The ID of the biometric device for which scheduling is being done.

    Returns:
    - HttpResponse: HTML response indicating success or failure of the scheduling operation.
    r   scheduler_durationinitial)scheduler_formr   POSTzkNrh   Fri   r   indexTc                  .    t         j                        S r.   )zk_biometric_device_attendancer   r   s   r3   <lambda>z+biometric_device_schedule.<locals>.<lambda>  s     >vyy I r>   intervalseconds)<script>window.location.reload()</script>z,An error comes in biometric_device_schedule a  
                    <script>
                        Swal.fire({
                          title : "Schedule Attendance unsuccessful",
                          text: "Please double-check the accuracy of the provided IP Address and Port Number for correctness",
                          icon: "warning",
                          showConfirmButton: false,
                          timer: 3500,
                          timerProgressBar: true,
                          didClose: () => {
                            location.reload();
                            },
                        });
                    </script>
                    anvizc                  .    t         j                        S r.   )!anviz_biometric_device_attendancer   r;  s   r3   r<  z+biometric_device_schedule.<locals>.<lambda>0      =fiiH r>   c                  .    t         j                        S r.   )!cosec_biometric_device_attendancer   r;  s   r3   r<  z+biometric_device_schedule.<locals>.<lambda>B  rD  r>   r4  z$biometric/scheduler_device_form.htmlzutf-8z<script>$('#BiometricDeviceTestModal').removeClass('oh-modal--show');            $('#BiometricDeviceModal').toggleClass('oh-modal--show');</script>)!r(   rw   r   r1  r$   methodr5  is_validmachine_typerj   ra   zk_passwordr   r9   rv   
test_voiceis_schedulerrz   r   r   add_jobr=   r   r
   r   r   r   r   r   r   r   contentdecode)r*  r   initial_datar4  r.  rb   ra   rc   rY   r   duration	schedulerr   scriptexisting_threadr  r   s                   @r3   biometric_device_schedulerU    s7    %%))Y)7F(&*C*CDL1,GN(G ~~5gllC""$""d*.0$kkG!'!2!2J%11HD ""$ !!$X"'#(!I %,,.DOO!O,&||//0DEH-5599Y9GF08F-*.F'%*FNKKM 3 5I%%I" 01J1J K & 
 OO%'(STT& $$/"<<++,@A&*#,4)/1	!!H,V-F-FG " 
 !#$OPP"<<++,@A&*#!&,4)/1	"4"8"8"C"#((**6995!!H,V-F-FG " 
 !#$OPP$2 !'#I7S##G,PP
 	

 'A7KKs ! 0LL!OQVWF (//#0s   DM 	M="M82M=8M=c                     | j                   j                         }t        j                  j	                  |      }d|_        |j                          t        j                  | t        d             t        d|       S )aT  
    Handles unschedule of attendance capture for a biometric device.

    Parameters:
    - request (HttpRequest): The HTTP request object.
    - device_id (uuid): The ID of the biometric device for which unscheduling is being done.

    Returns:
    - HttpResponseRedirect: Redirects to the biometric devices view after unscheduling.
    r   Fz)Biometric device unscheduled successfully/biometric/search-devices?)r)  	urlencoder(   rw   r   rL  r   r	   success_r   )r*  r   previous_datar   s       r3   biometric_device_unscheduler\  S  si     KK))+M%%))Y)7FF
KKMWa KLM0@AAr>   zbiometric.add_biometricdevicesc                 r   t        | j                  j                               t        d      d }t	               }| j
                  dk(  r^t	        | j                        }|j                         r9|j                          t        j                  | t        d             t	               }||d}t        | d|      S )a  
    Handles the addition of a new biometric device.

    Parameters:
    - request (HttpRequest): The HTTP request object containing data about the request.

    Returns:
    - HttpResponse: Renders the 'add_biometric_device.html' template with the biometric device form.
    zpd=Nr5  z$Biometric device added successfully.)r%  pdz#biometric/add_biometric_device.html)r   r)  rX  rM   r#   rG  r5  rH  r   r	   rY  rZ  r   )r*  r[  r%  r.  s       r3   biometric_device_addr_  j  s     GKK1134SZ\BM(*N~~,W\\:""$!Wa(N&OP02N!/}EG'@'JJr>   c                 H   t         j                  j                  |      }t        |      }| j                  dk(  rVt        | j
                  |      }|j                         r/|j                          t        j                  | t        d             ||d}t        | d|      S )a  
    Handles the editing of an existing biometric device.

    Parameters:
    - request (HttpRequest): The HTTP request object containing data about the request.
    - device_id (uuid): The ID of the biometric device to be edited.

    Returns:
    - HttpResponse: Renders the 'edit_biometric_device.html' template with the biometric
                    device form pre-filled with existing data.
    r   )instancer5  z&Biometric device updated successfully.)r%  r   z$biometric/edit_biometric_device.html)r(   rw   r   r#   rG  r5  rH  r   r	   rY  rZ  r   )r*  r   r   r%  r.  s        r3   biometric_device_editrb    s      %%))Y)7F(&9N~~,W\\FK""$!Wa(P&QR(G 'A7KKr>   c                 b   | j                   j                         }t        j                  j	                  |      }|j
                   |_        |j                          |j
                  st        d      n
t        d      }t        j                  | t        d      d|iz         t        d|       S )z>
    This method is used to archive or un-archive devices
    r   archivedzun-archivedzDevice is %(message)sr  rW  )r)  rX  r(   rw   r   r#  r   rZ  r	   rY  r   )r*  r   r[  
device_objr  s        r3   biometric_device_archiverf    s     KK))+M!))---;J)333JOO#-#7#7a
mQ}=MGWa 78Iw;OOP0@AAr>   z!biometric.delete_biometricdevicesc                     t         j                  j                  |      }|j                          | j                  j                         }t        j                  | t        d             t        d|       S )aw  
    Handles the deletion of a biometric device.

    Parameters:
    - request (HttpRequest): The HTTP request object containing data about the request.
    - device_id (uuid): The ID of the biometric device to be deleted.

    Returns:
    - HttpResponseRedirect: Redirects to the 'search-devices' page after deleting the
                            biometric device.

    r   z&Biometric device deleted successfully.rW  )
r(   rw   r   deleter)  rX  r	   rY  rZ  r   )r*  r   r   r[  s       r3   biometric_device_deleteri    sa    " %%))Y)7F
MMOKK))+MWa HIJ0@AAr>   c                 "   | j                   j                         }| j                   j                  d      }| j                   j                  d      }|d}t        | j                         j                  j                  d      }|r|dk(  r|j                  d      }g }t        |      }t        t        |       d}| j                   j                  d	      d
k(  rd}t        || j                   j                  d            }t        | ||||d      S )zZ
    This method is used to search biometric device model and return matching objects
    searchr#   r$  unknownTr"  z%biometric/card_biometric_devices.htmlviewr   z%biometric/list_biometric_devices.htmlr   )r&  r^  filter_dict)r)  rX  r   r"   qsr(  rx   r   r   r(   rD   r   )r*  r[  rk  r#  r&  	data_dictr-  s          r3   search_devicesrr    s     KK))+M[[__X&F,I~#GKK033<<]KG	Y...4.0I'I&	26H{{v&(:GW[[__V%<=G$	
 r>   c                    t         j                  j                  |      }|j                  dk(  r|j                  }|j
                  }|j                  }d}t        ||dt        |      dd      }	 |j                         }|j                  d       t        |       d	}|r|j#                          tI        |      S |j                  dk(  rddd|j$                  dd|j&                  |j(                  dd}
ddddddd}	d}	 t+        j,                  |j.                  |
d      }|j0                  dk7  r	 |j3                         }||	k(  rnJ|d   }
|
d   }|
d   }||_        ||_        |j9                          t;        |      }|j=                         }d	}tI        |      S |j                  d k(  r~t?        |j
                  |j                  |j@                  |jB                  d!"      }|jE                         }|j                  d#      rtG        |       d	}tI        |      S d$}tI        |      S d%}tI        |      S # t        j                  $ r}	d
}Y d}	~	d}	~	wt        $ r#}	t        j!                  d|	       d}Y d}	~	d}	~	ww xY w# |r|j#                          w w xY w# t        $ r*}	t        j!                  d|	       Y d}	~	tI        |      S d}	~	ww xY w)&ab  
    Test the connection with the specified biometric device.

    Parameters:
    - request (HttpRequest): Django HttpRequest object.
    - device_id (uuid): ID of the biometric device to test.

    Returns:
    - HttpResponse: HTML response containing JavaScript code to display
                    a notification about the connection test result.
    r   r6  Nrh   Fri   r   r7  a  <script>
                    Swal.fire({
                      text: "Test connection successful.",
                      icon: "success",
                      showConfirmButton: false,
                      timer: 1500,
                      timerProgressBar: true,
                      didClose: () => {
                        location.reload();
                        },
                    });
                    </script>
                a(  
           <script>
                Swal.fire({
                  title : "Failed to connect: Authentication error.",
                  text: "Please double-check the accuracy of the provided IP Address, Port Number and Password for correctness",
                  icon: "warning",
                  showConfirmButton: false,
                  timer: 3500,
                  timerProgressBar: true,
                  didClose: () => {
                    location.reload();
                    },
                });
            </script>
            z(An error comes in biometric_device_test a  
           <script>
                Swal.fire({
                  title : "Connection unsuccessful",
                  text: "Please double-check the accuracy of the provided IP Address, Port Number and Password for correctness",
                  icon: "warning",
                  showConfirmButton: false,
                  timer: 3500,
                  timerProgressBar: true,
                  didClose: () => {
                    location.reload();
                    },
                });
            </script>
            rA  r   r   r   r   r   r  r  r  r   r  
AUTH_ERRORr  a  
           <script>
                Swal.fire({
                  title : "Connection unsuccessful",
                  text: "Please double-check the accuracy of the provided API Url , API Key and API Secret for correctness",
                  icon: "warning",
                  showConfirmButton: false,
                  timer: 3500,
                  timerProgressBar: true,
                  didClose: () => {
                    location.reload();
                    },
                });
            </script>
            r     r   r  z9Got an error in test connection of Anviz Biometric Devicer   r   r   appa  
           <script>
                Swal.fire({
                  title : "Connection unsuccessful",
                  text: "Please double-check the accuracy of the provided Machine IP , Username and Password for correctness",
                  icon: "warning",
                  showConfirmButton: false,
                  timer: 3500,
                  timerProgressBar: true,
                  didClose: () => {
                    location.reload();
                    },
                });
            </script>
            a  
           <script>
                Swal.fire({
                  title : "Connection unsuccessful",
                  text: "Please select a valid biometric device",
                  icon: "warning",
                  showConfirmButton: false,
                  timer: 3500,
                  timerProgressBar: true,
                  didClose: () => {
                    location.reload();
                    },
                });
            </script>
            )%r(   rw   r   rI  rj   ra   rJ  r   r9   rv   rK  find_employees_in_zkzk_exceptionZKErrorResponser   r   r   
disconnectr   r  r  r	  r
  r  status_coder  r   r  r   r   r   r!   r   r   basic_configfind_employees_in_cosecr
   )_requestr   r   rb   ra   rc   rY   r   rS  r   r   r  r  r   r  anviz_deviceattendance_recordsr   s                     r3   biometric_device_testr    s     %%))Y)7Fd"++&&
%%]
	5	"$$&DOO!O$ +F` !t s 
			' /% #448 $*>>ARARS	
 %-kB ,F
!	}}V^^'1MH##s*#==?Lu$&y1#G,	%i0#, %0":9E%1%H%H%J"V s 
			'KK!!!!
 %%'<<#I.F\ AF@ !  } ++ 	F   	LLCUKF	$ ! z  	LLKU t }	sU   1/H> BJ# >JIJ J%J=J JJ J #	K,KKc                 h   t        | j                  | j                  dt        | j                        dd      }|j                         }|j                          |j                         }|j                         }g }|D ]  }|j                  }|j                  }t        j                  j                  |      j                         }	|	sM|	j                  }
t         j                  j                  |
      j                         }|r||j"                  r|j"                  nd}|j$                  r|j$                  nd}|j&                  r|j&                  nd}||j(                  d<   ||j(                  d<   ||j(                  d	<   n-d|j(                  d<   d|j(                  d<   d|j(                  d	<   |
|j(                  d
<   |
j*                  |j(                  d<   g }|D ]-  }|j                  |k(  s|j-                  |j.                         / |sg }||j(                  d<   |j-                  |        |S )a  
    Fetch employee data from the specified ZK biometric device.

    Parameters:
    - device: Biometric device object containing machine IP, port, etc.

    Returns:
    - list: A list of dictionaries, where each dictionary represents an employee
            with associated data including user ID, employee ID, work email,
            phone number, job position, badge ID, and fingerprint data.
    r    Fri   rn   )r   N
work_emailphonejob_positionr   badge_idfinger)r   ra   rj   r9   rJ  rv   enable_device	get_usersget_templatesro   uidr)   rw   rx   ry   r   r   emailmobilejob_position_id__dict__r  appendfid)r   r   rY   rF   fingers	employeesrt   ro   r  r   r   employee_work_infor  r  r  finger_printr  s                    r3   zk_employees_fetchr    s    [[V''(I DNNE  "GI ##,,hh#++2272CIIK))H!8!@!@!G!G$ "H "eg  "0B0H0H&,,d  6H5N5N*11TX *99 '66 
 /9l+).g&0<n-.2l+)-g&04n-(0DMM*%(0(9(9DMM*%L! 4::$ ''

34  !&2DMM(#T"G##H r>   c                 &   g }t         j                  j                  |       }t        j                  j	                  |      }t        |j                  |j                  |j                  |j                        }|D ]  }|j                  |j                        }|j                  d      r|j                  |d<   |j                  |j                        }|j                  d      |d<   |j                  d      |d<   |j                  d      |d<   i }|j                         D ]  \  }	}
|	j                  d	d
      }|
||<    |j!                  |       t        j                  j                  |j"                        j%                           |S )ab  
    Fetch employee data from the COSEC biometric device associated with the specified device ID.

    Parameters:
    - device_id: ID of the biometric device.

    Returns:
    - list: A list of dictionaries, where each dictionary represents an employee with associated
            data including user ID, employee ID, finger count, and card count.
    r   r   rn   user-idr   zfinger-countz
face-countz
card-count-rZ  )r(   rw   r   r)   rx   r!   ra   rj   r   r   get_cosec_userro   r   get_user_credential_countitemsr   r  r   rh  )r   rF   r   r  r   r   rt   user_credentialnew_dictkeyvaluenew_keys               r3   cosec_employee_fetchr    su    E%%))Y)7F"**11F1CI6;;(=(=v?T?TE  D##H,<,<#=88I"*"6"6D#==hFVFV=WO#2#6#6~#FD !0!4!4\!BD!0!4!4\!BDH"jjl *
U++c3/$)!* LL"&&**hkk*:AACD Lr>   c           	         t         j                  j                  |       }t        j                  j	                  d      j                  dd      }t        |j                  |j                  |j                  |j                        }t        j                  j	                  |      j                  dd      }g }|D ]  \  }}|s	|j                         st        |      d	k  s)|j                  |
      }|j                  d      sM|j                  d      |vsa|j                  t        |j                  d      |j                  d      ||               t        j                  j!                  |       y)~  
    Synchronize active employees with a COSEC biometric device.

    This function retrieves a list of active employees from the database,
    checks their presence on a specified COSEC biometric device, and updates
    the database with employees who are registered on the COSEC device.

    Args:
        device_id (uuid): The ID of the biometric device to synchronize with.
    r   Tr"  r   r  r   ro   flat   rn   r  ref-user-id)r   ro   employee_id_iddevice_id_idN)r(   rw   r   r   rx   values_listr!   ra   rj   r   r   r)   isalnumrM   r  r  bulk_create)	r   r   r  r   existing_user_idsbiometric_employees_to_creater   r  rt   s	            r3   r}  r}  "  sN    %%))Y)7F  ''$'7CCD*UI6;;(=(=v?T?TE +2299F9KWW X  %'!!* X((*s8}/B'''9Dxx	"txx	':BS'S-44&$(HH]$; $ 3'2%.		 **+HIr>   c           
         t         j                  j                  |       }t        j                  j	                  d      j                  dd      }t        t        j                  j	                  |       j                  dd            }t        |j                  |j                  t        |j                        d	
      }|j                         }|j                         D ci c]  }|j                  |j                    }}|D 	cg c]?  \  }}	|	r8|	j#                         r(t%        |	      dk  r|	|v r|	|vrt        ||	   |	||       A }
}}	t        j                  j'                  |
       |j)                          yc c}w c c}	}w )r  r   Tr"  r   r  r   ro   r  rh   )rj   rc   rk   	   )r  ro   r  r  N)r(   rw   r   r   rx   r  r   r)   r   ra   rj   r9   rJ  rv   r  ro   r  r  rM   r  rz  )r   r   r  r  r   rY   rt   zk_usersr   r  r  s              r3   rw  rw  E  sq    %%))Y)7F  ''$'7CCD*UI""))I)>JJD 	K 	

 c&:L:L6MWXI D37>>3CD4dhh&DHD &/% "KMQ -- 	"&"		
%! % **+HIOO! E%s   #E?AFz!biometric.view_biometricemployeesc           	      0   | j                   j                         }t        j                  |      }|r	 |j                  dk(  rNt               }t        |      }t        || j                   j                  d            }||||d}t        | d|      S |j                  dk(  rbt               }t        |      }t        |t        | j                   j                  dd                  }||j                  ||d}t        | d|      S 	 t+        t,              S t%        j"                  | t)        d             t+        t,              S # t        $ rM}t         j#                  d|       t%        j&                  | t)        d	             Y d
}~t+        t,              S d
}~ww xY w)aA  
    View function to display employees associated with a biometric device.

    Depending on the machine type of the biometric device (either "zk" or "cosec"),
    this function fetches the relevant employees and renders the appropriate template.

    Args:
        request (HttpRequest): The HTTP request object.
        device_id (uuid): The ID of the biometric device.
        **kwargs: Additional keyword arguments.

    Returns:
        HttpResponse: The rendered template response or a redirect to `biometric_devices_view`
                      in case of an error.
    r6  r   )r  r   formr^  z'biometric/view_employees_biometric.htmlr   r    z#biometric/view_cosec_employees.htmlAn error occurred: zFailed to establish a connection. Please verify the accuracy of the IP                    Address , Port No. and Password of the device.NBiometric device not found)r)  rX  r(   findrI  r'   r  rD   r   r   r%   r  rU   r9   r   r   r   r   r	   inforZ  r   r/  )	r*  r   kwargsr[  r   employee_add_formr  r.  r   s	            r3   biometric_device_employeesr  n  s   & KK))+M""9-F#	""d*$<$>!.v6	))W[[__V5LM	!*!*-'	 F  ""g-$4$6!0;	3s7;;??61#=>	 "+!'-'	 g'LgVV .0 *++ 	w"> ?@*++  	LL.6MMD  *++	s   AD? A0D? ?	F5FFc           	         | j                   j                         }| j                   j                  d      }t        j                  j                  |      }| j                   j                  d      }|j
                  dk(  rt        |      }|rQt        j                  j                  |      }|j                  dd      }|D cg c]  }|j                  |v s| }}t        || j                   j                  d	            }d
}	|||d}
nt        |      }|r"t        j                  j                  ||      }n t        j                  j                  |      }|D cg c]  }|j                   }}|D cg c]  }|d   |v r| }}t        |t        | j                   j                  d	d                  }d}	|||d}
t!        | |	|
      S c c}w c c}w c c}w )a  
    View function to search for employees associated with a specific biometric device.

    This function handles searching employees based on their first name and the type of
    biometric device (either "zk" or "cosec"). It then renders the appropriate template
    with the filtered employee list.

    Args:
        request (HttpRequest): The HTTP request object.

    Returns:
        HttpResponse: The rendered template response with the context.
    r   r   rk  r6  )+employee_id__employee_first_name__icontainsr  Tr  r   z'biometric/list_employees_biometric.html)r  r   r^  )r  r   r   ro   r    z-biometric/list_employees_cosec_biometric.html)r)  rX  r   r(   rw   rI  r  r)   rx   r  r  rD   r  ro   rU   r9   r   )r*  r[  r   r   rk  r  search_employeessearch_uidsr   r-  r.  queryset_user_idsfiltered_employeess                r3   search_employee_devicer    s   $ KK))+M)I%%))Y)7F[[__X&Fd"&v.	199@@<B  A   +66u46HK)2%hllk6QI  ")W[[__V-DE	<""
 )3	199@@<Bf  A    299@@6@R>NO(X--OO &
	"&77 
 

 5GKKOOFA$> ?
 C+"

 '8W--C$ P
s   GGG8Gz#biometric.delete_biometricemployeesc                    t         j                  j                  |      }t        |j                  |j
                  dt        |j                        dd      }|j                         }|j                  |       t        j                  j                  |      j                         }|j                          t        j                  | t!        d      j#                  |j$                               d| d}t'        |      S )	a-  
    This function connects to the specified biometric device, deletes the user
    identified by the given UID, and removes the corresponding entry from the
    BiometricEmployees table in the local database

    Args:
        request (HttpRequest): The HTTP request object.
        uid (str): The UID of the user to be deleted from the biometric device.
        device_id (uuid): The ID of the biometric device.

    Returns:
        HttpResponse: A redirect response to the list of employees for the specified
                      biometric device.
    r   rh   Fri   )r  2{} successfully removed from the biometric device.&/biometric/biometric-device-employees//)r(   rw   r   r   ra   rj   r9   rJ  rv   delete_userr)   rx   ry   rh  r	   rY  rZ  formatr   r   )r*  r  r   r   r   rY   employee_bioredirect_urls           r3   delete_biometric_userr    s    $ %%))Y)7F[[V''(I D%--444=CCEL	
>?FF$$	
 <I;aHLL!!r>   z#biometric.change_biometricemployeesc                    t        j                  |      }|rt        |j                  |j                  |j
                  |j                        }|j                  |d      }|j                  d      }|dk(  r t        j                  | t        d             n?t        j                  | t        d             nt        j                  | t        d             t        d| d	      S )
a  
    View function to enable face recognition for a user on a COSEC biometric device

    Args:
        request (HttpRequest): The HTTP request object.
        user_id (str): The ID of the user for whom face recognition is to be enabled.
        device_id (uuid): The ID of the COSEC biometric device.

    Returns:
        HttpResponse: A redirect response to the list of employees for the specified
                      biometric device.
    T)ro   	enable_frResponse-Coder   z%Face recognition enabled successfullyz'Something went wrong when enabling facezDevice not foundr  r  )r(   r  r!   ra   rj   r   r   enable_user_face_recognitionr   r	   rY  rZ  r   r   )r*  ro   r   r   r   r  response_codes          r3   enable_cosec_face_recognitionr    s      ""9-FKK!!!!	
 66wRV6W	!o6CWa(O&PQNN7A&O$PQw"4 56<YKqIJJr>   c                    t         j                  j                  |      }t        |j                  |j
                  |j                  |j                        }|j                  |      }|j                  d      rt        |d         }t        |d         }t        |d         }t        |||      }	|	j                  d      }
|d   t        t        |d               t        t        |d               t        t        |d	               |
d
}d|v rt        t        |d               |d<   t        |      }| j                  dk(  rt        | j                        }|j!                         r|j"                  d   }|j"                  d   }|j"                  d   }|j"                  d   }t%        |j"                  d         }t        j&                  |d      j)                         }|j*                  }|j,                  }|j.                  }|j"                  d   }|j1                  |d   |d   |t        |      t        |      t        |      t        |      |||
      }|j                  d      r>|j                  d      dk(  r*t3        j4                  | t7        d             t9        d      S |j                  d      r0|j                  d      }d|v r|j;                  dt7        d             t=        | d|||d      S y)a  
    View function to edit the details of a COSEC biometric user.

    Args:
        request (HttpRequest): The HTTP request object.
        user_id (str): The ID of the user to be edited.
        device_id (uuid): The ID of the COSEC biometric device.

    Returns:
        HttpResponse: The rendered form template for GET requests, and a response with
                      a success message for valid POST requests. Reloads the page after
                      successful update.

    r   r  zvalidity-date-yyyyzvalidity-date-mmzvalidity-date-ddz%Y-%m-%dzuser-activevipzvalidity-enable)r  user_activer  validity_enablevalidity_end_datezby-pass-fingerby_pass_fingerr2  r5  r  r  r  r  r  )
ro   r   r  r  r  r  r  validity_date_ddvalidity_date_mmvalidity_date_yyyyr  r   z(Biometric user data updated successfullyr@  r   NziThis date cannot be used as the Validity End Date for                                the COSEC Biometric.zbiometric/edit_cosec_user.html)r  ro   r   r.  )r(   rw   r   r!   ra   rj   r   r   r  r9   r   strftimeboolr&   rG  r5  rH  cleaned_datar  r   ru   yearmonthdayset_cosec_userr	   rY  rZ  r
   	add_errorr   )r*  ro   r   r   r   rt   r  r  r  date_objectformatted_daterP  r  r  r  r  r  validity_end_date_strr  validity_yearvalidity_monthvalidity_dayr  update_userr   s                            r3   edit_cosec_userr  :  s   & %%))Y)7F	E (Dxx4,-.D+,-$)*+tUC0$--j9LD$7 89DK()#C->(?$@A!/
 t#-1#d;K6L2M-NL)*\2>>V# .D}}((0"//>''."&"3"34E"F(+D,=,=>Q,R(S%$,$5$5):%$& " !2 6 6!2!8!8044!%!2!23C!D#22 O $] 3 #K 0C#&~#6$'$8%1%3'4 3   OOO4#8C?$$#M!N ((STT??7+'OOG4E+u4 !6 ,!gIN
 	
A r>   c                    t        j                  |      }|rt        j                  j	                  ||      j                         }t        |j                  |j                  |j                  |j                        }|j                  |      }|j                  d      r]|j                  d      dk(  rI|j                          t        j                  | t!        d      j#                  |j$                               n?t        j&                  | t!        d             nt        j&                  | t!        d             |rd| dnd	}t)        |      S )
a  
    View function to delete a user from a COSEC biometric device and database.

    Args:
        request (HttpRequest): The HTTP request object.
        user_id (str): The ID of the user to be deleted from the COSEC biometric device.
        device_id (uuid): The ID of the COSEC biometric device.

    Returns:
        HttpResponse: A redirect response to the list of employees for the specified
                      biometric device.
    ro   r   r  r   r  zBiometric user not foundr  r  r  z"/biometric/view-biometric-devices/)r(   r  r)   rw   rx   ry   r!   ra   rj   r   r   delete_cosec_userr   rh  r	   rY  rZ  r  r   r   r   )r*  ro   r   r   r  r   r  r  s           r3   delete_horilla_cosec_userr    s)     ""9-F)1188v 9 

%' 	 KK!!!!	
 **73<<(X\\/-Jc-Q!FGNN ,, NN7A&@$ABw"> ?@  11=1 
 L!!r>   c                    d}| j                   d   }| j                   d   }t        j                  |      }t        j                  j                  |      }	 t        |j                  |j                  dt        |j                        dd      }|j                         }|D ]  }t        |      }|j                  |       t        j                  j                  |      j                         }|j!                          |j#                          t%        j&                  | t)        d	      j+                  |j,                                	 t5        ddi      S # t.        $ r }	t0        j3                  d
|	       Y d}	~	1d}	~	ww xY w)a  
    View function to delete multiple users from a ZK biometric device and the local database.

    Args:
        request (HttpRequest): The HTTP request object.

    Returns:
        JsonResponse: A JSON response indicating the success of the bulk delete operation.

    NidsdeviceIdr   rh   Fri   rn   r  r  r	   Success)r5  r  loadsr(   rw   r   r   ra   rj   r9   rJ  rv   r  r)   rx   ry   rh  refresh_datar	   rY  rZ  r  r   r   r   r   r   )
r*  rY   json_idsr   r  r   r   ro   r  r   s
             r3   bio_users_bulk_deleter    sY    D||E"HZ(I
**X
C%%))Y)7F3++,
	   " 	G'lGW--55<<W<MSSUL!FGNN ,,	 Y/00  3*E223s   C2E 	F  E;;F c                    | j                   d   }| j                   d   }t        j                  |      }t        j                  j                  |      }	 t        |j                  |j                  |j                  |j                        }|D ]  }|j                  |       t        j                  j                  ||      j                         }|r|j                          t!        j"                  | |j$                   dt'        d      z           	 t/        d
di      S # t(        $ r }t*        j-                  d|       Y d	}~1d	}~ww xY w)a  
    View function to delete multiple users from a COSEC biometric device and database.

    Args:
        request (HttpRequest): The HTTP request object.

    Returns:
        JsonResponse: A JSON response indicating the success of the bulk delete operation.
    r  r  r   rn   r   z/successfully removed from the biometric device.r  Nr	   r  )r5  r  r  r(   rw   r   r!   ra   rj   r   r   r  r)   rx   ry   rh  r	   rY  r   rZ  r   r   r   r   )	r*  r  r   r  r   r   ro   r  r   s	            r3   cosec_users_bulk_deleter    s<    ||E"HZ(I
**X
C%%))Y)7F3KK!!!!	
  	G##G#4-55<<6 = eg  ##%++,A.EFG	 Y/00  3*E223s   B?D" "	E+EEz biometric.add_biometricemployeesc                 ,	   t         j                  j                  |      }|j                  dk(  r
t	               n	t               }| j                  dk(  rt         j                  j                  |      }	 |j                  dk(  r$t        |j                  |j                  dt        |j                        dd      }|j                         }|j                          |j                         D cg c]  }|j                   }}|j                         D cg c]  }|j                    }}d}	d}
| j"                  j%                  d	      }|D ]W  }t&        j                  j                  |      }t(        j                  j+                  ||
      j-                         }||	|v s|
|v rt        |
      }
|	dz  }	|
dz  }
|	|v r|
|v r|j/                  |	       |j/                  |
       |j1                         }|j3                  |	|ddt5        |
      d       t(        j                  j7                  |	t5        |
      ||       t9        j:                  | t=        d      j?                  |             *t9        j@                  | t=        d      j?                  |             Z nitC        |j                  |j                  |jD                  |jF                        }|jI                         }|j                  d      r| j"                  j%                  d	      }t(        j                  j+                  |      }tK        |jM                  dd            }|D ]  }t&        j                  j                  |      }|j1                         }|jN                  }
d}||v r
|dz  }||v r
|j/                  |       |jQ                  |
||ddddd      }|j                  d      }|s|dk(  st(        j                  j7                  ||
||        t[        d      S t]        | d||d !      S c c}w c c}w # tR        $ rR}|j                  dk(  r/jU                          tV        jY                  dt5        |             Y d}~t[        d      S d}~ww xY w)"a  
    View function to add a new user to a biometric device.

    This function adds a new user to the specified biometric device and stores their
    information in the database.

    Args:
        request (HttpRequest): The HTTP request object.
        device_id (uuid): The ID of the biometric device.

    Returns:
        HttpResponse: A JavaScript script to reload the current page after adding the user.

    r   r6  r5  rh   Fri   r    i  employee_ids)r   r   Nrl  r   )r  r  rc   group_idro   card)r  ro   r   r   z){} added to biometric device successfullyz${} already added to biometric devicerv  r   r   Tr  d   i  )ro   r   r  r  r  r  r  r  r  r   )r   ro   r   r   r  r@  z!biometric/add_biometric_user.html)r  r   r  )/r(   rw   r   rI  r'   r%   rG  r   ra   rj   r9   rJ  rv   r  r  r  ro   r5  getlistr   r)   rx   ry   r  get_full_nameset_userr  creater	   rY  rZ  r  r  r!   r   r   r|  r   r  r  r  r   disable_devicer   r   r
   r   )r*  r   r   r  r   rY   rt   existing_uidsr  r  ro   r  obj_idr   existing_biometric_employeeemployee_namer   basiccosec_usersexisting_ref_user_idsr   r  r   s                          r3   add_biometric_userr  $  s   & %%))Y)7F $& 	!" 
 ~~!))---;d	@""d*%% !3!34#$	 !((*""$6:nn6F Gd G G>Bnn>N$OdT\\$O!$O&||33NC* 'F'//33v3>H2D2L2L2S2S$, 3T 3eg 0 3:!]2gAR6R&)'lG1HC#qLG "]2gAR6R &,,S1)009(0(>(>(@ #!.%'%'$'L!" &  +2299 #$'L(0&,	 :  !((#IJQQ ( !#DELLXVI'R '%%KK))))	 **,99U##*<<#7#7#GL"4"<"<"C"Ci"C"XK,0#//D/I-) #/ #+#3#3#7#76#7#B(0(>(>(@"*"3"3&))-BB'1,K *-BB-44[A$33$+(3!.(,,0-.-./3  4 	  $(88O#<#C.66==,7(/,4*0	 > )< GHH+*C u !H$Oh  	@""d*##%2CJ?GHH		@sW   5A:P8 /P.P8 P3)BP8 P8 G P8 )=P8 'P8 -%P8 .
P8 8	R>RRc                    | j                   j                  d      }| j                   j                  d      }t        j                  j                  |      }|dk(  }|r|j                  }|j
                  }t        |j                        }d}	 |j                  dk(  rzt        ||dt        |      dd	      }|j                         }t        |||      }	|j                  d
       |rd|_        d|_        |j                          |	j!                          n|j                  dk(  rt#        |j
                  |j                  |j$                  |j&                  d      }
|
j)                         }|j                  d      rWd|_        d|_        |j                          t+        |j,                        }|j!                          |t.        |j,                  <   nt0        	 d}|r|j7                          t;        |      S d|_        |j                          |j                  dk(  rBt/        j                  |j,                        }|r!|j9                          t.        |j,                  = d}t;        |      S # t0        $ r9}d|_        |j                          t2        j5                  d|       d}Y d}~d}~ww xY w# |r|j7                          w w xY w)z
    Activate or deactivate live capture mode for a biometric device based on the request parameters.

    :param request: The Django request object.
    :return: A JsonResponse containing a script to be executed on the client side.
    rz   r  r   onNr6  rh   Fri      r7  Tr   r   r   rv  a=  <script>
                    Swal.fire({
                      text: "The live capture mode has been activated successfully.",
                      icon: "success",
                      showConfirmButton: false,
                      timer: 1500,
                      timerProgressBar: true, // Show a progress bar as the timer counts down
                      didClose: () => {
                        location.reload(); // Reload the page after the SweetAlert is closed
                        },
                    });
                    </script>
                z'An error comes in biometric_device_livea  
           <script>
                Swal.fire({
                  title : "Connection unsuccessful",
                  text: "Please double-check the accuracy of the provided IP Address and Port Number for correctness",
                  icon: "warning",
                  showConfirmButton: false,
                  timer: 3000,
                  timerProgressBar: true,
                  didClose: () => {
                    location.reload();
                    },
                });
            </script>
            a  
           <script>
                Swal.fire({
                  text: "The live capture mode has been deactivated successfully.",
                  icon: "warning",
                  showConfirmButton: false,
                  timer: 3000,
                  timerProgressBar: true,
                  didClose: () => {
                    location.reload();
                    },
                });
            </script>
            )r)  r   r(   rw   rj   ra   r9   rJ  rI  r   rv   r]   rK  rz   rL  r   r   r!   r   r   r|  r   r   r   TimeoutErrorr   r   rz  r   r
   )r*  rz   r   r   rb   ra   rc   rY   r   ra  r   r  threadrS  r   rT  s                   r3   biometric_device_liver    sp    kkooi(G
+I%%))Y)7FoG++&&
v))*I	"""d*  ]#$	 !((**:wIb)%)FN*/F'KKMNN$$$/&%%KK)))) !--/<<&%)FN*/F'KKM5fii@FLLN4:&vyy1&&FB !0 - ')044VYY?O$$&&vyy1 [  	"FNKKMLLBEJF		( ! s+   EI2 2	J4;/J/*J7 /J44J7 7Kc                    t         j                  j                  |       }|j                  r|j                  }|j
                  }d}t        ||dt        |j                        dd      }	 |j                         }|j                          |j                         }|d   j                  }|j                  rj|j                  r^|D cg c]R  }|j                  j                         |j                  k\  r)|j                  j!                         |j                  kD  r|T }	}n|}	|j                         |_        |j!                         |_        |j#                          |	D ]  }|j$                  }
|j&                  }t)        j*                  |j                        }|j                         }|j!                         }t,        j                  j/                  |
      j1                         }|st3        |j4                  j6                  |||      }|d	v r	 t9        |       	 tA        |        	 |r|jC                          yyyc c}w # t:        $ r!}t<        j?                  d
|       Y d}~d}~ww xY w# t:        $ r!}t<        j?                  d
|       Y d}~:d}~ww xY w# t:        $ r }t<        j?                  d|       Y d}~d}~ww xY w# |r|jC                          w w xY w)z
    Retrieve attendance records from a ZK biometric device and update the clock-in/clock-out status.

    :param device_id: The ID of the ZK biometric device.
    r   Nrh   Fri   r   rn   rs   rp   zGot an error : zProcess terminate : )"r(   rw   r   rL  rj   ra   r   r9   rJ  rv   r  get_attendancer   r   r   ru   r;   r   ro   r}   r~   r   r)   rx   ry   r   r   r   r   r   r   r   r   rz  )r   r   rb   ra   rY   r   r   last_attendance_datetimer   filtered_attendancesro   r   r   ru   r;   r   r   r   s                     r3   r:  r:  %  s    %%))Y)7F++&&
++,
	-	"$$&D --/K'22'@'@$%%&*@*@ '2("!++002f6L6LL",,113f6L6LL ($ ( (3$%=%B%B%DF"%=%B%B%DF"KKM2 C
$,,'--
+66z7K7KL	 ~~' ~~'+33::7:KQQS#*#//@@!!!*	$L "Y.C$\2C%l3+C6 ! q $(8  ) C"LL):EBBC
  ) C"LL):EBBC 	8LL/77	8 ! s   -AJ" AICJ" +'J" IJ"  I5+J" -K J" 	I2I-'J" -I22J" 5	J>JJ" JJ" "	K+KK KK K#c                    t         j                  j                  |       }|j                  rt	        |       }|j                         }|d   d   D ]  }|d   d   }|d   }t        j                  |d   d      }|j                  t        j                               }t        j                  j                  |	      j                         }	|	s}t        |	j                  |j!                         |j#                         |
      }
|dv r	 t%        |
       	 t-        |
        yy# t&        $ r }t(        j+                  d|       Y d}~d}~ww xY w# t&        $ r!}t(        j+                  d|       Y d}~$d}~ww xY w)z
    Retrieves attendance records from an Anviz biometric device and processes them.

    :param device_id: The Object Id of the Anviz biometric device.
    r   r   r   r   workno	checktype	checktimez%Y-%m-%dT%H:%M:%S%z)r  rs   >   r      zError in clock in NzError in clock out )r(   rw   r   rL  r   r   r   r   
astimezoner~   get_current_timezoner   rx   ry   r   r   ru   r;   r   r   r   r   r   )r   r   r  r  r   r  r   date_time_utcdate_time_objr   r   r   s               r3   rC  rC  h  sw    %%))Y)7F29=)@@B,Y7? 	CJ!*-h7H#K0J$--;')>M *44446M  ''...AGGIH&!22&++-&++-*	  )B .C!,/3	C . % B%95AAB % C%:EBBCs0   D#E#	E,EE	E9E44E9c           	         t         j                  j                  |       }|j                  syt        j                  j                  |      j                         }|rt        |j                        nd}|rt        |j                        nd}t        |j                  |j                  |j                  |j                  d      }|j                  |t        |      dz         }t!        |t"              sy|D ]  }|d   }t$        j                  j                  |	      j                         }	|	s9|d
   }
|d   }t'        j(                  |
d      j+                         }t'        j(                  |d      j-                         }t'        j.                  ||      }|d   }t1        |	j2                  j4                  ||t7        j8                  |            }	 |dv rt;        |       n|dv rt=        |       n	  |r0|d   }t        j                  jE                  ||d   |d   d       yy# t>        $ r!}t@        jC                  d|       Y d}~Xd}~ww xY w)a?  
    Retrieve and process attendance events from a COSEC biometric device.

    This function fetches attendance events from the specified COSEC biometric device
    and processes them to record clock-in and clock-out events for employees.

    Args:
        device_id (uuid): The ID of the COSEC biometric device.
    r   Nr   r   r    r   r   r   r   ru   r;   r   r   r   rs   r   r   r   r   r   r   r   r   )#r(   rw   r   rL  r*   rx   ry   r9   r   r   r!   ra   rj   r   r   r   r   r   r)   r   r   ru   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   s                      r3   rF  rF    sK    %%))Y)7F*2299F9KQQSK6AK112q  GRC A ABWXE --!3'<#=#AK k4(! A
 ,%--444MSSUf%f%"++HjAFFH"++HjAFFH&..P
+
%%66  $//0CD	
	A;;&99,'5A< %b/ ((99-<=N-O)8)B 	: 	
   	ALL8%@@	As   !H**	I3IIF)rz   T)rL  rA  c                  4    t        t        j                        S r.   )rC  r   r   r/   r>   r3   r<  r<         A&)) L r>   r=  r>  r6  c                  4    t        t        j                        S r.   )r:  r   r   r/   r>   r3   r<  r<    s     >vyy I r>   r   c                  4    t        t        j                        S r.   )rF  r   r   r/   r>   r3   r<  r<    r"  r>   )   )rr   r  loggingr   	threadingr   r   urllib.parser   r   r	  !apscheduler.schedulers.backgroundr   django.contribr	   django.httpr
   r   django.shortcutsr   r   django.utilsr   r~   django.utils.translationr   __r   rZ  r6  r   r   rx  attendance.methods.utilsr   attendance.views.clock_in_outr   r   base.methodsr   r   employee.modelsr   r   horilla.decoratorsr   r   r   r   horilla.filtersr   horilla.horilla_settingsr   r   r!   filtersr"   formsr#   r$   r%   r&   r'   modelsr(   r)   r*   	getLoggerr   r   r=   rD   rU   r[   r]   r   r   r/  rU  r\  r_  rb  rf  ri  rr  r  r  r  r}  rw  r  r  r  r  r  r  r  r  r  r  r:  rC  rF  rw   allupdater&  rx   r   r1  rI  rR  rM  r   r/   r>   r3   <module>r=     s      # *  A # 2 - 4 2 6  ( , = : =  - 7 ! *  S R			8	$F2a*f a*Hkv k\w wt 67. 8  .D 89lL :  lL^ 89B :   B& 56K 7   K, 89L :   L4 89
B :   
B 89B :   B( 67 8   > 56J  7   J Z=@ F JF&R 899, :  9,x 89:. :   :.z :;#" <  #"L :;K <  K@ :;[
 <   [
| :;*" <  *"Z :;(1 <  (1V :;$1 <  $1N 78A 9   AH 89r  :   r j@"F%CPH
V 	&&**,33E3BG"**11t1D  9 9:Q>&&'1 3 5I%%L" 01J1J K & 
 OO%((D0 3 5I%%I" 01J1J K & 
 OO%((G3 3 5I%%L" 01J1J K & 
 OO%9:	s   AQ Q 0C(Q Q