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