Fixed false qoh alerts.
[fa-stable.git] / sales / includes / ui / sales_order_ui.inc
1 <?php
2 /**********************************************************************
3     Copyright (C) FrontAccounting, LLC.
4         Released under the terms of the GNU Affero General Public License,
5         AGPL, as published by the Free Software Foundation, either version 
6         3 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/agpl-3.0.html>.
11 ***********************************************************************/
12 include_once($path_to_root . "/sales/includes/cart_class.inc");
13 include_once($path_to_root . "/includes/manufacturing.inc");
14
15 //--------------------------------------------------------------------------------
16 function add_to_order(&$order, $new_item, $new_item_qty, $price, $discount)
17 {
18         // calculate item price to sum of kit element prices factor for 
19         // value distribution over all exploded kit items
20          $std_price = get_kit_price($new_item, $order->customer_currency, 
21                 $order->sales_type,     $order->price_factor, get_post('OrderDate'), true);
22
23         if ($std_price == 0)
24                 $price_factor = 0;
25         else
26                 $price_factor = $price/$std_price;
27
28         $kit = get_item_kit($new_item);
29         $item_num = db_num_rows($kit);
30
31         while($item = db_fetch($kit)) {
32                 $std_price = get_kit_price($item['stock_id'], $order->customer_currency, 
33                         $order->sales_type,     $order->price_factor, get_post('OrderDate'), true);
34
35                 // rounding differences are included in last price item in kit
36                 $item_num--;
37                 if ($item_num) {
38                         $price -= $item['quantity']*$std_price*$price_factor;
39                         $item_price = $std_price*$price_factor;
40                 } else {
41                         if ($item['quantity']) 
42                                 $price = $price/$item['quantity'];
43                         $item_price = $price;
44                 }
45                 $item_price = round($item_price, user_price_dec());
46
47          if (!$item['is_foreign'] && $item['item_code'] != $item['stock_id'])
48          {      // this is sales kit - recurse 
49                 add_to_order($order, $item['stock_id'], $new_item_qty*$item['quantity'],
50                         $item_price, $discount, $std_price);
51          }
52          else
53          {      // stock item record eventually with foreign code
54
55                 // check duplicate stock item
56                 foreach ($order->line_items as $order_item)
57                 {
58                         if (strcasecmp($order_item->stock_id, $item['stock_id']) == 0)
59                         {
60                                 display_warning(_("For Part :").$item['stock_id']. " " 
61                                         . _("This item is already on this order. You have been warned."));
62                                 break;
63                         }
64                 }
65                 $order->add_to_cart (count($order->line_items), $item['stock_id'], 
66                         $new_item_qty*$item['quantity'], $item_price, $discount);
67          }
68         }
69 }
70 //---------------------------------------------------------------------------------
71
72 function get_customer_details_to_order(&$order, $customer_id, $branch_id)
73 {
74         $ret_error = "";
75
76         $myrow = get_customer_to_order($customer_id);
77
78         $name = $myrow['name'];
79
80         if ($myrow['dissallow_invoices'] == 1)
81                 $ret_error = _("The selected customer account is currently on hold. Please contact the credit control personnel to discuss.");
82
83         $deliver = $myrow['address']; // in case no branch address use company address
84
85         $order->set_customer($customer_id, $name, $myrow['curr_code'], 
86                 $myrow['discount'], $myrow['pymt_discount']);
87
88         // the sales type determines the price list to be used by default
89         $order->set_sales_type($myrow['salestype'], $myrow['sales_type'], $myrow['tax_included'],
90             $myrow['factor']);
91
92         if ($order->trans_type != 30)
93         {
94                 $order->dimension_id = $myrow['dimension_id'];
95                 $order->dimension2_id = $myrow['dimension2_id'];
96         }
97         $result = get_branch_to_order($customer_id, $branch_id);
98
99         if (db_num_rows($result) == 0)
100         {
101                 return _("The selected customer and branch are not valid, or the customer does not have any branches.");
102         }
103
104         $myrow = db_fetch($result);
105
106         $order->set_branch($branch_id, $myrow["tax_group_id"],
107         $myrow["tax_group_name"], $myrow["phone"], $myrow["email"]);
108
109         $address = trim($myrow["br_post_address"]) != '' ? $myrow["br_post_address"]
110                 : (trim($myrow["br_address"]) != '' ? $myrow["br_address"]:$deliver);
111
112         $order->set_delivery($myrow["default_ship_via"], $myrow["br_name"],
113                 $address);
114         if ($order->trans_type == 10) {
115                 $order->due_date = get_invoice_duedate($customer_id, $order->document_date);
116                 if ($order->pos != -1)
117                         $order->cash = date_diff($order->due_date, Today(), 'd')<2;
118         }
119         if($order->cash ) {
120                 if($order->pos != -1) {
121                 $paym = get_sales_point($order->pos);
122                 $order->set_location($paym["pos_location"], $paym["location_name"]);
123                 }
124         } else
125                 $order->set_location($myrow["default_location"], $myrow["location_name"]);
126                 
127         return $ret_error;
128 }
129
130 //---------------------------------------------------------------------------------
131
132 function display_order_summary($title, &$order, $editable_items=false)
133 {
134         global $table_style, $path_to_root;
135
136         display_heading($title);
137
138     div_start('items_table');
139         start_table("$table_style colspan=7 width=90%");
140         $th = array(_("Item Code"), _("Item Description"), _("Quantity"),
141                 _("Delivered"),
142                 _("Unit"), _("Price"), _("Discount %"), _("Total"), "");
143
144         if ($order->trans_no == 0) {
145         unset( $th[3] );
146         }
147
148         if (count($order->line_items))
149              $th[]= '';
150
151         table_header($th);
152
153         $total = 0;
154         $k = 0;  //row colour counter
155
156         $id = find_submit('Edit');
157         foreach ($order->line_items as $line_no=>$stock_item)
158         {
159
160                 $line_total = round($stock_item->qty_dispatched * $stock_item->price * (1 - $stock_item->discount_percent),
161                    user_price_dec());
162
163
164                 if (!$editable_items || $id != $line_no)
165                 {
166                         alt_table_row_color($k);
167
168                         view_stock_status_cell($stock_item->stock_id);
169
170                         label_cell($stock_item->item_description, "nowrap" );
171                         qty_cell($stock_item->qty_dispatched, false, get_qty_dec($stock_item->stock_id));
172
173                         if ($order->trans_no!=0)
174                                 amount_cell($stock_item->qty_done);
175
176                         label_cell($stock_item->units);
177                         amount_cell($stock_item->price);
178
179                         percent_cell($stock_item->discount_percent * 100);
180                         amount_cell($line_total);
181
182                         if ($editable_items)
183                         {
184                                 edit_button_cell("Edit$line_no", _("Edit"),
185                                 _('Edit document line'));
186                                 delete_button_cell("Delete$line_no", _("Delete"),
187                                 _('Remove line from document'));
188                         }
189                         end_row();
190                 }
191                 else
192                 {
193                         sales_order_item_controls($order, $k,  $line_no);
194                 }
195
196                 $total += $line_total;
197         }
198
199         if ($id==-1 && $editable_items)
200                 sales_order_item_controls($order, $k);
201
202         $display_total = price_format($total);
203         label_row(_("Total Excluding Shipping"), $display_total, "colspan=6 align=right",
204                 "nowrap align=right", 2);
205
206         end_table();
207     div_end();
208 }
209
210 // ------------------------------------------------------------------------------
211
212 function display_order_header(&$order, $editable, $date_text, $display_tax_group=false)
213 {
214         global $table_style, $Ajax;
215
216         start_outer_table("width=80% $table_style");
217
218         table_section(1);
219         
220         $customer_error = "";
221         $change_prices = 0;
222
223         if (isset($order) && !$editable)
224         {
225                 // can't change the customer/branch if items already received on this order
226                 echo $order->customer_name . " - " . $order->deliver_to;
227                 hidden('customer_id', $order->customer_id);
228                 hidden('branch_id', $order->Branch);
229                 hidden('sales_type', $order->sales_type);
230                 if ($order->trans_type != 30) {
231                         hidden('dimension_id', $order->dimension_id); // 2008-11-12 Joe Hunt
232                         hidden('dimension2_id', $order->dimension2_id);
233                 }       
234         }
235         else
236         {
237                 customer_list_row(_("Customer:"), 'customer_id', null, false, true);
238
239                 if ($order->customer_id != get_post('customer_id', -1))
240                 {
241                         // customer has changed
242                         $Ajax->activate('branch_id');
243                 }
244                 customer_branches_list_row(_("Branch:"),
245                   $_POST['customer_id'], 'branch_id', null, false, true, true);
246
247         if( ($order->customer_id != get_post('customer_id', -1)) ||
248                         ($order->Branch != get_post('branch_id', -1)) ||
249                         list_updated('customer_id')) {
250
251                 if (!isset($_POST['branch_id']) || $_POST['branch_id'] == "")
252                 {
253                         // ignore errors on customer search box call
254                         if ($_POST['customer_id'] == '')
255                             $customer_error = _("No customer found for entered text.");
256                         else
257                             $customer_error = _("The selected customer does not have any branches. Please create at least one branch.");
258                     unset($_POST['branch_id']);
259                     $order->Branch = 0;
260                 } else
261                 {
262
263                                 $old_order = (PHP_VERSION<5) ? $order : clone( $order );
264                                 $customer_error = get_customer_details_to_order($order, $_POST['customer_id'], $_POST['branch_id']);
265
266                                 $_POST['Location'] = $order->Location;
267                                 $_POST['deliver_to'] = $order->deliver_to;
268                                 $_POST['delivery_address'] = $order->delivery_address;
269                                 $_POST['phone'] = $order->phone;
270                                 if (get_post('cash') !== $order->cash) {
271                                         $_POST['cash'] = $order->cash;
272                                         $Ajax->activate('delivery');
273                                         $Ajax->activate('cash');
274                                 } else {
275                                         if ($order->trans_type == 10)
276                                         {
277                                                 $_POST['delivery_date'] = $order->due_date;
278                                                 $Ajax->activate('delivery_date');
279                                         }
280                                         $Ajax->activate('Location');
281                                         $Ajax->activate('deliver_to');
282                                         $Ajax->activate('phone');
283                                         $Ajax->activate('delivery_address');
284                                 }
285                                 // change prices if necessary
286                                 // what about discount in template case?
287                                 if ($old_order->customer_currency != $order->customer_currency) {
288                                     $change_prices = 1;
289                                 }
290                                 if ($old_order->sales_type != $order->sales_type) {
291                                 //  || $old_order->default_discount!=$order->default_discount
292                                         $_POST['sales_type'] = $order->sales_type;
293                                     $Ajax->activate('sales_type');
294                                     $change_prices = 1;
295                                 }
296                                 if ($old_order->dimension_id != $order->dimension_id) {
297                                         $_POST['dimension_id'] = $order->dimension_id;
298                                     $Ajax->activate('dimension_id');
299                                 }
300                                 if ($old_order->dimension2_id != $order->dimension2_id) {
301                                         $_POST['dimension2_id'] = $order->dimension2_id;
302                                     $Ajax->activate('dimension2_id');
303                                 }
304                                 unset($old_order);
305                         }
306                 set_global_customer($_POST['customer_id']);
307                 } // changed branch
308         }
309
310         if ($order->trans_type != 30) {
311                 ref_cells(_("Reference").':', 'ref', _('Reference number unique for this document type'), null, '');
312         }
313
314         if (!is_company_currency($order->customer_currency))
315         {
316             table_section(2);
317
318             div_start('currency');
319                 label_row(_("Customer Currency:"), $order->customer_currency);
320                 exchange_rate_display($order->customer_currency, get_company_currency(),
321                         ($editable ? $_POST['OrderDate'] : $order->document_date));
322             div_end();
323         }
324         table_section(3);
325
326         if ($order->trans_type == 10 && $order->pos != -1) {
327                 sale_payment_list_cells(_('Payment:'), 'cash', null, true);
328                 $cash_payment = get_post('cash', 0);
329                 // current user can issue both credit and cash invoices
330                 if ($order->cash != $cash_payment) {
331                         $order->cash = $cash_payment;
332                         if ($cash_payment) {
333                                 $paym = get_sales_point(user_pos());
334                                 $order->cash_account = $paym['pos_account'];
335                                 $order->account_name = $paym['bank_account_name'];
336                                 $_POST['Location'] = $order->Location = $paym['pos_location'];
337                                 $order->location_name = $paym['location_name'];
338                         }
339                         check_qoh($order);
340                         $Ajax->activate('delivery');
341                         set_focus($order->pos == -1 ? 'delivery_date' : 'account');
342                 }
343         } else
344                 hidden('cash', $order->cash);
345
346         if($editable) {
347                 $str = sales_types_list_row(_("Price List"), 'sales_type', null, true);
348         } else {
349                 label_row(_("Price List:"), $order->sales_type_name);
350         }
351         if ($order->sales_type != $_POST['sales_type']) {
352                 $myrow = get_sales_type($_POST['sales_type']);
353                 $order->set_sales_type($myrow['id'], $myrow['sales_type'],
354                         $myrow['tax_included'], $myrow['factor']);
355                 $Ajax->activate('sales_type');
356                 $change_prices = 1;
357         }
358
359         label_row(_("Customer Discount:"), ($order->default_discount * 100) . "%");
360         
361         table_section(4);
362
363         if ($editable)
364         {
365                 if (!isset($_POST['OrderDate']) || $_POST['OrderDate'] == "")
366                         $_POST['OrderDate'] = $order->document_date;
367
368                 date_row($date_text, 'OrderDate',
369                   _('Date of order receive'), null, 0, 0, 0, null, true);
370                 if (isset($_POST['_OrderDate_changed'])) {
371                         if (!is_company_currency($order->customer_currency) 
372                                 && (get_base_sales_type()>0)) {
373                                         $change_prices = 1;
374                         }
375                         $Ajax->activate('currency');
376                         if ($order->trans_type == 10) {
377                                 $_POST['delivery_date'] = get_invoice_duedate(get_post('customer_id'), get_post('OrderDate'));
378                         } else 
379                                 $_POST['delivery_date'] = add_days(get_post('OrderDate'), sys_prefs::default_delivery_required_by());
380                         $Ajax->activate('delivery_date');
381                 }
382                 if ($order->trans_type != 30)
383                 {       // 2008-11-12 Joe Hunt added dimensions
384                         $dim = get_company_pref('use_dimension');
385                         if ($dim > 0)
386                                 dimensions_list_row(_("Dimension").":", 'dimension_id', 
387                                         null, true, ' ', false, 1, false);
388                         else
389                                 hidden('dimension_id', 0);
390                         if ($dim > 1)
391                                 dimensions_list_row(_("Dimension")." 2:", 'dimension2_id', 
392                                         null, true, ' ', false, 2, false);
393                         else
394                                 hidden('dimension2_id', 0);
395                 }       
396         }
397         else
398         {
399                 label_row($date_text, $order->document_date);
400                 hidden('OrderDate', $order->document_date);
401         }
402
403         if ($display_tax_group)
404         {
405             label_row(_("Tax Group:"), $order->tax_group_name);
406             hidden('tax_group_id', $order->tax_group_id);
407         }
408
409         end_outer_table(1); // outer table
410
411         if ($change_prices != 0) {
412                 foreach ($order->line_items as $line_no=>$item) {
413                         $line = &$order->line_items[$line_no];
414                         $line->price = get_kit_price($line->stock_id, $order->customer_currency,
415                                 $order->sales_type, $order->price_factor, get_post('OrderDate'));
416                 //              $line->discount_percent = $order->default_discount;
417                 }
418             $Ajax->activate('items_table');
419         }
420
421         return $customer_error;
422 }
423
424 //--------------------------------------------------------------------------------
425
426 function sales_order_item_controls(&$order, &$rowcounter, $line_no=-1)
427 {
428     global $Ajax;
429
430         alt_table_row_color($rowcounter);
431
432         $id = find_submit('Edit');
433         if ($line_no!=-1 && $line_no == $id) // edit old line
434         {
435                 $_POST['stock_id'] = $order->line_items[$id]->stock_id;
436                 $dec = get_qty_dec($_POST['stock_id']);
437                 $_POST['qty'] = number_format2($order->line_items[$id]->qty_dispatched, $dec);
438                 $_POST['price'] = price_format($order->line_items[$id]->price);
439                 $_POST['Disc'] = percent_format($order->line_items[$id]->discount_percent*100);
440                 $units = $order->line_items[$id]->units;
441                 hidden('stock_id', $_POST['stock_id']);
442                 label_cell($_POST['stock_id']);
443                 label_cell($order->line_items[$line_no]->item_description, "nowrap");
444             $Ajax->activate('items_table');
445         }
446         else    // prepare new line
447         {
448                 sales_items_list_cells(null,'stock_id', null, false, true);
449                 if (list_updated('stock_id')) {
450                             $Ajax->activate('price');
451                             $Ajax->activate('units');
452                             $Ajax->activate('qty');
453                             $Ajax->activate('line_total');
454                 }
455
456                 $item_info = get_item_edit_info($_POST['stock_id']);
457                 $units = $item_info["units"];
458                 $dec = $item_info['decimals'];
459                 $_POST['qty'] = number_format2(1, $dec);
460                 $price = get_kit_price($_POST['stock_id'],
461                         $order->customer_currency, $order->sales_type,
462                         $order->price_factor, get_post('OrderDate'));
463                 $_POST['price'] = price_format($price);
464                 // default to the customer's discount %
465                 $_POST['Disc'] = percent_format($order->default_discount * 100);
466         }
467
468         qty_cells(null, 'qty', $_POST['qty'], null, null, $dec);
469
470         if ($order->trans_no!=0) {
471                 qty_cell($line_no==-1 ? 0 :$order->line_items[$line_no]->qty_done, false, $dec);
472         }
473
474         label_cell($units, '', 'units');
475
476         $str = amount_cells(null, 'price');
477
478         small_amount_cells(null, 'Disc', percent_format($_POST['Disc']), null, null, user_percent_dec());
479
480         $line_total = input_num('qty') * input_num('price') * (1 - input_num('Disc') / 100);
481
482         amount_cell($line_total, false, '','line_total');
483
484         if ($id!=-1)
485         {
486                 button_cell('UpdateItem', _("Update"),
487                                 _('Confirm changes'), ICON_UPDATE);
488                 button_cell('CancelItemChanges', _("Cancel"),
489                                 _('Cancel changes'), ICON_CANCEL);
490                 hidden('LineNo', $line_no);
491                 set_focus('qty');
492         }
493         else
494         {
495                 submit_cells('AddItem', _("Add Item"), "colspan=2",
496                     _('Add new item to document'), true);
497         }
498
499         end_row();
500 }
501
502 //--------------------------------------------------------------------------------
503
504 function display_delivery_details(&$order)
505 {
506         global $table_style2, $Ajax;
507
508         div_start('delivery');  
509
510         if (get_post('cash', 0)) {      // Direct payment sale
511                 display_heading(_('Cash payment'));
512                 start_table("$table_style2 width=60%");
513                 label_row(_("Deliver from Location:"), $order->location_name);
514
515                 hidden('Location', $order->Location);
516                 label_row(_("Cash account:"), $order->account_name);
517                 textarea_row(_("Comments:"), "Comments", $order->Comments, 31, 5);
518                 end_table();
519         } else {
520
521                 if ($order->trans_type==10)
522                 {
523                         $title = _("Delivery Details");
524                         $delname = _("Due Date").':';
525                 }
526                 elseif ($order->trans_type==13)
527                 {
528                         $title = _("Invoice Delivery Details");
529                         $delname = _("Invoice before").':';
530                 }
531                 else
532                 {
533                         $title = _("Order Delivery Details");
534                         $delname = _("Required Delivery Date").':';
535                 }
536                 display_heading($title);
537                 start_outer_table("$table_style2 width=90%");
538                 table_section(1);
539
540                 locations_list_row(_("Deliver from Location:"), 'Location', null, 
541                         false, true);
542                 if (list_updated('Location'))
543                         check_qoh($order);
544
545                 date_row($delname, 'delivery_date',
546                         $order->trans_type==30 ?  _('Enter requested day of delivery') : '', 
547                         $order->due_date, 0, 0, 0);
548                 text_row(_("Deliver To:"), 'deliver_to', $order->deliver_to, 40, 40,
549                         _('Additional identifier for delivery e.g. name of receiving person'));
550
551                 textarea_row(_("Address:"), 'delivery_address', $order->delivery_address, 35, 5,
552                         _('Delivery address. Default is address of customer branch'));
553                 text_row(_("Contact Phone Number:"), 'phone', $order->phone, 25, 25,
554                     _('Phone number of ordering person. Defaults to branch phone number'));
555
556                 table_section(2);
557
558                 text_row(_("Customer Reference:"), 'cust_ref', $order->cust_ref, 25, 25,
559                   _('Customer reference number for this order (if any)'));
560                 textarea_row(_("Comments:"), "Comments", $order->Comments, 31, 5);
561
562                 small_amount_row(_("Shipping Charge:"), 'freight_cost',
563                 price_format(get_post('freight_cost',0)));
564
565                 shippers_list_row(_("Shipping Company:"), 'ship_via', $order->ship_via);
566
567                 end_outer_table(1);
568         }
569         div_end();
570 }
571
572 function check_qoh($order) 
573 {
574         $msg = '';
575         foreach($order->line_items as $line_no => $line) {
576                 if (!is_inventory_item($line['stock_id'])) continue;
577                 $qoh = get_qoh_on_date($line->stock_id, $_POST['Location'], $_POST['OrderDate']);
578                 if ($line->qty_dispatched > $qoh)       {
579                         $msg .= $line->stock_id . " - " . $line->item_description . ": " .
580                                 _("Quantity On Hand") . " = " 
581                                 . number_format2($qoh, get_qty_dec($line->stock_id)) . '<br>';
582                 }
583         }
584         if (strlen($msg)) {
585                 display_error(_("The delivery cannot be processed because there is an insufficient quantity for item:")
586                         . '<br>'. $msg);
587                 return false;
588         }
589         return true;
590 }
591 ?>