Customer Payment, Supplier Payment: early discount support.
[fa-stable.git] / includes / ui / allocation_cart.inc
1 <?php
2 /**********************************************************************
3     Copyright (C) FrontAccounting, LLC.
4         Released under the terms of the GNU General Public License, GPL, 
5         as published by the Free Software Foundation, either version 3 
6         of the License, or (at your option) any later version.
7     This program is distributed in the hope that it will be useful,
8     but WITHOUT ANY WARRANTY; without even the implied warranty of
9     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
10     See the License here <http://www.gnu.org/licenses/gpl-3.0.html>.
11 ***********************************************************************/
12 /*
13         Class for supplier/customer payment/credit allocations edition
14         and related helpers.
15 */
16 //-----------------------------------------------------------------------------------
17
18 class allocation 
19 {
20
21         var $trans_no; 
22         var $type;
23         var $person_id = '';
24         var $person_name = '';
25         var $person_type;       // PT_SUPPLIER/PT_CUSTOMER
26         var $person_curr;
27         var $date_;
28         var $amount = 0; /*Total amount of the transaction in FX */
29         var $currency;
30
31         var $allocs; /*array of transactions allocated to */
32
33         function __construct($type, $trans_no, $person_id = null, $person_type_id=null)
34         {
35                 $this->allocs = array();
36                 
37                 $this->trans_no = $trans_no;
38                 $this->type = $type;
39                 if ($person_id)
40                         $this->set_person($person_id, $person_type_id);
41
42                 $this->read($type, $trans_no, $person_id, $person_type_id); // read payment or credit
43         }
44
45         function set_person($person_id, $person_type)
46         {
47                 $this->person_id = $person_id;
48                 $this->person_type = $person_type;
49                 $this->person_curr = $person_type == PT_SUPPLIER ?
50                         get_supplier_currency($person_id) : get_customer_currency($person_id);
51                 return $this->person_curr;
52         }
53
54         function add_item($type, $type_no, $date_, $due_date, $amount, $amount_allocated, 
55                 $current_allocated, $ref, $early_discount=0, $early_days=0, $discount=0)
56         {
57                 if (floatcmp($amount, 0))
58                 {
59                         $this->allocs[count($this->allocs)] = new allocation_item($type, $type_no, 
60                                 $date_, $due_date, $amount, $amount_allocated, $current_allocated, $ref, $early_discount, $early_days, $discount);
61                         return $this->allocs[count($this->allocs)-1];
62                 } 
63                 else 
64                 {
65                         return false;
66                 }
67         }
68         
69         function update_item($index, $type, $type_no, $date_, $due_date, 
70                 $amount, $amount_allocated, $current_allocated, $ref, $early_discount=0, $early_days=0, $discount=0)
71         {
72                 if (floatcmp($amount, 0))
73                 {
74                         $this->allocs[$index] = new allocation_item($type, $type_no, 
75                                 $date_, $due_date, $amount, $amount_allocated, $current_allocated, $ref, $early_discount, $early_days, $discount);
76                         return $this->allocs[$index];
77                 } 
78                 else 
79                 {
80                         return false;
81                 }
82         }
83         
84         function add_or_update_item($type, $type_no, $date_, $due_date, 
85                 $amount, $amount_allocated, $current_allocated, $ref, $early_discount=0, $early_days=0, $discount=0)
86         {
87                 for ($i = 0; $i < count($this->allocs); $i++) 
88                 {
89                         $item = $this->allocs[$i];
90                         if (($item->type == $type) && ($item->type_no == $type_no)) 
91                         {
92                                 return $this->update_item($i, $type, $type_no, $date_, $due_date, 
93                                         $amount, $amount_allocated, $current_allocated, $ref, $early_discount, $early_days, $discount);
94                         }
95                 }
96         return $this->add_item($type, $type_no, $date_, $due_date, 
97                 $amount, $amount_allocated, $current_allocated, $ref, $early_discount, $early_days, $discount);
98         }
99
100         //
101         //      Read payment or credit current/available allocations to cart.
102         //
103         // FIXME - read all transactions below twice seems to be suboptimal
104         //
105         function read($type = null, $trans_no = 0, $person_id=null, $person_type_id=null)
106         {
107                 if ($type !== null) {   // otherwise re-read
108                         $type = $this->type;
109                         $trans_no = $this->trans_no;
110
111                         if (isset($person_type_id))
112                         {
113                                 $this->person_type = $person_type_id;
114                                 $this->person_id = $person_id;
115                         } else { // guess person_type_id
116                                 if (in_array($type, array(ST_BANKPAYMENT, ST_BANKDEPOSIT)))
117                                 {
118                                         $bank_trans = db_fetch(get_bank_trans($type, $trans_no));
119                                         $this->person_type = $bank_trans['person_type_id'];
120                                 } else
121                                         $this->person_type = in_array($type, array(ST_SUPPCREDIT, ST_SUPPAYMENT)) ? PT_SUPPLIER : PT_CUSTOMER;
122                         }
123
124                         if ($trans_no) {
125                                 $trans = $this->person_type == PT_SUPPLIER ? get_supp_trans($trans_no, $type, $person_id)
126                                         : get_customer_trans($trans_no, $type, $person_id);
127
128                                 $this->person_id = $trans[$this->person_type == PT_SUPPLIER ? 'supplier_id':'debtor_no'];
129                                 $this->person_name = $trans[$this->person_type == PT_SUPPLIER ? "supplier_name":"DebtorName"];
130                                 $this->date_ = sql2date($trans["tran_date"]);
131                                 $this->person_curr = $trans['curr_code'];
132                                 $this->currency = isset($trans['bank_curr_code']) ? $trans['bank_curr_code'] : $trans['curr_code'];
133                                 $this->bank_amount = isset($trans["bank_amount"]) ? $trans["bank_amount"] : $trans["Total"]; // not set for journal entry
134                                 $this->amount = $trans["Total"];
135                         }
136                 }
137
138         /* Now populate the array of possible (and previous actual) allocations for this customer/supplier.
139                 First get the transactions that have outstanding balances ie Total-alloc >0 */
140                 $this->allocs = array();
141                 if ($this->person_id)
142                 {
143                         if ($this->person_type==PT_SUPPLIER)
144                                 $trans_items = get_allocatable_to_supp_transactions($this->person_id, $this->trans_no, $this->type);
145                         else
146                                 $trans_items = get_allocatable_to_cust_transactions($this->person_id, $this->trans_no, $this->type);
147
148                         while ($myrow = db_fetch($trans_items))
149                         {
150                                 $this->add_or_update_item ($myrow["type"], $myrow["trans_no"],
151                                         sql2date($myrow["tran_date"]),
152                                         sql2date($myrow["due_date"]),
153                                         $myrow["Total"], $myrow["alloc"]-$myrow["amt"], $myrow["amt"],
154                                         $myrow["reference"],
155                                         $myrow["early_discount"], $myrow["early_days"], $myrow["discount"]);
156                         }
157                 }
158         }
159         //
160         //      Update allocations in database.
161         //
162         function write()
163         {
164                 global  $no_exchange_variations;
165
166                 begin_transaction();
167
168                 if ($this->person_type == PT_SUPPLIER)
169                         clear_supp_alloctions($this->type, $this->trans_no, $this->person_id, $this->date_);
170                 else
171                         clear_cust_alloctions($this->type, $this->trans_no, $this->person_id, $this->date_);
172
173                 // now add the new allocations
174                 $total_allocated = 0;
175                 $dec = user_price_dec();
176                 foreach ($this->allocs as $alloc_item)
177                 {
178                         if ($alloc_item->current_allocated > 0)
179                         {
180                                 $amount = round($alloc_item->current_allocated, $dec);
181
182                                 if ($this->person_type == PT_SUPPLIER) {
183                                         add_supp_allocation($amount,
184                                                 $this->type, $this->trans_no,
185                                         $alloc_item->type, $alloc_item->type_no, $this->person_id, $this->date_, round2($alloc_item->early_discount*abs($alloc_item->amount), user_price_dec()));
186
187                                         update_supp_trans_allocation($alloc_item->type, $alloc_item->type_no, $this->person_id);
188                                 } else {
189                                         add_cust_allocation($amount,
190                                                 $this->type, $this->trans_no,
191                                         $alloc_item->type, $alloc_item->type_no, $this->person_id, $this->date_, round2($alloc_item->early_discount*abs($alloc_item->amount), user_price_dec()));
192
193                                         update_debtor_trans_allocation($alloc_item->type, $alloc_item->type_no, $this->person_id);
194                                 }
195
196                                 // Exchange Variations Joe Hunt 2008-09-20 ////////////////////
197                                 if ($alloc_item->type != ST_SALESORDER && !@$no_exchange_variations
198                                         && $alloc_item->type != ST_PURCHORDER && $alloc_item->type != ST_JOURNAL && $this->type != ST_JOURNAL)
199                                         exchange_variation($this->type, $this->trans_no,
200                                                 $alloc_item->type, $alloc_item->type_no, $this->date_,
201                                                 $amount, $this->person_type);
202
203                                 //////////////////////////////////////////////////////////////
204                                 $total_allocated += $alloc_item->current_allocated;
205                         }
206
207                 }  /*end of the loop through the array of allocations made */
208                 if ($this->person_type == PT_SUPPLIER)
209                         update_supp_trans_allocation($this->type, $this->trans_no, $this->person_id);
210                 else
211                         update_debtor_trans_allocation($this->type,     $this->trans_no, $this->person_id);
212
213                 commit_transaction();
214
215         }
216
217
218
219 //-----------------------------------------------------------------------------------
220
221 class allocation_item 
222 {
223
224         var $type;
225         var $type_no;
226         
227         var $date_;
228         var $due_date;
229         
230         var $amount_allocated;
231         var $amount;
232         var $ref;
233         
234         var $current_allocated;
235         var $early_discount;    // nominal early payment discount according to payment terms
236         var $early_days;        // days for early payment
237         var $discount_confirmed = false;
238         
239         function __construct($type, $type_no, $date_, $due_date, $amount, 
240                 $amount_allocated, $current_allocated, $ref, $early_discount=0, $early_days=0)
241         {
242
243                 $this->type = $type;
244                 $this->type_no = $type_no;
245
246                 $this->ref = $ref;
247
248                 $this->date_ = $date_;
249                 $this->due_date = $due_date;
250                 
251                 $this->amount = $amount;
252                 $this->amount_allocated = $amount_allocated;
253                 $this->current_allocated = $current_allocated;
254                 $this->early_discount = $early_discount;
255                 $this->early_days = $early_days;
256         }
257
258         function confirm_discount($confirmed)
259         {
260                 $this->discount_confirmed = $confirmed;
261         }
262 }
263
264 //--------------------------------------------------------------------------------
265
266 function show_allocatable($reallocation) {
267
268         global $systypes_array;
269         
270     $k = $total_allocated = $total_discount = 0;
271
272         $cart = $_SESSION['alloc'];
273         $supp_ref = in_array($cart->type, array(ST_SUPPCREDIT, ST_SUPPAYMENT, ST_BANKPAYMENT));
274
275         if (count($cart->allocs)) 
276         {
277                 display_heading(sprintf(_("Allocated amounts in %s:"), $cart->person_curr));
278                 start_table(TABLESTYLE, "width='60%'");
279                 $th = array(_("Transaction Type"), _("#"), $supp_ref ? _("Supplier Ref"): _("Ref"), _("Date"), _("Due Date"), _("Amount"),
280                         _("Other Allocations"), _("Left to Allocate"), _("Early Payment Discount"), _("This Allocation"),'','');
281
282                 table_header($th);
283                 $doc_ids = array();
284                 foreach ($cart->allocs as $id => $alloc_item)
285                 {
286                         $doc_ids[] = $id;
287                         $early_discount = $alloc_item->early_discount != 0 && !date1_greater_date2($cart->date_,  add_days($alloc_item->date_, $alloc_item->early_days));
288                                 alt_table_row_color($k);
289                         label_cell($systypes_array[$alloc_item->type]);
290                                 label_cell(get_trans_view_str($alloc_item->type, $alloc_item->type_no), "nowrap align='right'");
291                                 label_cell($alloc_item->ref);
292                         label_cell($alloc_item->date_, "align=right");
293                         label_cell($alloc_item->due_date, "align=right");
294                         amount_cell(abs($alloc_item->amount));
295                                 amount_cell($alloc_item->amount_allocated);
296
297                         $_POST['amount' . $id] = price_format($alloc_item->current_allocated);
298                         
299                         $un_allocated = round((abs($alloc_item->amount) - $alloc_item->amount_allocated), 6);
300
301                                 amount_cell($un_allocated-$alloc_item->current_allocated, false,'', 'left'.$id);
302
303                         if ($early_discount) {
304                                 $discount = round2($alloc_item->early_discount*abs($alloc_item->amount),user_price_dec());
305                                         check_cells(null, 'early_disc'.$id, price_format($discount), false, false, 'align=center');
306                                         $total_discount += $discount;
307                                 } else {
308                                         label_cell(_("N/A"), 'align=center', 'early_disc'.$id); hidden('early_disc'.$id, 0);
309                                 }
310                         amount_cells(null, "amount" . $id);
311
312                                 label_cell("<a href='#' name=Alloc$id onclick='allocate_all(this.name.substr(5));return true;'>"
313                                          . _("All") . "</a>");
314                                 label_cell("<a href='#' name=DeAll$id onclick='allocate_none(this.name.substr(5));return true;'>"
315                                          . _("None") . "</a>".hidden("un_allocated".$id, price_format($un_allocated), false));
316                                 end_row();
317
318                         $total_allocated += input_num('amount' . $id);
319                 }
320                 add_js_source('var docs=['.implode(',', $doc_ids).']');
321                 if ($reallocation) {
322                 label_row(_("Total Allocated"), price_format($total_allocated),
323                         "colspan=9 align=right", "align=right id='total_allocated'", 3);
324
325                 label_row(_("Total Discount"), price_format($total_discount),
326                         "colspan=9 align=right", "align=right id='total_discount'", 3);
327
328                         $amount = abs($cart->amount);
329
330                         if (floatcmp($amount, $total_allocated) < 0)
331                 {
332                         $font1 = "<font color=red>";
333                         $font2 = "</font>";
334             }
335                 else
336                         $font1 = $font2 = "";
337                         $left_to_allocate = price_format($amount - $total_allocated);
338                 label_row(_("Left to Allocate"), $font1 . $left_to_allocate . $font2, 
339                                 "colspan=9 align=right", "nowrap align=right id='left_to_allocate'",
340                                  3);
341                 }
342                 end_table(1);
343         }
344         hidden('TotalNumberOfAllocs', count($cart->allocs));
345 }
346 //--------------------------------------------------------------------------------
347
348 function check_allocations()
349 {
350         global $SysPrefs;
351
352         $total_allocated = $discount=0;
353
354         for ($counter = 0; $counter < get_post("TotalNumberOfAllocs"); $counter++)
355         {
356                 if (!isset($_POST['amount'.$counter])) continue;
357                 if (!check_num('amount' . $counter, 0))
358                 {
359                         display_error(_("The entry for one or more amounts is invalid or negative."));
360                         set_focus('amount'.$counter);
361                         return false;
362                  }
363
364                   /* Now check to see that the AllocAmt is no greater than the
365                  amount left to be allocated against the transaction under review;
366                  skip check if no allocation is set to avoid deadlock on mistakenly overallocated transactions*/
367                  $allocated = input_num('amount' . $counter);
368                  if ($allocated && ($allocated > input_num('un_allocated' . $counter)))
369                  {
370                         display_error(_("At least one transaction is overallocated."));
371                         set_focus('amount'.$counter);
372                         return false;
373                  }
374
375                  $_SESSION['alloc']->allocs[$counter]->current_allocated = input_num('amount' . $counter);
376
377                  $total_allocated += input_num('amount' . $counter);
378
379                  $_SESSION['alloc']->allocs[$counter]->discount_confirmed = check_value('early_disc'.$counter) != 0;
380                  $discount += check_value('early_disc'.$counter) 
381                         ? round2($_SESSION['alloc']->allocs[$counter]->early_discount*input_num('amount' . $counter), user_price_dec()) : 0;
382         }
383         $amount = abs($_SESSION['alloc']->amount);
384
385         if ($total_allocated - ($amount + $discount)  > $SysPrefs->allocation_settled_allowance())
386         {
387                 display_error(_("These allocations cannot be processed because the amount allocated is more than the total amount left to allocate."));
388                 return false;
389         }
390
391         return true;
392 }
393
394 //----------------------------------------------------------------------------------------
395 //
396 //      Returns sales or purchase invoice allocations to be reallocated after invoice edition.
397 //
398 function get_inv_allocations($trans_no, $trans_type, $person_id)
399 {
400         $allocs = array();
401         if ($trans_type == ST_SUPPINVOICE || $trans_type == ST_SUPPCREDIT)
402                 $result = get_allocatable_from_supp_transactions($person_id, $trans_no, $trans_type);
403         else
404                 $result = get_allocatable_from_cust_transactions($person_id, $trans_no, $trans_type);
405
406         while($dat = db_fetch($result))
407         {
408                 $allocs[] = array('type'=> $dat['type'], 'trans_no'=> $dat['trans_no'], 'amount'=>$dat['alloc']);
409         }
410         return $allocs;
411 }
412