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