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