Incorrect Journal Balance (sales invoice) when many decimals in tax and price.
[fa-stable.git] / sales / customer_delivery.php
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 //
14 //      Entry/Modify Delivery Note against Sales Order
15 //
16 $page_security = 'SA_SALESDELIVERY';
17 $path_to_root = "..";
18
19 include_once($path_to_root . "/sales/includes/cart_class.inc");
20 include_once($path_to_root . "/includes/session.inc");
21 include_once($path_to_root . "/includes/data_checks.inc");
22 include_once($path_to_root . "/sales/includes/sales_db.inc");
23 include_once($path_to_root . "/sales/includes/sales_ui.inc");
24 include_once($path_to_root . "/reporting/includes/reporting.inc");
25 include_once($path_to_root . "/taxes/tax_calc.inc");
26
27 $js = "";
28 if ($SysPrefs->use_popup_windows) {
29         $js .= get_js_open_window(900, 500);
30 }
31 if (user_use_date_picker()) {
32         $js .= get_js_date_picker();
33 }
34
35 if (isset($_GET['ModifyDelivery'])) {
36         $_SESSION['page_title'] = sprintf(_("Modifying Delivery Note # %d."), $_GET['ModifyDelivery']);
37         $help_context = "Modifying Delivery Note";
38         processing_start();
39 } elseif (isset($_GET['OrderNumber'])) {
40         $_SESSION['page_title'] = _($help_context = "Deliver Items for a Sales Order");
41         processing_start();
42 }
43
44 page($_SESSION['page_title'], false, false, "", $js);
45
46 if (isset($_GET['AddedID'])) {
47         $dispatch_no = $_GET['AddedID'];
48
49         display_notification_centered(sprintf(_("Delivery # %d has been entered."),$dispatch_no));
50
51         display_note(get_customer_trans_view_str(ST_CUSTDELIVERY, $dispatch_no, _("&View This Delivery")), 0, 1);
52
53         display_note(print_document_link($dispatch_no, _("&Print Delivery Note"), true, ST_CUSTDELIVERY));
54         display_note(print_document_link($dispatch_no, _("&Email Delivery Note"), true, ST_CUSTDELIVERY, false, "printlink", "", 1), 1, 1);
55         display_note(print_document_link($dispatch_no, _("P&rint as Packing Slip"), true, ST_CUSTDELIVERY, false, "printlink", "", 0, 1));
56         display_note(print_document_link($dispatch_no, _("E&mail as Packing Slip"), true, ST_CUSTDELIVERY, false, "printlink", "", 1, 1), 1);
57
58         display_note(get_gl_view_str(13, $dispatch_no, _("View the GL Journal Entries for this Dispatch")),1);
59
60         if (!isset($_GET['prepaid']))
61                 hyperlink_params("$path_to_root/sales/customer_invoice.php", _("Invoice This Delivery"), "DeliveryNumber=$dispatch_no");
62
63         hyperlink_params("$path_to_root/sales/inquiry/sales_orders_view.php", _("Select Another Order For Dispatch"), "OutstandingOnly=1");
64
65         display_footer_exit();
66
67 } elseif (isset($_GET['UpdatedID'])) {
68
69         $delivery_no = $_GET['UpdatedID'];
70
71         display_notification_centered(sprintf(_('Delivery Note # %d has been updated.'),$delivery_no));
72
73         display_note(get_trans_view_str(ST_CUSTDELIVERY, $delivery_no, _("View this delivery")), 0, 1);
74
75         display_note(print_document_link($delivery_no, _("&Print Delivery Note"), true, ST_CUSTDELIVERY));
76         display_note(print_document_link($delivery_no, _("&Email Delivery Note"), true, ST_CUSTDELIVERY, false, "printlink", "", 1), 1, 1);
77         display_note(print_document_link($delivery_no, _("P&rint as Packing Slip"), true, ST_CUSTDELIVERY, false, "printlink", "", 0, 1));
78         display_note(print_document_link($delivery_no, _("E&mail as Packing Slip"), true, ST_CUSTDELIVERY, false, "printlink", "", 1, 1), 1);
79
80         if (!isset($_GET['prepaid']))
81                 hyperlink_params($path_to_root . "/sales/customer_invoice.php", _("Confirm Delivery and Invoice"), "DeliveryNumber=$delivery_no");
82
83         hyperlink_params($path_to_root . "/sales/inquiry/sales_deliveries_view.php", _("Select A Different Delivery"), "OutstandingOnly=1");
84
85         display_footer_exit();
86 }
87 //-----------------------------------------------------------------------------
88
89 if (isset($_GET['OrderNumber']) && $_GET['OrderNumber'] > 0) {
90
91         $ord = new Cart(ST_SALESORDER, $_GET['OrderNumber'], true);
92         if ($ord->is_prepaid())
93                 check_deferred_income_act(_("You have to set Deferred Income Account in GL Setup to entry prepayment invoices."));
94
95         if ($ord->count_items() == 0) {
96                 hyperlink_params($path_to_root . "/sales/inquiry/sales_orders_view.php",
97                         _("Select a different sales order to delivery"), "OutstandingOnly=1");
98                 echo "<br><center><b>" . _("This order has no items. There is nothing to delivery.") .
99                         "</center></b>";
100                 display_footer_exit();
101         } else if (!$ord->is_released()) {
102                 hyperlink_params($path_to_root . "/sales/inquiry/sales_orders_view.php",_("Select a different sales order to delivery"),
103                         "OutstandingOnly=1");
104                 echo "<br><center><b>"._("This prepayment order is not yet ready for delivery due to insufficient amount received.")
105                         ."</center></b>";
106                 display_footer_exit();
107         }
108         // Adjust Shipping Charge based upon previous deliveries TAM
109         adjust_shipping_charge($ord, $_GET['OrderNumber']);
110  
111         $_SESSION['Items'] = $ord;
112         copy_from_cart();
113
114 } elseif (isset($_GET['ModifyDelivery']) && $_GET['ModifyDelivery'] > 0) {
115
116         check_is_editable(ST_CUSTDELIVERY, $_GET['ModifyDelivery']);
117         $_SESSION['Items'] = new Cart(ST_CUSTDELIVERY,$_GET['ModifyDelivery']);
118
119         if (!$_SESSION['Items']->prepaid && $_SESSION['Items']->count_items() == 0) {
120                 hyperlink_params($path_to_root . "/sales/inquiry/sales_orders_view.php",
121                         _("Select a different delivery"), "OutstandingOnly=1");
122                 echo "<br><center><b>" . _("This delivery has all items invoiced. There is nothing to modify.") .
123                         "</center></b>";
124                 display_footer_exit();
125         }
126
127         copy_from_cart();
128         
129 } elseif ( !processing_active() ) {
130         /* This page can only be called with an order number for invoicing*/
131
132         display_error(_("This page can only be opened if an order or delivery note has been selected. Please select it first."));
133
134         hyperlink_params("$path_to_root/sales/inquiry/sales_orders_view.php", _("Select a Sales Order to Delivery"), "OutstandingOnly=1");
135
136         end_page();
137         exit;
138
139 } else {
140         check_edit_conflicts(get_post('cart_id'));
141
142         if (!check_quantities()) {
143                 display_error(_("Selected quantity cannot be less than quantity invoiced nor more than quantity not dispatched on sales order."));
144
145         } elseif(!check_num('ChargeFreightCost', 0)) {
146                 display_error(_("Freight cost cannot be less than zero"));
147                 set_focus('ChargeFreightCost');
148         }
149 }
150
151 //-----------------------------------------------------------------------------
152
153 function check_data()
154 {
155         global $Refs, $SysPrefs;
156
157         if (!isset($_POST['DispatchDate']) || !is_date($_POST['DispatchDate'])) {
158                 display_error(_("The entered date of delivery is invalid."));
159                 set_focus('DispatchDate');
160                 return false;
161         }
162
163         if (!is_date_in_fiscalyear($_POST['DispatchDate'])) {
164                 display_error(_("The entered date is out of fiscal year or is closed for further data entry."));
165                 set_focus('DispatchDate');
166                 return false;
167         }
168
169         if (!isset($_POST['due_date']) || !is_date($_POST['due_date'])) {
170                 display_error(_("The entered dead-line for invoice is invalid."));
171                 set_focus('due_date');
172                 return false;
173         }
174
175         if ($_SESSION['Items']->trans_no==0) {
176                 if (!$Refs->is_valid($_POST['ref'], ST_CUSTDELIVERY)) {
177                         display_error(_("You must enter a reference."));
178                         set_focus('ref');
179                         return false;
180                 }
181         }
182         if ($_POST['ChargeFreightCost'] == "") {
183                 $_POST['ChargeFreightCost'] = price_format(0);
184         }
185
186         if (!check_num('ChargeFreightCost',0)) {
187                 display_error(_("The entered shipping value is not numeric."));
188                 set_focus('ChargeFreightCost');
189                 return false;
190         }
191
192         if ($_SESSION['Items']->has_items_dispatch() == 0 && input_num('ChargeFreightCost') == 0) {
193                 display_error(_("There are no item quantities on this delivery note."));
194                 return false;
195         }
196
197         if (!check_quantities()) {
198                 return false;
199         }
200
201         copy_to_cart();
202
203         if (!$SysPrefs->allow_negative_stock() && ($low_stock = $_SESSION['Items']->check_qoh()))
204         {
205                 display_error(_("This document cannot be processed because there is insufficient quantity for items marked."));
206                 return false;
207         }
208
209         return true;
210 }
211 //------------------------------------------------------------------------------
212 function copy_to_cart()
213 {
214         $cart = &$_SESSION['Items'];
215         $cart->ship_via = $_POST['ship_via'];
216         $cart->freight_cost = input_num('ChargeFreightCost');
217         $cart->document_date = $_POST['DispatchDate'];
218         $cart->due_date =  $_POST['due_date'];
219         $cart->Location = $_POST['Location'];
220         $cart->Comments = $_POST['Comments'];
221         $cart->dimension_id = $_POST['dimension_id'];
222         $cart->dimension2_id = $_POST['dimension2_id'];
223         if ($cart->trans_no == 0)
224                 $cart->reference = $_POST['ref'];
225
226 }
227 //------------------------------------------------------------------------------
228
229 function copy_from_cart()
230 {
231         $cart = &$_SESSION['Items'];
232         $_POST['ship_via'] = $cart->ship_via;
233         $_POST['ChargeFreightCost'] = price_format($cart->freight_cost);
234         $_POST['DispatchDate'] = $cart->document_date;
235         $_POST['due_date'] = $cart->due_date;
236         $_POST['Location'] = $cart->Location;
237         $_POST['Comments'] = $cart->Comments;
238         $_POST['dimension_id'] = $cart->dimension_id;
239         $_POST['dimension2_id'] = $cart->dimension2_id;
240         $_POST['cart_id'] = $cart->cart_id;
241         $_POST['ref'] = $cart->reference;
242 }
243 //------------------------------------------------------------------------------
244
245 function check_quantities()
246 {
247         $ok =1;
248         // Update cart delivery quantities/descriptions
249         foreach ($_SESSION['Items']->line_items as $line=>$itm) {
250                 if (isset($_POST['Line'.$line])) {
251                         if($_SESSION['Items']->trans_no) {
252                                 $min = $itm->qty_done;
253                                 $max = $itm->quantity;
254                         } else {
255                                 $min = 0;
256                                 // Fixing floating point problem in PHP.
257                                 $max = round2($itm->quantity - $itm->qty_done, get_unit_dec($itm->stock_id));
258                         }
259
260                         if (check_num('Line'.$line, $min, $max)) {
261                                 $_SESSION['Items']->line_items[$line]->qty_dispatched =
262                                   input_num('Line'.$line);
263                         } else {
264                                 set_focus('Line'.$line);
265                                 $ok = 0;
266                         }
267
268                 }
269
270                 if (isset($_POST['Line'.$line.'Desc'])) {
271                         $line_desc = $_POST['Line'.$line.'Desc'];
272                         if (strlen($line_desc) > 0) {
273                                 $_SESSION['Items']->line_items[$line]->item_description = $line_desc;
274                         }
275                 }
276         }
277         return $ok;
278 }
279
280 //------------------------------------------------------------------------------
281
282 if (isset($_POST['process_delivery']) && check_data()) {
283         $dn = &$_SESSION['Items'];
284
285         if ($_POST['bo_policy']) {
286                 $bo_policy = 0;
287         } else {
288                 $bo_policy = 1;
289         }
290         $newdelivery = ($dn->trans_no == 0);
291
292         if ($newdelivery)
293                 new_doc_date($dn->document_date);
294
295         $delivery_no = $dn->write($bo_policy);
296
297         if ($delivery_no == -1)
298         {
299                 display_error(_("The entered reference is already in use."));
300                 set_focus('ref');
301         }
302         else
303         {
304                 $is_prepaid = $dn->is_prepaid() ? "&prepaid=Yes" : '';
305
306                 processing_end();
307                 if ($newdelivery) {
308                         meta_forward($_SERVER['PHP_SELF'], "AddedID=$delivery_no$is_prepaid");
309                 } else {
310                         meta_forward($_SERVER['PHP_SELF'], "UpdatedID=$delivery_no$is_prepaid");
311                 }
312         }
313 }
314
315 if (isset($_POST['Update']) || isset($_POST['_Location_update']) || isset($_POST['qty']) || isset($_POST['process_delivery'])) {
316         $Ajax->activate('Items');
317 }
318 //------------------------------------------------------------------------------
319 start_form();
320 hidden('cart_id');
321
322 start_table(TABLESTYLE2, "width='80%'", 5);
323 echo "<tr><td>"; // outer table
324
325 start_table(TABLESTYLE, "width='100%'");
326 start_row();
327 label_cells(_("Customer"), $_SESSION['Items']->customer_name, "class='tableheader2'");
328 label_cells(_("Branch"), get_branch_name($_SESSION['Items']->Branch), "class='tableheader2'");
329 label_cells(_("Currency"), $_SESSION['Items']->customer_currency, "class='tableheader2'");
330 end_row();
331 start_row();
332
333 if ($_SESSION['Items']->trans_no==0) {
334         ref_cells(_("Reference"), 'ref', '', null, "class='tableheader2'", false, ST_CUSTDELIVERY,
335         array('customer' => $_SESSION['Items']->customer_id,
336                         'branch' => $_SESSION['Items']->Branch,
337                         'date' => get_post('DispatchDate')));
338 } else {
339         label_cells(_("Reference"), $_SESSION['Items']->reference, "class='tableheader2'");
340 }
341
342 label_cells(_("For Sales Order"), get_customer_trans_view_str(ST_SALESORDER, $_SESSION['Items']->order_no), "class='tableheader2'");
343
344 label_cells(_("Sales Type"), $_SESSION['Items']->sales_type_name, "class='tableheader2'");
345 end_row();
346 start_row();
347
348 if (!isset($_POST['Location'])) {
349         $_POST['Location'] = $_SESSION['Items']->Location;
350 }
351 label_cell(_("Delivery From"), "class='tableheader2'");
352 locations_list_cells(null, 'Location', null, false, true);
353
354 if (!isset($_POST['ship_via'])) {
355         $_POST['ship_via'] = $_SESSION['Items']->ship_via;
356 }
357 label_cell(_("Shipping Company"), "class='tableheader2'");
358 shippers_list_cells(null, 'ship_via', $_POST['ship_via']);
359
360 // set this up here cuz it's used to calc qoh
361 if (!isset($_POST['DispatchDate']) || !is_date($_POST['DispatchDate'])) {
362         $_POST['DispatchDate'] = new_doc_date();
363         if (!is_date_in_fiscalyear($_POST['DispatchDate'])) {
364                 $_POST['DispatchDate'] = end_fiscalyear();
365         }
366 }
367 date_cells(_("Date"), 'DispatchDate', '', $_SESSION['Items']->trans_no==0, 0, 0, 0, "class='tableheader2'");
368 end_row();
369
370 end_table();
371
372 echo "</td><td>";// outer table
373
374 start_table(TABLESTYLE, "width='90%'");
375
376 if (!isset($_POST['due_date']) || !is_date($_POST['due_date'])) {
377         $_POST['due_date'] = get_invoice_duedate($_SESSION['Items']->payment, $_POST['DispatchDate']);
378 }
379 customer_credit_row($_SESSION['Items']->customer_id, $_SESSION['Items']->credit, "class='tableheader2'");
380
381 $dim = get_company_pref('use_dimension');
382 if ($dim > 0) {
383         start_row();
384         label_cell(_("Dimension").":", "class='tableheader2'");
385         dimensions_list_cells(null, 'dimension_id', null, true, ' ', false, 1, false);
386         end_row();
387 }               
388 else
389         hidden('dimension_id', 0);
390 if ($dim > 1) {
391         start_row();
392         label_cell(_("Dimension")." 2:", "class='tableheader2'");
393         dimensions_list_cells(null, 'dimension2_id', null, true, ' ', false, 2, false);
394         end_row();
395 }               
396 else
397         hidden('dimension2_id', 0);
398 //---------
399 start_row();
400 date_cells(_("Invoice Dead-line"), 'due_date', '', null, 0, 0, 0, "class='tableheader2'");
401 end_row();
402 end_table();
403
404 echo "</td></tr>";
405 end_table(1); // outer table
406
407 $row = get_customer_to_order($_SESSION['Items']->customer_id);
408 if ($row['dissallow_invoices'] == 1)
409 {
410         display_error(_("The selected customer account is currently on hold. Please contact the credit control personnel to discuss."));
411         end_form();
412         end_page();
413         exit();
414 }       
415 display_heading(_("Delivery Items"));
416 div_start('Items');
417 start_table(TABLESTYLE, "width='80%'");
418
419 $new = $_SESSION['Items']->trans_no==0;
420 $th = array(_("Item Code"), _("Item Description"), 
421         $new ? _("Ordered") : _("Max. delivery"), _("Units"), $new ? _("Delivered") : _("Invoiced"),
422         _("This Delivery"), _("Price"), _("Tax Type"), _("Discount"), _("Total"));
423
424 table_header($th);
425 $k = 0;
426 $has_marked = false;
427
428 foreach ($_SESSION['Items']->line_items as $line=>$ln_itm) {
429         if ($ln_itm->quantity==$ln_itm->qty_done) {
430                 continue; //this line is fully delivered
431         }
432         if(isset($_POST['_Location_update']) || isset($_POST['clear_quantity']) || isset($_POST['reset_quantity'])) {
433                 // reset quantity
434                 $ln_itm->qty_dispatched = $ln_itm->quantity-$ln_itm->qty_done;
435         }
436         // if it's a non-stock item (eg. service) don't show qoh
437         $row_classes = null;
438         if (has_stock_holding($ln_itm->mb_flag) && $ln_itm->qty_dispatched) {
439                 // It's a stock : call get_dispatchable_quantity hook  to get which quantity to preset in the
440                 // quantity input box. This allows for example a hook to modify the default quantity to what's dispatchable
441                 // (if there is not enough in hand), check at other location or other order people etc ...
442                 // This hook also returns a 'reason' (css classes) which can be used to theme the row.
443                 //
444                 // FIXME: hook_get_dispatchable definition does not allow qoh checks on transaction level
445                 // (but anyway dispatch is checked again later before transaction is saved)
446
447                 $qty = $ln_itm->qty_dispatched;
448                 if ($check = check_negative_stock($ln_itm->stock_id, $ln_itm->qty_done-$ln_itm->qty_dispatched, $_POST['Location'], $_POST['DispatchDate']))
449                         $qty = $check['qty'];
450
451                 $q_class =  hook_get_dispatchable_quantity($ln_itm, $_POST['Location'], $_POST['DispatchDate'], $qty);
452
453                 // Skip line if needed
454                 if($q_class === 'skip')  continue;
455                 if(is_array($q_class)) {
456                   list($ln_itm->qty_dispatched, $row_classes) = $q_class;
457                         $has_marked = true;
458                 }
459         }
460
461         alt_table_row_color($k, $row_classes);
462         view_stock_status_cell($ln_itm->stock_id);
463
464         if ($ln_itm->descr_editable)
465                 text_cells(null, 'Line'.$line.'Desc', $ln_itm->item_description, 30, 50);
466         else
467                 label_cell($ln_itm->item_description);
468
469         $dec = get_qty_dec($ln_itm->stock_id);
470         qty_cell($ln_itm->quantity, false, $dec);
471         label_cell($ln_itm->units);
472         qty_cell($ln_itm->qty_done, false, $dec);
473
474         if(isset($_POST['clear_quantity'])) {
475                 $ln_itm->qty_dispatched = 0;
476         }
477         $_POST['Line'.$line]=$ln_itm->qty_dispatched; /// clear post so value displayed in the fiel is the 'new' quantity
478         small_qty_cells(null, 'Line'.$line, qty_format($ln_itm->qty_dispatched, $ln_itm->stock_id, $dec), null, null, $dec);
479
480         $display_discount_percent = percent_format($ln_itm->discount_percent*100) . "%";
481
482         $line_total = ($ln_itm->qty_dispatched * $ln_itm->price * (1 - $ln_itm->discount_percent));
483
484         amount_cell($ln_itm->price);
485         label_cell($ln_itm->tax_type_name);
486         label_cell($display_discount_percent, "nowrap align=right");
487         amount_cell($line_total);
488
489         end_row();
490 }
491
492 $_POST['ChargeFreightCost'] =  get_post('ChargeFreightCost', 
493         price_format($_SESSION['Items']->freight_cost));
494
495 $colspan = 9;
496
497 start_row();
498 label_cell(_("Shipping Cost"), "colspan=$colspan align=right");
499 small_amount_cells(null, 'ChargeFreightCost', $_SESSION['Items']->freight_cost);
500 end_row();
501
502 $inv_items_total = $_SESSION['Items']->get_items_total_dispatch();
503
504 $display_sub_total = price_format($inv_items_total + input_num('ChargeFreightCost'));
505
506 label_row(_("Sub-total"), $display_sub_total, "colspan=$colspan align=right","align=right");
507
508 $taxes = $_SESSION['Items']->get_taxes(input_num('ChargeFreightCost'));
509 $tax_total = display_edit_tax_items($taxes, $colspan, $_SESSION['Items']->tax_included);
510
511 $display_total = price_format(($inv_items_total + input_num('ChargeFreightCost') + $tax_total));
512
513 label_row(_("Amount Total"), $display_total, "colspan=$colspan align=right","align=right");
514
515 end_table(1);
516
517 if ($has_marked) {
518         display_note(_("Marked items have insufficient quantities in stock as on day of delivery."), 0, 1, "class='stockmankofg'");
519 }
520 start_table(TABLESTYLE2);
521
522 policy_list_row(_("Action For Balance"), "bo_policy", null);
523
524 textarea_row(_("Memo"), 'Comments', null, 50, 4);
525
526 end_table(1);
527 div_end();
528 submit_center_first('Update', _("Update"),
529         _('Refresh document page'), true);
530 if(isset($_POST['clear_quantity'])) {
531         submit('reset_quantity', _('Reset quantity'), true, _('Refresh document page'));
532 }
533 else  {
534         submit('clear_quantity', _('Clear quantity'), true, _('Refresh document page'));
535 }
536 submit_center_last('process_delivery', _("Process Dispatch"),
537         _('Check entered data and save document'), 'default');
538
539 end_form();
540
541
542 end_page();
543