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