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