Merged last changes from stable.
[fa-stable.git] / sales / sales_order_entry.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 Sales Quotations
15 //      Entry/Modify Sales Order
16 //      Entry Direct Delivery
17 //      Entry Direct Invoice
18 //
19
20 $path_to_root = "..";
21 $page_security = 'SA_SALESORDER';
22
23 include_once($path_to_root . "/sales/includes/cart_class.inc");
24 include_once($path_to_root . "/includes/session.inc");
25 include_once($path_to_root . "/sales/includes/sales_ui.inc");
26 include_once($path_to_root . "/sales/includes/ui/sales_order_ui.inc");
27 include_once($path_to_root . "/sales/includes/sales_db.inc");
28 include_once($path_to_root . "/sales/includes/db/sales_types_db.inc");
29 include_once($path_to_root . "/reporting/includes/reporting.inc");
30
31 set_page_security( @$_SESSION['Items']->trans_type,
32         array(  ST_SALESORDER=>'SA_SALESORDER',
33                         ST_SALESQUOTE => 'SA_SALESQUOTE',
34                         ST_CUSTDELIVERY => 'SA_SALESDELIVERY',
35                         ST_SALESINVOICE => 'SA_SALESINVOICE'),
36         array(  'NewOrder' => 'SA_SALESORDER',
37                         'ModifyOrderNumber' => 'SA_SALESORDER',
38                         'AddedID' => 'SA_SALESORDER',
39                         'UpdatedID' => 'SA_SALESORDER',
40                         'NewQuotation' => 'SA_SALESQUOTE',
41                         'ModifyQuotationNumber' => 'SA_SALESQUOTE',
42                         'NewQuoteToSalesOrder' => 'SA_SALESQUOTE',
43                         'AddedQU' => 'SA_SALESQUOTE',
44                         'UpdatedQU' => 'SA_SALESQUOTE',
45                         'NewDelivery' => 'SA_SALESDELIVERY',
46                         'AddedDN' => 'SA_SALESDELIVERY', 
47                         'NewInvoice' => 'SA_SALESINVOICE',
48                         'AddedDI' => 'SA_SALESINVOICE'
49                         )
50 );
51
52 $js = '';
53
54 if ($use_popup_windows) {
55         $js .= get_js_open_window(900, 500);
56 }
57
58 if ($use_date_picker) {
59         $js .= get_js_date_picker();
60 }
61
62 if (isset($_GET['NewDelivery']) && is_numeric($_GET['NewDelivery'])) {
63
64         $_SESSION['page_title'] = _($help_context = "Direct Sales Delivery");
65         create_cart(ST_CUSTDELIVERY, $_GET['NewDelivery']);
66
67 } elseif (isset($_GET['NewInvoice']) && is_numeric($_GET['NewInvoice'])) {
68
69         $_SESSION['page_title'] = _($help_context = "Direct Sales Invoice");
70         create_cart(ST_SALESINVOICE, $_GET['NewInvoice']);
71
72 } elseif (isset($_GET['ModifyOrderNumber']) && is_numeric($_GET['ModifyOrderNumber'])) {
73
74         $help_context = 'Modifying Sales Order';
75         $_SESSION['page_title'] = sprintf( _("Modifying Sales Order # %d"), $_GET['ModifyOrderNumber']);
76         create_cart(ST_SALESORDER, $_GET['ModifyOrderNumber']);
77
78 } elseif (isset($_GET['ModifyQuotationNumber']) && is_numeric($_GET['ModifyQuotationNumber'])) {
79
80         $help_context = 'Modifying Sales Quotation';
81         $_SESSION['page_title'] = sprintf( _("Modifying Sales Quotation # %d"), $_GET['ModifyQuotationNumber']);
82         create_cart(ST_SALESQUOTE, $_GET['ModifyQuotationNumber']);
83
84 } elseif (isset($_GET['NewOrder'])) {
85
86         $_SESSION['page_title'] = _($help_context = "New Sales Order Entry");
87         create_cart(ST_SALESORDER, 0);
88 } elseif (isset($_GET['NewQuotation'])) {
89
90         $_SESSION['page_title'] = _($help_context = "New Sales Quotation Entry");
91         create_cart(ST_SALESQUOTE, 0);
92 } elseif (isset($_GET['NewQuoteToSalesOrder'])) {
93         $_SESSION['page_title'] = _($help_context = "Sales Order Entry");
94         create_cart(ST_SALESQUOTE, $_GET['NewQuoteToSalesOrder']);
95 }
96
97 page($_SESSION['page_title'], false, false, "", $js);
98
99 if (isset($_GET['ModifyOrderNumber']))
100         check_is_editable(ST_SALESORDER, $_GET['ModifyOrderNumber']);
101 elseif (isset($_GET['ModifyQuotationNumber']))
102         check_is_editable(ST_SALESQUOTE, $_GET['ModifyQuotationNumber']);
103
104 //-----------------------------------------------------------------------------
105
106 if (list_updated('branch_id')) {
107         // when branch is selected via external editor also customer can change
108         $br = get_branch(get_post('branch_id'));
109         $_POST['customer_id'] = $br['debtor_no'];
110         $Ajax->activate('customer_id');
111 }
112
113 if (isset($_GET['AddedID'])) {
114         $order_no = $_GET['AddedID'];
115         display_notification_centered(sprintf( _("Order # %d has been entered."),$order_no));
116
117         submenu_view(_("&View This Order"), ST_SALESORDER, $order_no);
118
119         submenu_print(_("&Print This Order"), ST_SALESORDER, $order_no, 'prtopt');
120         submenu_print(_("&Email This Order"), ST_SALESORDER, $order_no, null, 1);
121         set_focus('prtopt');
122         
123         submenu_option(_("Make &Delivery Against This Order"),
124                 "/sales/customer_delivery.php?OrderNumber=$order_no");
125
126         submenu_option(_("Work &Order Entry"),  "/manufacturing/work_order_entry.php?");
127
128         submenu_option(_("Enter a &New Order"), "/sales/sales_order_entry.php?NewOrder=0");
129
130         display_footer_exit();
131
132 } elseif (isset($_GET['UpdatedID'])) {
133         $order_no = $_GET['UpdatedID'];
134
135         display_notification_centered(sprintf( _("Order # %d has been updated."),$order_no));
136
137         submenu_view(_("&View This Order"), ST_SALESORDER, $order_no);
138
139         submenu_print(_("&Print This Order"), ST_SALESORDER, $order_no, 'prtopt');
140         submenu_print(_("&Email This Order"), ST_SALESORDER, $order_no, null, 1);
141         set_focus('prtopt');
142
143         submenu_option(_("Confirm Order Quantities and Make &Delivery"),
144                 "/sales/customer_delivery.php?OrderNumber=$order_no");
145
146         submenu_option(_("Select A Different &Order"),
147                 "/sales/inquiry/sales_orders_view.php?OutstandingOnly=1");
148
149         display_footer_exit();
150
151 } elseif (isset($_GET['AddedQU'])) {
152         $order_no = $_GET['AddedQU'];
153         display_notification_centered(sprintf( _("Quotation # %d has been entered."),$order_no));
154
155         submenu_view(_("&View This Quotation"), ST_SALESQUOTE, $order_no);
156
157         submenu_print(_("&Print This Quotation"), ST_SALESQUOTE, $order_no, 'prtopt');
158         submenu_print(_("&Email This Quotation"), ST_SALESQUOTE, $order_no, null, 1);
159         set_focus('prtopt');
160         
161         submenu_option(_("Make &Sales Order Against This Quotation"),
162                 "/sales/sales_order_entry.php?NewQuoteToSalesOrder=$order_no");
163
164         submenu_option(_("Enter a New &Quotation"),     "/sales/sales_order_entry.php?NewQuotation=0");
165
166         display_footer_exit();
167
168 } elseif (isset($_GET['UpdatedQU'])) {
169         $order_no = $_GET['UpdatedQU'];
170
171         display_notification_centered(sprintf( _("Quotation # %d has been updated."),$order_no));
172
173         submenu_view(_("&View This Quotation"), ST_SALESQUOTE, $order_no);
174
175         submenu_print(_("&Print This Quotation"), ST_SALESQUOTE, $order_no, 'prtopt');
176         submenu_print(_("&Email This Quotation"), ST_SALESQUOTE, $order_no, null, 1);
177         set_focus('prtopt');
178
179         submenu_option(_("Make &Sales Order Against This Quotation"),
180                 "/sales/sales_order_entry.php?NewQuoteToSalesOrder=$order_no");
181
182         submenu_option(_("Select A Different &Quotation"),
183                 "/sales/inquiry/sales_orders_view.php?type=".ST_SALESQUOTE);
184
185         display_footer_exit();
186 } elseif (isset($_GET['AddedDN'])) {
187         $delivery = $_GET['AddedDN'];
188
189         display_notification_centered(sprintf(_("Delivery # %d has been entered."),$delivery));
190
191         submenu_view(_("&View This Delivery"), ST_CUSTDELIVERY, $delivery);
192
193         submenu_print(_("&Print Delivery Note"), ST_CUSTDELIVERY, $delivery, 'prtopt');
194         submenu_print(_("&Email Delivery Note"), ST_CUSTDELIVERY, $delivery, null, 1);
195         submenu_print(_("P&rint as Packing Slip"), ST_CUSTDELIVERY, $delivery, 'prtopt', null, 1);
196         submenu_print(_("E&mail as Packing Slip"), ST_CUSTDELIVERY, $delivery, null, 1, 1);
197         set_focus('prtopt');
198
199         display_note(get_gl_view_str(ST_CUSTDELIVERY, $delivery, _("View the GL Journal Entries for this Dispatch")),0, 1);
200
201         submenu_option(_("Make &Invoice Against This Delivery"),
202                 "/sales/customer_invoice.php?DeliveryNumber=$delivery");
203
204         if ((isset($_GET['Type']) && $_GET['Type'] == 1))
205                 submenu_option(_("Enter a New Template &Delivery"),
206                         "/sales/inquiry/sales_orders_view.php?DeliveryTemplates=Yes");
207         else
208                 submenu_option(_("Enter a &New Delivery"), 
209                         "/sales/sales_order_entry.php?NewDelivery=0");
210
211         display_footer_exit();
212
213 } elseif (isset($_GET['AddedDI'])) {
214         $invoice = $_GET['AddedDI'];
215
216         display_notification_centered(sprintf(_("Invoice # %d has been entered."), $invoice));
217
218         submenu_view(_("&View This Invoice"), ST_SALESINVOICE, $invoice);
219
220         submenu_print(_("&Print Sales Invoice"), ST_SALESINVOICE, $invoice."-".ST_SALESINVOICE, 'prtopt');
221         submenu_print(_("&Email Sales Invoice"), ST_SALESINVOICE, $invoice."-".ST_SALESINVOICE, null, 1);
222         set_focus('prtopt');
223         
224         $sql = "SELECT trans_type_from, trans_no_from FROM ".TB_PREF."cust_allocations
225                         WHERE trans_type_to=".ST_SALESINVOICE." AND trans_no_to=".db_escape($invoice);
226         $result = db_query($sql, "could not retrieve customer allocation");
227         $row = db_fetch($result);
228         if ($row !== false)
229                 submenu_print(_("Print &Receipt"), $row['trans_type_from'], $row['trans_no_from']."-".$row['trans_type_from'], 'prtopt');
230
231         display_note(get_gl_view_str(ST_SALESINVOICE, $invoice, _("View the GL &Journal Entries for this Invoice")),0, 1);
232
233         if ((isset($_GET['Type']) && $_GET['Type'] == 1))
234                 submenu_option(_("Enter a &New Template Invoice"), 
235                         "/sales/inquiry/sales_orders_view.php?InvoiceTemplates=Yes");
236         else
237                 submenu_option(_("Enter a &New Direct Invoice"),
238                         "/sales/sales_order_entry.php?NewInvoice=0");
239
240         submenu_option(_("Add an Attachment"), "/admin/attachments.php?filterType=".ST_SALESINVOICE."&trans_no=$invoice");
241
242         display_footer_exit();
243 } else
244         check_edit_conflicts();
245 //-----------------------------------------------------------------------------
246
247 function copy_to_cart()
248 {
249         $cart = &$_SESSION['Items'];
250
251         $cart->reference = $_POST['ref'];
252
253         $cart->Comments =  $_POST['Comments'];
254
255         $cart->document_date = $_POST['OrderDate'];
256
257         $newpayment = false;
258
259         if (isset($_POST['payment']) && ($cart->payment != $_POST['payment'])) {
260                 $cart->payment = $_POST['payment'];
261                 $cart->payment_terms = get_payment_terms($_POST['payment']);
262                 $newpayment = true;
263         }
264         if ($cart->payment_terms['cash_sale']) {
265                 if ($newpayment) {
266                         $cart->due_date = $cart->document_date;
267                         $cart->phone = $cart->cust_ref = $cart->delivery_address = '';
268                         $cart->ship_via = 0;
269                         $cart->deliver_to = '';
270                         $cart->prep_amount = 0;
271                 }
272         } else {
273                 $cart->due_date = $_POST['delivery_date'];
274                 $cart->cust_ref = $_POST['cust_ref'];
275                 $cart->deliver_to = $_POST['deliver_to'];
276                 $cart->delivery_address = $_POST['delivery_address'];
277                 $cart->phone = $_POST['phone'];
278                 $cart->ship_via = $_POST['ship_via'];
279                 if (!$cart->trans_no || ($cart->trans_type == ST_SALESORDER && !$cart->is_started()))
280                         $cart->prep_amount = input_num('prep_amount', 0);
281         }
282         $cart->Location = $_POST['Location'];
283         $cart->freight_cost = input_num('freight_cost');
284         if (isset($_POST['email']))
285                 $cart->email =$_POST['email'];
286         else
287                 $cart->email = '';
288         $cart->customer_id      = $_POST['customer_id'];
289         $cart->Branch = $_POST['branch_id'];
290         $cart->sales_type = $_POST['sales_type'];
291
292         if ($cart->trans_type!=ST_SALESORDER && $cart->trans_type!=ST_SALESQUOTE) { // 2008-11-12 Joe Hunt
293                 $cart->dimension_id = $_POST['dimension_id'];
294                 $cart->dimension2_id = $_POST['dimension2_id'];
295         }
296         $cart->ex_rate = input_num('_ex_rate', null);
297 }
298
299 //-----------------------------------------------------------------------------
300
301 function copy_from_cart()
302 {
303         $cart = &$_SESSION['Items'];
304         $_POST['ref'] = $cart->reference;
305         $_POST['Comments'] = $cart->Comments;
306
307         $_POST['OrderDate'] = $cart->document_date;
308         $_POST['delivery_date'] = $cart->due_date;
309         $_POST['cust_ref'] = $cart->cust_ref;
310         $_POST['freight_cost'] = price_format($cart->freight_cost);
311
312         $_POST['deliver_to'] = $cart->deliver_to;
313         $_POST['delivery_address'] = $cart->delivery_address;
314         $_POST['phone'] = $cart->phone;
315         $_POST['Location'] = $cart->Location;
316         $_POST['ship_via'] = $cart->ship_via;
317
318         $_POST['customer_id'] = $cart->customer_id;
319
320         $_POST['branch_id'] = $cart->Branch;
321         $_POST['sales_type'] = $cart->sales_type;
322         $_POST['prep_amount'] = price_format($cart->prep_amount);
323         // POS 
324         $_POST['payment'] = $cart->payment;
325         if ($cart->trans_type!=ST_SALESORDER && $cart->trans_type!=ST_SALESQUOTE) { // 2008-11-12 Joe Hunt
326                 $_POST['dimension_id'] = $cart->dimension_id;
327                 $_POST['dimension2_id'] = $cart->dimension2_id;
328         }
329         $_POST['cart_id'] = $cart->cart_id;
330         $_POST['_ex_rate'] = $cart->ex_rate;
331 }
332 //--------------------------------------------------------------------------------
333
334 function line_start_focus() {
335   global        $Ajax;
336
337   $Ajax->activate('items_table');
338   set_focus('_stock_id_edit');
339 }
340
341 //--------------------------------------------------------------------------------
342 function can_process() {
343         global $Refs;
344
345         if (!get_post('customer_id')) 
346         {
347                 display_error(_("There is no customer selected."));
348                 set_focus('customer_id');
349                 return false;
350         } 
351         
352         if (!get_post('branch_id')) 
353         {
354                 display_error(_("This customer has no branch defined."));
355                 set_focus('branch_id');
356                 return false;
357         } 
358         
359         if (!is_date($_POST['OrderDate'])) {
360                 display_error(_("The entered date is invalid."));
361                 set_focus('OrderDate');
362                 return false;
363         }
364         if ($_SESSION['Items']->trans_type!=ST_SALESORDER && $_SESSION['Items']->trans_type!=ST_SALESQUOTE && !is_date_in_fiscalyear($_POST['OrderDate'])) {
365                 display_error(_("The entered date is out of fiscal year or is closed for further data entry."));
366                 set_focus('OrderDate');
367                 return false;
368         }
369         if (count($_SESSION['Items']->line_items) == 0) {
370                 display_error(_("You must enter at least one non empty item line."));
371                 set_focus('AddItem');
372                 return false;
373         }
374         if ($_SESSION['Items']->payment_terms['cash_sale'] == 0) {
375                 if (!$_SESSION['Items']->is_started() && ($_SESSION['Items']->payment_terms['days_before_due'] < 0) && ((input_num('prep_amount')<=0) ||
376                         input_num('prep_amount')>$_SESSION['Items']->get_trans_total())) {
377                         display_error(_("Pre-payment required have to be positive and less than total amount."));
378                         set_focus('prep_amount');
379                         return false;
380                 }
381                 if (strlen($_POST['deliver_to']) <= 1) {
382                         display_error(_("You must enter the person or company to whom delivery should be made to."));
383                         set_focus('deliver_to');
384                         return false;
385                 }
386
387
388                 if ($_SESSION['Items']->trans_type != ST_SALESQUOTE && strlen($_POST['delivery_address']) <= 1) {
389                         display_error( _("You should enter the street address in the box provided. Orders cannot be accepted without a valid street address."));
390                         set_focus('delivery_address');
391                         return false;
392                 }
393
394                 if ($_POST['freight_cost'] == "")
395                         $_POST['freight_cost'] = price_format(0);
396
397                 if (!check_num('freight_cost',0)) {
398                         display_error(_("The shipping cost entered is expected to be numeric."));
399                         set_focus('freight_cost');
400                         return false;
401                 }
402                 if (!is_date($_POST['delivery_date'])) {
403                         if ($_SESSION['Items']->trans_type==ST_SALESQUOTE)
404                                 display_error(_("The Valid date is invalid."));
405                         else    
406                                 display_error(_("The delivery date is invalid."));
407                         set_focus('delivery_date');
408                         return false;
409                 }
410                 //if (date1_greater_date2($_SESSION['Items']->document_date, $_POST['delivery_date'])) {
411                 if (date1_greater_date2($_POST['OrderDate'], $_POST['delivery_date'])) {
412                         if ($_SESSION['Items']->trans_type==ST_SALESQUOTE)
413                                 display_error(_("The requested valid date is before the date of the quotation."));
414                         else    
415                                 display_error(_("The requested delivery date is before the date of the order."));
416                         set_focus('delivery_date');
417                         return false;
418                 }
419         }
420         else
421         {
422                 if (!db_has_cash_accounts())
423                 {
424                         display_error(_("You need to define a cash account for your Sales Point."));
425                         return false;
426                 }       
427         }       
428         if (!$Refs->is_valid($_POST['ref'])) {
429                 display_error(_("You must enter a reference."));
430                 set_focus('ref');
431                 return false;
432         }
433         if (!db_has_currency_rates($_SESSION['Items']->customer_currency, $_POST['OrderDate']))
434                 return false;
435         
436         if ($_SESSION['Items']->get_items_total() < 0) {
437                 display_error("Invoice total amount cannot be less than zero.");
438                 return false;
439         }
440         return true;
441 }
442
443 //-----------------------------------------------------------------------------
444
445 if (isset($_POST['update'])) {
446         copy_to_cart();
447         $Ajax->activate('items_table');
448 }
449
450 if (isset($_POST['ProcessOrder']) && can_process()) {
451         copy_to_cart();
452         $modified = ($_SESSION['Items']->trans_no != 0);
453         $so_type = $_SESSION['Items']->so_type;
454
455         $ret = $_SESSION['Items']->write(1);
456         if ($ret == -1)
457         {
458                 display_error(_("The entered reference is already in use."));
459                 $ref = get_next_reference($_SESSION['Items']->trans_type);
460                 if ($ref != $_SESSION['Items']->reference)
461                 {
462                         display_error(_("The reference number field has been increased. Please save the document again."));
463                         $_POST['ref'] = $_SESSION['Items']->reference = $ref;
464                         $Ajax->activate('ref');
465                 }       
466                 set_focus('ref');
467         }
468         else
469         {
470                 if (count($messages)) { // abort on failure or error messages are lost
471                         $Ajax->activate('_page_body');
472                         display_footer_exit();
473                 }
474                 $trans_no = key($_SESSION['Items']->trans_no);
475                 $trans_type = $_SESSION['Items']->trans_type;
476                 new_doc_date($_SESSION['Items']->document_date);
477                 processing_end();
478                 if ($modified) {
479                         if ($trans_type == ST_SALESQUOTE)
480                                 meta_forward($_SERVER['PHP_SELF'], "UpdatedQU=$trans_no");
481                         else    
482                                 meta_forward($_SERVER['PHP_SELF'], "UpdatedID=$trans_no");
483                 } elseif ($trans_type == ST_SALESORDER) {
484                         meta_forward($_SERVER['PHP_SELF'], "AddedID=$trans_no");
485                 } elseif ($trans_type == ST_SALESQUOTE) {
486                         meta_forward($_SERVER['PHP_SELF'], "AddedQU=$trans_no");
487                 } elseif ($trans_type == ST_SALESINVOICE) {
488                         meta_forward($_SERVER['PHP_SELF'], "AddedDI=$trans_no&Type=$so_type");
489                 } else {
490                         meta_forward($_SERVER['PHP_SELF'], "AddedDN=$trans_no&Type=$so_type");
491                 }
492         }       
493 }
494
495 //--------------------------------------------------------------------------------
496
497 function check_item_data()
498 {
499         global $SysPrefs, $allow_negative_prices;
500         
501         $is_inventory_item = is_inventory_item(get_post('stock_id'));
502         if(!get_post('stock_id_text', true)) {
503                 display_error( _("Item description cannot be empty."));
504                 set_focus('stock_id_edit');
505                 return false;
506         }
507         elseif (!check_num('qty', 0) || !check_num('Disc', 0, 100)) {
508                 display_error( _("The item could not be updated because you are attempting to set the quantity ordered to less than 0, or the discount percent to more than 100."));
509                 set_focus('qty');
510                 return false;
511         } elseif (!check_num('price', 0) && (!$allow_negative_prices || $is_inventory_item)) {
512                 display_error( _("Price for inventory item must be entered and can not be less than 0"));
513                 set_focus('price');
514                 return false;
515         } elseif (isset($_POST['LineNo']) && isset($_SESSION['Items']->line_items[$_POST['LineNo']])
516             && !check_num('qty', $_SESSION['Items']->line_items[$_POST['LineNo']]->qty_done)) {
517
518                 set_focus('qty');
519                 display_error(_("You attempting to make the quantity ordered a quantity less than has already been delivered. The quantity delivered cannot be modified retrospectively."));
520                 return false;
521         } // Joe Hunt added 2008-09-22 -------------------------
522         elseif ($is_inventory_item && $_SESSION['Items']->trans_type!=ST_SALESORDER && $_SESSION['Items']->trans_type!=ST_SALESQUOTE 
523                 && !$SysPrefs->allow_negative_stock())
524         {
525                 $qoh = get_qoh_on_date($_POST['stock_id'], $_POST['Location'], $_POST['OrderDate']);
526                 if (input_num('qty') > $qoh)
527                 {
528                         $stock = get_item($_POST['stock_id']);
529                         display_error(_("The delivery cannot be processed because there is an insufficient quantity for item:") .
530                                 " " . $stock['stock_id'] . " - " . $stock['description'] . " - " .
531                                 _("Quantity On Hand") . " = " . number_format2($qoh, get_qty_dec($_POST['stock_id'])));
532                         return false;
533                 }
534                 return true;
535         }
536         $cost_home = get_standard_cost(get_post('stock_id')); // Added 2011-03-27 Joe Hunt
537         $cost = $cost_home / get_exchange_rate_from_home_currency($_SESSION['Items']->customer_currency, $_SESSION['Items']->document_date);
538         if (input_num('price') < $cost)
539         {
540                 $dec = user_price_dec();
541                 $curr = $_SESSION['Items']->customer_currency;
542                 $price = number_format2(input_num('price'), $dec);
543                 if ($cost_home == $cost)
544                         $std_cost = number_format2($cost_home, $dec);
545                 else
546                 {
547                         $price = $curr . " " . $price;
548                         $std_cost = $curr . " " . number_format2($cost, $dec);
549                 }
550                 display_warning(sprintf(_("Price %s is below Standard Cost %s"), $price, $std_cost));
551         }       
552         return true;
553 }
554
555 //--------------------------------------------------------------------------------
556
557 function handle_update_item()
558 {
559         if ($_POST['UpdateItem'] != '' && check_item_data()) {
560                 $_SESSION['Items']->update_cart_item($_POST['LineNo'],
561                  input_num('qty'), input_num('price'),
562                  input_num('Disc') / 100, $_POST['item_description'] );
563         }
564         page_modified();
565   line_start_focus();
566 }
567
568 //--------------------------------------------------------------------------------
569
570 function handle_delete_item($line_no)
571 {
572     if ($_SESSION['Items']->some_already_delivered($line_no) == 0) {
573             $_SESSION['Items']->remove_from_cart($line_no);
574     } else {
575         display_error(_("This item cannot be deleted because some of it has already been delivered."));
576     }
577     line_start_focus();
578 }
579
580 //--------------------------------------------------------------------------------
581
582 function handle_new_item()
583 {
584
585         if (!check_item_data()) {
586                         return;
587         }
588         add_to_order($_SESSION['Items'], get_post('stock_id'), input_num('qty'),
589                 input_num('price'), input_num('Disc') / 100, get_post('stock_id_text'));
590
591         unset($_POST['_stock_id_edit'], $_POST['stock_id']);
592         page_modified();
593         line_start_focus();
594 }
595
596 //--------------------------------------------------------------------------------
597
598 function  handle_cancel_order()
599 {
600         global $path_to_root, $Ajax;
601
602
603         if ($_SESSION['Items']->trans_type == ST_CUSTDELIVERY) {
604                 display_notification(_("Direct delivery entry has been cancelled as requested."), 1);
605                 submenu_option(_("Enter a New Sales Delivery"), "/sales/sales_order_entry.php?NewDelivery=1");
606         } elseif ($_SESSION['Items']->trans_type == ST_SALESINVOICE) {
607                 display_notification(_("Direct invoice entry has been cancelled as requested."), 1);
608                 submenu_option(_("Enter a New Sales Invoice"),  "/sales/sales_order_entry.php?NewInvoice=1");
609         } elseif ($_SESSION['Items']->trans_type == ST_SALESQUOTE)
610         {
611                 delete_sales_order(key($_SESSION['Items']->trans_no), $_SESSION['Items']->trans_type);
612                 display_notification(_("This sales quotation has been cancelled as requested."), 1);
613                 submenu_option(_("Enter a New Sales Quotation"), "/sales/sales_order_entry.php?NewQuotation=Yes");
614         } else { // sales order
615                 if ($_SESSION['Items']->trans_no != 0) {
616                         $order_no = key($_SESSION['Items']->trans_no);
617                         if (sales_order_has_deliveries($order_no))
618                         {
619                                 close_sales_order($order_no);
620                                 display_notification(_("Undelivered part of order has been cancelled as requested."), 1);
621                                 submenu_option(_("Select Another Sales Order for Edition"), "/sales/inquiry/sales_orders_view.php?type=".ST_SALESORDER);
622                         } else {
623                                 delete_sales_order(key($_SESSION['Items']->trans_no), $_SESSION['Items']->trans_type);
624
625                                 display_notification(_("This sales order has been cancelled as requested."), 1);
626                                 submenu_option(_("Enter a New Sales Order"), "/sales/sales_order_entry.php?NewOrder=Yes");
627                         }
628                 } else {
629                         processing_end();
630                         meta_forward($path_to_root.'/index.php','application=orders');
631                 }
632         }
633         $Ajax->activate('_page_body');
634         processing_end();
635         display_footer_exit();
636 }
637
638 //--------------------------------------------------------------------------------
639
640 function create_cart($type, $trans_no)
641
642         global $Refs;
643
644         if (!$_SESSION['SysPrefs']->db_ok) // create_cart is called before page() where the check is done
645                 return;
646
647         processing_start();
648
649         if (isset($_GET['NewQuoteToSalesOrder']))
650         {
651                 $trans_no = $_GET['NewQuoteToSalesOrder'];
652                 $doc = new Cart(ST_SALESQUOTE, $trans_no, true);
653                 $doc->Comments = _("Sales Quotation") . " # " . $trans_no;
654                 $_SESSION['Items'] = $doc;
655         }       
656         elseif($type != ST_SALESORDER && $type != ST_SALESQUOTE && $trans_no != 0) { // this is template
657
658                 $doc = new Cart(ST_SALESORDER, array($trans_no));
659                 $doc->trans_type = $type;
660                 $doc->trans_no = 0;
661                 $doc->document_date = new_doc_date();
662                 if ($type == ST_SALESINVOICE) {
663                         $doc->due_date = get_invoice_duedate($doc->payment, $doc->document_date);
664                         $doc->pos = get_sales_point(user_pos());
665                 } else
666                         $doc->due_date = $doc->document_date;
667                 $doc->reference = $Refs->get_next($doc->trans_type);
668                 //$doc->Comments='';
669                 foreach($doc->line_items as $line_no => $line) {
670                         $doc->line_items[$line_no]->qty_done = 0;
671                 }
672                 $_SESSION['Items'] = $doc;
673         } else
674                 $_SESSION['Items'] = new Cart($type, array($trans_no));
675         copy_from_cart();
676 }
677
678 //--------------------------------------------------------------------------------
679
680 if (isset($_POST['CancelOrder']))
681         handle_cancel_order();
682
683 $id = find_submit('Delete');
684 if ($id!=-1)
685         handle_delete_item($id);
686
687 if (isset($_POST['UpdateItem']))
688         handle_update_item();
689
690 if (isset($_POST['AddItem']))
691         handle_new_item();
692
693 if (isset($_POST['CancelItemChanges'])) {
694         line_start_focus();
695 }
696
697 //--------------------------------------------------------------------------------
698 check_db_has_stock_items(_("There are no inventory items defined in the system."));
699
700 check_db_has_customer_branches(_("There are no customers, or there are no customers with branches. Please define customers and customer branches."));
701
702 if ($_SESSION['Items']->trans_type == ST_SALESINVOICE) {
703         $idate = _("Invoice Date:");
704         $orderitems = _("Sales Invoice Items");
705         $deliverydetails = _("Enter Delivery Details and Confirm Invoice");
706         $cancelorder = _("Cancel Invoice");
707         $porder = _("Place Invoice");
708 } elseif ($_SESSION['Items']->trans_type == ST_CUSTDELIVERY) {
709         $idate = _("Delivery Date:");
710         $orderitems = _("Delivery Note Items");
711         $deliverydetails = _("Enter Delivery Details and Confirm Dispatch");
712         $cancelorder = _("Cancel Delivery");
713         $porder = _("Place Delivery");
714 } elseif ($_SESSION['Items']->trans_type == ST_SALESQUOTE) {
715         $idate = _("Quotation Date:");
716         $orderitems = _("Sales Quotation Items");
717         $deliverydetails = _("Enter Delivery Details and Confirm Quotation");
718         $cancelorder = _("Cancel Quotation");
719         $porder = _("Place Quotation");
720         $corder = _("Commit Quotations Changes");
721 } else {
722         $idate = _("Order Date:");
723         $orderitems = _("Sales Order Items");
724         $deliverydetails = _("Enter Delivery Details and Confirm Order");
725         $cancelorder = _("Cancel Order");
726         $porder = _("Place Order");
727         $corder = _("Commit Order Changes");
728 }
729 start_form();
730
731 hidden('cart_id');
732 $customer_error = display_order_header($_SESSION['Items'], !$_SESSION['Items']->is_started(), $idate);
733
734 if ($customer_error == "") {
735         start_table(TABLESTYLE, "width=80%", 10);
736         echo "<tr><td>";
737         display_order_summary($orderitems, $_SESSION['Items'], true);
738         echo "</td></tr>";
739         echo "<tr><td>";
740         display_delivery_details($_SESSION['Items']);
741         echo "</td></tr>";
742         end_table(1);
743
744         if ($_SESSION['Items']->trans_no == 0) {
745
746                 submit_center_first('ProcessOrder', $porder,
747                     _('Check entered data and save document'), 'default');
748                 submit_js_confirm('CancelOrder', _('You are about to void this Document.\nDo you want to continue?'));
749         } else {
750                 if ($_SESSION['Items']->trans_type==ST_SALESORDER)
751                         submit_js_confirm('CancelOrder', _('You are about to cancel undelivered part of this order.\nDo you want to continue?'));
752                 submit_center_first('ProcessOrder', $corder,
753                     _('Validate changes and update document'), 'default');
754         }
755
756         submit_center_last('CancelOrder', $cancelorder,
757            _('Cancels document entry or removes sales order when editing an old document'));
758 } else {
759         display_error($customer_error);
760 }
761
762 end_form();
763 end_page();
764 ?>