@@ -111,6 +111,19 @@ def on_submit(self):
111111 self .notify_employee ()
112112
113113 self .create_leave_ledger_entry ()
114+ # create a reverse ledger entry for backdated leave applications for whom expiry entry already exists
115+ leave_allocation = self .get_leave_allocation ()
116+ if not leave_allocation :
117+ return
118+ to_date = leave_allocation .get ("to_date" )
119+ can_expire = not frappe .db .get_value ("Leave Type" , self .leave_type , "is_carry_forward" )
120+
121+ if to_date < getdate () and can_expire :
122+ args = frappe ._dict (
123+ leaves = self .total_leave_days , from_date = to_date , to_date = to_date , is_carry_forward = 0
124+ )
125+ create_leave_ledger_entry (self , args )
126+
114127 self .reload ()
115128
116129 def before_cancel (self ):
@@ -247,6 +260,22 @@ def validate_back_dated_application(self):
247260 ).format (formatdate (future_allocation [0 ].from_date ), future_allocation [0 ].name )
248261 )
249262
263+ def get_leave_allocation (self ):
264+ date = self .posting_date or getdate ()
265+ LeaveAllocation = frappe .qb .DocType ("Leave Allocation" )
266+ leave_allocation = (
267+ frappe .qb .from_ (LeaveAllocation )
268+ .select (LeaveAllocation .to_date )
269+ .where (
270+ ((LeaveAllocation .from_date <= date ) & (date <= LeaveAllocation .to_date ))
271+ & (LeaveAllocation .docstatus == 1 )
272+ & (LeaveAllocation .leave_type == self .leave_type )
273+ & (LeaveAllocation .employee == self .employee )
274+ )
275+ ).run (as_dict = True )
276+
277+ return leave_allocation [0 ] if leave_allocation else None
278+
250279 def update_attendance (self ):
251280 if self .status != "Approved" :
252281 return
@@ -969,12 +998,12 @@ def get_leave_balance_on(
969998
970999 allocation_records = get_leave_allocation_records (employee , date , leave_type )
9711000 allocation = allocation_records .get (leave_type , frappe ._dict ())
972-
973- end_date = allocation .to_date if cint (consider_all_leaves_in_the_allocation_period ) else date
1001+ end_date = (
1002+ allocation .to_date if (allocation and cint (consider_all_leaves_in_the_allocation_period )) else date
1003+ )
9741004 cf_expiry = get_allocation_expiry_for_cf_leaves (employee , leave_type , to_date , allocation .from_date )
9751005
9761006 leaves_taken = get_leaves_for_period (employee , leave_type , allocation .from_date , end_date )
977-
9781007 manually_expired_leaves = get_manually_expired_leaves (
9791008 employee , leave_type , allocation .from_date , end_date
9801009 )
@@ -1138,7 +1167,7 @@ def get_manually_expired_leaves(
11381167 & (ledger .employee == employee )
11391168 & (ledger .leave_type == leave_type )
11401169 & (ledger .from_date >= from_date )
1141- & (ledger .to_date <= end_date )
1170+ & (ledger .to_date < end_date )
11421171 & (ledger .transaction_type == "Leave Allocation" )
11431172 & ((ledger .is_expired == 1 ) & (ledger .is_carry_forward == 0 ))
11441173 )
0 commit comments