o
    Bhw                     @   s  d dl mZmZ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mZmZ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$m%Z%m&Z&m'Z'm(Z(m)Z) edd Z*edd Z+eedd Z,dd Z-d dl.Z.e./e0Z1edd Z2edd Z3edd Z4ed d! Z5ed"d# Z6ed$d% Z7ed&d' Z8ed(d) Z9dS )*    )renderredirectget_object_or_404)login_required)messages)timezone)HttpResponseForbiddenJsonResponse)reverse)QSumFCountAvg)ValidationError)datetime)Decimal)Employee)require_POST   )OvertimeRequestOvertimeRequestHistory)OvertimeRequestForm)notify_overtime_submissionnotify_overtime_hr_approvalnotify_overtime_hr_rejection"notify_overtime_registrar_approval#notify_overtime_registrar_rejection!notify_overtime_payment_processedc                 C   s   | j jjdkrt| d tdS tjjddd	dd
d	}tjjdddd
jtdtdd}| |tdd pAdtdd |D |jtdtd dd pXdd}d||d}t| d|S )z;View for finance to see processed overtime payments historyFIN/You do not have permission to access this page.home	PROCESSEDPAIDstatuspayment_statusemployee__userfinance_processed_by__userz-finance_processed_atemployeeidamount)total_requeststotal_amountamount__sumr   c                 s       | ]}|j V  qd S Ntotal_hours.0request r6   %/var/www/html/wtlms/overtime/views.py	<genexpr>4       z#overtime_history.<locals>.<genexpr>)r   r   )total_paymentsr-   r2   
avg_amountzOvertime Payment History)titleprocessed_requestsstatszovertime/overtime_history.html)userr)   roler   errorr   r   objectsfilterselect_relatedorder_byvaluesannotater   r   count	aggregatesumr   )r5   r=   employee_statsr>   contextr6   r6   r7   overtime_history   s>   	
rM   c                 C   s  | j jjdkrt| d tdS | jd}t| jdt	
 j}t| jdt	
 j}tjjddd	d
}|j||d}|rltt|d}|j|d}|jtddd pZd}d|j   |||||dd}	n_i }
|D ]C}|j}|j|
vr|dtdtdd|
|j< |
|j d  d7  < |
|j d  tt|j7  < |
|j d  |jptd7  < qp|jtddd pd}d|
 |||dd}	t| d|	S )z-View for finance to process overtime paymentsr   r    r!   employee_idmonthyearREG_APPROVEDPENDINGr$   r'   )date__month
date__yearr*   )rN   r+   )totalrV   r   zOvertime Details for T)r<   r)   overtime_requestsr-   selected_monthselected_yearshow_employee_detailsz0.00)r)   request_countr2   r-   r[   r   r2   r-   zApproved Overtime ReportsF)r<   employees_with_overtimer-   rX   rY   rZ   zovertime/finance_overtime.html)r?   r)   r@   r   rA   r   GETgetintr   nowrO   rP   r   rB   rC   rD   r   r   rI   r   get_full_namer*   r   strr2   r+   rF   r   )r5   rN   rO   rP   
base_queryfiltered_requestsr)   rW   employee_totalrL   r\   overtime_reqr-   r6   r6   r7   finance_overtime?   sz   
 "	rg   c              
   C   s  | j jjdkrtdddS | jd}| jd}| jd}z:tjj|d}d	|_d
|_	||_
| j j|_t |_||_|  t|| d tjj|d|| j jd tddiW S  tjyk   tddd Y S  ty } ztdt|dW  Y d}~S d}~ww )zProcess overtime paymentr   FPermission deniedsuccessmessage
request_idpayment_datecommentrU   r"   r#   r5   PAYMENT_PROCESSEDr5   r%   rn   actorrj   TzRequest not foundN)r?   r)   r@   r	   POSTr^   r   rB   r%   r&   rm   finance_processed_byr   r`   finance_processed_atfinance_commentsaver   r   createDoesNotExist	Exceptionrb   )r5   rl   rm   rn   overtime_requester6   r6   r7   process_payment   s8   

r}   c              
   C   s8  | j jjdkrtdddS | jd}| jd}| jd}|s)tdddS zWd	}|D ]F}z:tjj|d
}|j	dkr?W q.d|_
d|_	||_| j j|_t |_||_|  tjj|d|| j jd |d7 }W q. tjyt   Y q.w tdd| ddW S  ty } ztdt|dW  Y d}~S d}~ww )z*Process multiple overtime payments at oncer   Frh   ri   zrequest_ids[]rm   rn   zNo requests selectedr   rU   r#   r"   rp   rq   r   TzSuccessfully processed z payment(s)N)r?   r)   r@   r	   rs   getlistr^   r   rB   r&   r%   rm   rt   r   r`   ru   rv   rw   r   rx   ry   rz   rb   )r5   request_idsrm   rn   processed_countrl   r{   r|   r6   r6   r7   process_bulk_payments   sN   




r   Nc              
   C   sD  t d| j d| jddk  | jjjdkr3| jddkr)tddidd	S t	
| d td
S | jdkrt| j| j| jjd}d|jv rw|jd rwzt|jd d }t  }||krj|dd W n ttfyv   Y nw t d|j  t d|   | st 
d|j  t 
d|   | rz|jd }|jd }|jd }tjj| jj|||d }|rd}| jddkrtd|ddd	W S |d| t | dd|iW S |j!dd}	| jj|	_| jjjdkrd |	_"| jj|	_#t |	_$d!|	_%|	j& d"k}
t d#|	j d$|
  |	'  |	!  t d%|	j(  t)|	| d& | jddkrXd'd(t*d)|	j(gd*d+}t d,|  t|W S t	+| d( td
W S  t,y } zEt-|}t.|j/d-dgd. t-r|j/d- d. }t 
d/|  | jddkrtd|ddd	W  Y d}~S |d| W Y d}~nd}~ww | jddkri }|j0 D ]\}}d0d1 |D ||< qd|v rt1d2d3 |d D rd4g|d-< nd|v rt1d5d3 |d D rd6g|d-< t d7|  td|d8dd	S nt| jjd}t | dd|iS )9z/Handle overtime request creation for employees.z#Overtime request received. Method: z, Is AJAX: zX-Requested-WithXMLHttpRequestREGrA   z*Registrar cannot submit overtime requests.i  r%   r!   rs   r)   datez%Y-%m-%dz(Cannot request overtime for future dateszForm data received: zForm is valid: zForm errors: zForm non-field errors: 
start_timeend_time)r)   r   r   r   z@An overtime request for this date and time range already exists.F)rj   rA   i  Novertime/request_form.htmlformcommitHRHR_APPROVEDzAuto-approved (HR request)   zRequest date: z, Is weekend: z Overtime request saved with ID: ro   Tz(Overtime request submitted successfully.overtime:view_request)args)rj   rk   view_urlzSending success response: __all__r   zValidation error: c                 S   s   g | ]}t |qS r6   )rb   )r4   rA   r6   r6   r7   
<listcomp>U  s    z$request_overtime.<locals>.<listcomp>c                 s       | ]}d |v V  qdS )zcurrent month or previous monthNr6   r4   errr6   r6   r7   r8   X      z#request_overtime.<locals>.<genexpr>zPlease select a date within the current month or previous month. Overtime cannot be requested for dates older than the previous month.c                 s   r   )futureNr6   r   r6   r6   r7   r8   Z  r   zPPlease select a date up to today. Overtime cannot be requested for future dates.zSending validation errors: )rj   errors)2loggerinfomethodheadersr^   r?   r)   r@   r	   r   rA   r   r   rs   FILESdatar   strptimer   r   r`   	add_error
ValueError	TypeErroris_validr   non_field_errorscleaned_datar   rB   rC   existsr   rw   r%   hr_approved_byhr_approved_at
hr_commentweekday
full_cleanr*   r   r
   rj   r   rb   
isinstancemessage_dictitemsany)r5   r   
date_valuecurrent_dater   r   r   existing_request	error_msgovertime
is_weekendresponse_datar|   r   field
error_listr6   r6   r7   request_overtime   s   $








""
r   c              
   C   sB  | j j}|jdvrt| d tdS |jdkrd}nd}tjj|d}dd	l	m
} tjj|d
j|dd}dd |D }i }|D ]}|jj}	|	|vsT|j||	 jkr_|||	< ||	d|_qBt| dd dd}
| jdkr| jd}| jd}| jdd}|r|rtt|d}d}t }|jdkr|dkrd}||_||_||_||_t| d t|| d nZd}||_||_||_||_t| d t|| d n?|jdkr|dkrd }||_||_ ||_!||_"t| d! t#|| d nd"}||_||_ ||_!||_"t| d t$|| d z|%  t&jj'||||d# tt(d$W S  t)yg } z1t*|}t+|d%rM|j,rMd&-d'd( |j,. D }t| d)| d* tt(d$W  Y d}~S d}~w t/y } zt| d+t*| d, tt(d$W  Y d}~S d}~ww |
|j|jdkrd-nd.d/}t0| d0|S )1z/Handle overtime approvals for HR and Registrar.r   r   z/You do not have permission to approve requests.r!   r   rR   r   r   r   )r   )overtimerequest__statusovertimerequest)r[   c                 S   s   i | ]}|j |jqS r6   )r*   r[   )r4   r|   r6   r6   r7   
<dictcomp>  s    z$approve_overtime.<locals>.<dictcomp>c                 S   s   | j S r0   )r   )xr6   r6   r7   <lambda>  s    z"approve_overtime.<locals>.<lambda>T)keyr
   rs   rl   actionrn    rU   Napprovez'Request approved and sent to Registrar.ro   HR_REJECTEDzRequest rejected.r   rQ   z(Request approved for payment processing.REG_REJECTEDrq   overtime:approver   z; c                 S   s$   g | ]\}}| d d | qS )z: z, )join)r4   r   r   r6   r6   r7   r     s   $ z$approve_overtime.<locals>.<listcomp>zError processing request: z3. Please review the overtime details and try again.zAn unexpected error occurred: z&. Please contact system administrator.zPending Overtime RequestszHR Approved Requests)requestsr@   r<   zovertime/approvals.html)1r?   r)   r@   r   rA   r   r   rB   rC   django.db.modelsr   r   rG   r*   r   r^   r[   sortedrF   r   rs   r   r   r`   r%   r   r   r   rj   r   warningr   registrar_approved_byregistrar_approved_atregistrar_commentr   r   rw   r   rx   r
   r   rb   hasattrr   r   r   rz   r   )r5   r)   status_filterall_requestsr   employees_with_countsemployee_countsemployee_requestsreqrN   r   rl   r   rn   r{   
new_statusr`   r|   r   rL   r6   r6   r7   approve_overtimeg  s   


r   c                 C   sx   t t|d}| jj|jkr-t| jjjdk| jjjdk| jjjdkgs-t| d tdS |d|j	 d}t
| d	|S )
NrU   r   r   r   z/You don't have permission to view this request.r!   zOvertime Request - )r5   r<   zovertime/view_request.html)r   r   r?   r)   r   r@   r   rA   r   r   r   )r5   rl   r{   rL   r6   r6   r7   view_request  s   
r   c                 C   s8  t t|d}| jj|jkrt| d tdS |jdvr&t| d tdS | jdkrt	| j
| j|| jjd}| r|jdd	}| jj|_d
|_d|_d|_d|_d|_d|_d|_|  |jddv rzddlm} ||| d t| d nt| d td|jdS nt	|| jjd}|d|d}t| d|S )z9Allow employees to edit their rejected overtime requests.rU   z$You can only edit your own requests.r!   )r   r   z$You can only edit rejected requests.rs   )instancer)   Fr   rR   Nr   r%   r   )r   ro   z6Overtime request updated successfully and resubmitted.z&Overtime request updated successfully.r   rl   zEdit Overtime Request)r   r<   r{   r   )r   r   r?   r)   r   rA   r   r%   r   r   rs   r   r   rw   r   r   r   r   r   r   initialr^   notifications.utilsr   rj   r*   r   )r5   rl   r{   r   r   rL   r6   r6   r7   edit_request  sB   


r   c                 C   sn   t t|d}| jj|jkrt| d tdS |jdvr)t| d td|jdS |	  t
| d td	S )
NrU   z1You don't have permission to delete this request.r!   )rR   r   r   z1Only pending or rejected requests can be deleted.r   r   z&Overtime request deleted successfully.zovertime:my_requests)r   r   r?   r)   r   rA   r   r%   r*   deleterj   )r5   rl   r{   r6   r6   r7   delete_request!  s   
r   c                 C   s   t jj| jjddddddd}| |jdd	 |jd
d	 |jddgd |jdd	 |jdd	t	dd pBdt
dd |jdd	D d}d||d}t| d|S )z1View for users to see their own overtime requestsr   r'   hr_approved_by__userregistrar_approved_by__userr(   -datez-created_atrR   r   rQ   r   r   )
status__inr"   r+   r.   r   c                 s   r/   r0   r1   r3   r6   r6   r7   r8   G  r9   zmy_requests.<locals>.<genexpr>)r,   pending_requestsapproved_requestsrejected_requestsr=   r-   r2   zMy Overtime Requests)r<   r   r>   zovertime/my_requests.html)r   rB   rC   r?   r)   rD   rE   rH   rI   r   rJ   r   )r5   r   r>   rL   r6   r6   r7   my_requests2  s0   r   c                 C   s"   dt    d}t| d|S )z&Simple overtime calculator for financezOvertime Calculator)r<   r   zovertime/calculator.html)r   r`   r   	isoformatr   )r5   rL   r6   r6   r7   overtime_calculatorR  s   r   c              
   C   s  | j j}|jdvrt| d tdS tt|d}|jdkr*tj	j
|ddd}ntj	j
|d	dd}| jd
kr| jd}| jd}| jdd}|r|rd}|jdkrf|dkr_d	}n|dkred}n|dkrmd}n|dkrsd}|rt }	d}
|D ]J}z>tj	j|d}||_|jdkr||_|	|_||_n||_|	|_||_|dkr|  |  tj	j||||d |
d7 }
W q} tjy   Y q}w d|v rdnd}t| d| d|
 d|j    tdS t | dd |j   |||jd!S )"zGView and approve/reject all overtime requests from a specific employee.r   r    r!   rU   r   rR   )r)   r%   r   r   rs   r   r   rn   r   Nr   rejectr   rQ   r   r   rq   r   APPROVEDapprovedrejectedzSuccessfully  z overtime requests for r   zovertime/employee_requests.htmlzOvertime Requests - )
page_titler)   r   r@   )!r?   r)   r@   r   rA   r   r   r   r   rB   rC   rE   r   rs   r^   r~   r   r`   r%   r   r   r   r   r   r   calculate_amountrw   r   rx   ry   rj   ra   r   )r5   rN   current_employeer)   r   r   r   rn   r   r`   updated_countrl   r{   action_textr6   r6   r7   employee_overtime_requests_  s   




r   ):django.shortcutsr   r   r   django.contrib.auth.decoratorsr   django.contribr   django.utilsr   django.httpr   r	   django.urlsr
   r   r   r   r   r   r   django.core.exceptionsr   r   decimalr   accounts.modelsr   django.views.decorators.httpr   modelsr   r   formsr   r   r   r   r   r   r   r   rM   rg   r}   r   logging	getLogger__name__r   r   r   r   r   r   r   r   r   r6   r6   r6   r7   <module>   sR     
'
K'2

|
x

-


