[0000085] Fixed session conflicts during document edition in multiply browser tabs.
[fa-stable.git] / sales / sales_order_entry.php
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 //-----------------------------------------------------------------------------
13 //
14 //      Entry/Modify Sales Order
15 //      Entry Direct Delivery
16 //      Entry Direct Invoice
17 //
18
19 $page_security = 1;
20 $path_to_root="..";
21
22 include_once($path_to_root . "/sales/includes/cart_class.inc");
23 include_once($path_to_root . "/includes/session.inc");
24 include_once($path_to_root . "/sales/includes/sales_ui.inc");
25 include_once($path_to_root . "/sales/includes/ui/sales_order_ui.inc");
26 include_once($path_to_root . "/sales/includes/sales_db.inc");
27 include_once($path_to_root . "/sales/includes/db/sales_types_db.inc");
28 include_once($path_to_root . "/reporting/includes/reporting.inc");
29 $js = '';
30
31 editor_redirect( array(
32         'customer_id' => $path_to_root.'/sales/manage/customers.php?debtor_no='.get_post('customer_id'),
33         'branch_id' => $path_to_root.'/sales/manage/customer_branches.php?branch_id='.get_post('branch_id'),
34         ));
35
36 editor_return( array(
37         'customer_id'=>'customer_id',
38         'branch_id'=>'branch_id'));
39
40 if ($use_popup_windows) {
41         $js .= get_js_open_window(900, 500);
42 }
43
44 if ($use_date_picker) {
45         $js .= get_js_date_picker();
46 }
47
48 if (isset($_GET['NewDelivery']) && is_numeric($_GET['NewDelivery'])) {
49
50         $_SESSION['page_title'] = _("Direct Sales Delivery");
51         create_cart(13, $_GET['NewDelivery']);
52
53 } elseif (isset($_GET['NewInvoice']) && is_numeric($_GET['NewInvoice'])) {
54
55         $_SESSION['page_title'] = _("Direct Sales Invoice");
56         create_cart(10, $_GET['NewInvoice']);
57
58 } elseif (isset($_GET['ModifyOrderNumber']) && is_numeric($_GET['ModifyOrderNumber'])) {
59
60         $help_page_title = _('Modifying Sales Order');
61         $_SESSION['page_title'] = sprintf( _("Modifying Sales Order # %d"), $_GET['ModifyOrderNumber']);
62         create_cart(30, $_GET['ModifyOrderNumber']);
63
64 } elseif (isset($_GET['NewOrder'])) {
65
66         $_SESSION['page_title'] = _("New Sales Order Entry");
67         create_cart(30, 0);
68 }
69
70 page($_SESSION['page_title'], false, false, "", $js);
71 //-----------------------------------------------------------------------------
72
73 if (isset($_GET['AddedID'])) {
74         $order_no = $_GET['AddedID'];
75
76         display_notification_centered(sprintf( _("Order # %d has been entered."),$order_no));
77
78         display_note(get_trans_view_str(30, $order_no, _("&View This Order")));
79         echo '<br>';
80         display_note(print_document_link($order_no, _("&Print This Order"), true, 30));
81
82         hyperlink_params($path_to_root . "/sales/customer_delivery.php",
83                 _("Make &Delivery Against This Order"), "OrderNumber=$order_no");
84
85         hyperlink_params($_SERVER['PHP_SELF'], _("Enter a &New Order"), "NewOrder=0");
86
87         display_footer_exit();
88
89 } elseif (isset($_GET['UpdatedID'])) {
90         $order_no = $_GET['UpdatedID'];
91
92         display_notification_centered(sprintf( _("Order # %d has been updated."),$order_no));
93
94         display_note(get_trans_view_str(30, $order_no, _("&View This Order")));
95         echo '<br>';
96         display_note(print_document_link($order_no, _("&Print This Order"), true, 30));
97
98         hyperlink_params($path_to_root . "/sales/customer_delivery.php",
99                 _("Confirm Order Quantities and Make &Delivery"), "OrderNumber=$order_no");
100
101         hyperlink_params($path_to_root . "/sales/inquiry/sales_orders_view.php",
102                 _("Select A Different &Order"), "OutstandingOnly=1");
103
104         display_footer_exit();
105
106 } elseif (isset($_GET['AddedDN'])) {
107         $delivery = $_GET['AddedDN'];
108
109         display_notification_centered(sprintf(_("Delivery # %d has been entered."),$delivery));
110
111         display_note(get_trans_view_str(13, $delivery, _("&View This Delivery")));
112         echo '<br>';
113         display_note(print_document_link($delivery, _("&Print Delivery Note"), true, 13));
114
115         hyperlink_params($path_to_root . "/sales/customer_invoice.php",
116         _("Make &Invoice Against This Delivery"), "DeliveryNumber=$delivery");
117
118         if ((isset($_GET['Type']) && $_GET['Type'] == 1))
119         hyperlink_params("inquiry/sales_orders_view.php",
120                 _("Enter a New Template &Delivery"), "DeliveryTemplates=Yes");
121         else
122         hyperlink_params($_SERVER['PHP_SELF'], _("Enter a &New Delivery"), "NewDelivery=0");
123
124         display_footer_exit();
125
126 } elseif (isset($_GET['AddedDI'])) {
127         $invoice = $_GET['AddedDI'];
128
129         display_notification_centered(sprintf(_("Invoice # %d has been entered."),$invoice));
130
131         display_note(get_trans_view_str(10, $invoice, _("&View This Invoice")));
132         echo '<br>';
133         display_note(print_document_link($invoice, _("&Print Sales Invoice"), true, 10));
134
135         if ((isset($_GET['Type']) && $_GET['Type'] == 1))
136         hyperlink_params("inquiry/sales_orders_view.php",
137                 _("Enter a &New Template Invoice"), "InvoiceTemplates=Yes");
138         else
139         hyperlink_params($_SERVER['PHP_SELF'], _("Enter a &New Direct Invoice"), "NewInvoice=0");
140
141         display_footer_exit();
142 } else
143         check_edit_conflicts();
144
145 //-----------------------------------------------------------------------------
146
147 function copy_to_cart()
148 {
149         $cart = &$_SESSION['Items'];
150
151         if ($cart->trans_type!=30) {
152                 $cart->reference = $_POST['ref'];
153         } 
154         $cart->Comments =  $_POST['Comments'];
155
156         $cart->document_date = $_POST['OrderDate'];
157         if ($cart->trans_type == 10)
158                 $cart->cash = $_POST['cash']; 
159         if ($cart->cash) {
160                 $cart->due_date = $cart->document_date;
161                 $cart->phone = $cart->cust_ref = $cart->delivery_address = '';
162                 $cart->freight_cost = 0;
163                 $cart->ship_via = 1;
164                 $cart->deliver_to = '';//$_POST['deliver_to'];
165         } else {
166                 $cart->due_date = $_POST['delivery_date'];
167                 $cart->cust_ref = $_POST['cust_ref'];
168                 $cart->freight_cost = input_num('freight_cost');
169                 $cart->deliver_to = $_POST['deliver_to'];
170                 $cart->delivery_address = $_POST['delivery_address'];
171                 $cart->phone = $_POST['phone'];
172                 $cart->Location = $_POST['Location'];
173                 $cart->ship_via = $_POST['ship_via'];
174         }
175         if (isset($_POST['email']))
176                 $cart->email =$_POST['email'];
177         else
178                 $cart->email = '';
179         $cart->customer_id      = $_POST['customer_id'];
180         $cart->Branch = $_POST['branch_id'];
181         $cart->sales_type = $_POST['sales_type'];
182         // POS
183         if ($cart->trans_type!=30) { // 2008-11-12 Joe Hunt
184                 $cart->dimension_id = $_POST['dimension_id'];
185                 $cart->dimension2_id = $_POST['dimension2_id'];
186         }       
187 }
188
189 //-----------------------------------------------------------------------------
190
191 function copy_from_cart()
192 {
193         $cart = &$_SESSION['Items'];
194         if ($cart->trans_type!=30) {
195                 $_POST['ref'] = $cart->reference;
196         }
197         $_POST['Comments'] = $cart->Comments;
198
199         $_POST['OrderDate'] = $cart->document_date;
200         $_POST['delivery_date'] = $cart->due_date;
201         $_POST['cust_ref'] = $cart->cust_ref;
202         $_POST['freight_cost'] = price_format($cart->freight_cost);
203
204         $_POST['deliver_to'] = $cart->deliver_to;
205         $_POST['delivery_address'] = $cart->delivery_address;
206         $_POST['phone'] = $cart->phone;
207         $_POST['Location'] = $cart->Location;
208         $_POST['ship_via'] = $cart->ship_via;
209
210         $_POST['customer_id'] = $cart->customer_id;
211
212         $_POST['branch_id'] = $cart->Branch;
213         $_POST['sales_type'] = $cart->sales_type;
214         // POS 
215         if ($cart->trans_type == 10)
216                 $_POST['cash'] = $cart->cash;
217         if ($cart->trans_type!=30) { // 2008-11-12 Joe Hunt
218                 $_POST['dimension_id'] = $cart->dimension_id;
219                 $_POST['dimension2_id'] = $cart->dimension2_id;
220         }       
221         $_POST['cart_id'] = $cart->cart_id;
222                 
223 }
224 //--------------------------------------------------------------------------------
225
226 function line_start_focus() {
227   global        $Ajax;
228
229   $Ajax->activate('items_table');
230   set_focus('_stock_id_edit');
231 }
232 //--------------------------------------------------------------------------------
233
234 function can_process() {
235         if (!is_date($_POST['OrderDate'])) {
236                 display_error(_("The entered date is invalid."));
237                 set_focus('OrderDate');
238                 return false;
239         }
240         if ($_SESSION['Items']->trans_type!=30 && !is_date_in_fiscalyear($_POST['OrderDate'])) {
241                 display_error(_("The entered date is not in fiscal year"));
242                 set_focus('OrderDate');
243                 return false;
244         }
245         if (count($_SESSION['Items']->line_items) == 0) {
246                 display_error(_("You must enter at least one non empty item line."));
247                 set_focus('AddItem');
248                 return false;
249         }
250         if ($_SESSION['Items']->cash == 0) {
251         if (strlen($_POST['deliver_to']) <= 1) {
252                 display_error(_("You must enter the person or company to whom delivery should be made to."));
253                 set_focus('deliver_to');
254                 return false;
255         }
256
257                 if (strlen($_POST['delivery_address']) <= 1) {
258                         display_error( _("You should enter the street address in the box provided. Orders cannot be accepted without a valid street address."));
259                         set_focus('delivery_address');
260                         return false;
261                 }
262
263                 if ($_POST['freight_cost'] == "")
264                         $_POST['freight_cost'] = price_format(0);
265
266                 if (!check_num('freight_cost',0)) {
267                         display_error(_("The shipping cost entered is expected to be numeric."));
268                         set_focus('freight_cost');
269                         return false;
270                 }
271                 if (!is_date($_POST['delivery_date'])) {
272                         display_error(_("The delivery date is invalid."));
273                         set_focus('delivery_date');
274                         return false;
275                 }
276                 //if (date1_greater_date2($_SESSION['Items']->document_date, $_POST['delivery_date'])) {
277                 if (date1_greater_date2($_POST['OrderDate'], $_POST['delivery_date'])) {
278                         display_error(_("The requested delivery date is before the date of the order."));
279                         set_focus('delivery_date');
280                         return false;
281                 }
282         }
283         if ($_SESSION['Items']->trans_type != 30 && !references::is_valid($_POST['ref'])) {
284                 display_error(_("You must enter a reference."));
285                 set_focus('ref');
286                 return false;
287         }
288         return true;
289 }
290
291 //-----------------------------------------------------------------------------
292
293 if (isset($_POST['ProcessOrder']) && can_process()) {
294         copy_to_cart();
295
296         $modified = ($_SESSION['Items']->trans_no != 0);
297         $so_type = $_SESSION['Items']->so_type;
298         $_SESSION['Items']->write(1);
299         if (count($messages)) { // abort on failure or error messages are lost
300                 $Ajax->activate('_page_body');
301                 display_footer_exit();
302         }
303         $trans_no = key($_SESSION['Items']->trans_no);
304         $trans_type = $_SESSION['Items']->trans_type;
305
306         processing_end();
307         if ($modified) {
308                 meta_forward($_SERVER['PHP_SELF'], "UpdatedID=$trans_no");
309         } elseif ($trans_type == 30) {
310                 meta_forward($_SERVER['PHP_SELF'], "AddedID=$trans_no");
311         } elseif ($trans_type == 10) {
312                 meta_forward($_SERVER['PHP_SELF'], "AddedDI=$trans_no&Type=$so_type");
313         } else {
314                 meta_forward($_SERVER['PHP_SELF'], "AddedDN=$trans_no&Type=$so_type");
315         }
316 }
317
318 //--------------------------------------------------------------------------------
319
320 function check_item_data()
321 {
322         if (!check_num('qty', 0) || !check_num('Disc', 0, 100)) {
323                 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."));
324                 set_focus('qty');
325                 return false;
326         } elseif (!check_num('price', 0)) {
327                 display_error( _("Price for item must be entered and can not be less than 0"));
328                 set_focus('price');
329                 return false;
330         } elseif (isset($_POST['LineNo']) && isset($_SESSION['Items']->line_items[$_POST['LineNo']])
331             && !check_num('qty', $_SESSION['Items']->line_items[$_POST['LineNo']]->qty_done)) {
332
333                 set_focus('qty');
334                 display_error(_("You attempting to make the quantity ordered a quantity less than has already been delivered. The quantity delivered cannot be modified retrospectively."));
335                 return false;
336         } // Joe Hunt added 2008-09-22 -------------------------
337         elseif ($_SESSION['Items']->trans_type!=30 && !sys_prefs::allow_negative_stock() &&
338                 is_inventory_item($_POST['stock_id']))
339         {
340                 $qoh = get_qoh_on_date($_POST['stock_id'], $_POST['Location'], $_POST['OrderDate']);
341                 if (input_num('qty') > $qoh)
342                 {
343                         $stock = get_item($_POST['stock_id']);
344                         display_error(_("The delivery cannot be processed because there is an insufficient quantity for item:") .
345                                 " " . $stock['stock_id'] . " - " . $stock['description'] . " - " .
346                                 _("Quantity On Hand") . " = " . number_format2($qoh, get_qty_dec($_POST['stock_id'])));
347                         return false;
348                 }
349                 return true;
350         }
351         return true;
352 }
353
354 //--------------------------------------------------------------------------------
355
356 function handle_update_item()
357 {
358         if ($_POST['UpdateItem'] != '' && check_item_data()) {
359                 $_SESSION['Items']->update_cart_item($_POST['LineNo'],
360                  input_num('qty'), input_num('price'),
361                  input_num('Disc') / 100 );
362         }
363   line_start_focus();
364 }
365
366 //--------------------------------------------------------------------------------
367
368 function handle_delete_item($line_no)
369 {
370     if ($_SESSION['Items']->some_already_delivered($line_no) == 0) {
371             $_SESSION['Items']->remove_from_cart($line_no);
372     } else {
373         display_error(_("This item cannot be deleted because some of it has already been delivered."));
374     }
375     line_start_focus();
376 }
377
378 //--------------------------------------------------------------------------------
379
380 function handle_new_item()
381 {
382
383         if (!check_item_data()) {
384                         return;
385         }
386         add_to_order($_SESSION['Items'], $_POST['stock_id'], input_num('qty'),
387                 input_num('price'), input_num('Disc') / 100);
388         $_POST['_stock_id_edit'] = $_POST['stock_id']   = "";
389         line_start_focus();
390 }
391
392 //--------------------------------------------------------------------------------
393
394 function  handle_cancel_order()
395 {
396         global $path_to_root, $Ajax;
397
398
399         if ($_SESSION['Items']->trans_type == 13) {
400                         display_note(_("Direct delivery entry has been cancelled as requested."), 1);
401                         hyperlink_params($path_to_root . "/sales/sales_order_entry.php",
402                                         _("Enter a New Sales Delivery"), SID . "&NewDelivery=0");
403         } elseif ($_SESSION['Items']->trans_type == 10) {
404                         display_note(_("Direct invoice entry has been cancelled as requested."), 1);
405                         hyperlink_params($path_to_root . "/sales/sales_order_entry.php",
406                                         _("Enter a New Sales Delivery"), SID . "&NewDelivery=0");
407         } else {
408                 if ($_SESSION['Items']->trans_no != 0) {
409                         if (sales_order_has_deliveries(key($_SESSION['Items']->trans_no)))
410                                 display_error(_("This order cannot be cancelled because some of it has already been invoiced or dispatched. However, the line item quantities may be modified."));
411                         else {
412                                 delete_sales_order(key($_SESSION['Items']->trans_no));
413
414                         display_note(_("This sales order has been cancelled as requested."), 1);
415                                 hyperlink_params($path_to_root . "/sales/sales_order_entry.php",
416                                 _("Enter a New Sales Order"), SID . "&NewOrder=Yes");
417                         }
418                 } else {
419                         processing_end();
420                         meta_forward($path_to_root.'/index.php?application=orders');
421                 }
422         }
423         $Ajax->activate('_page_body');
424         processing_end();
425         br(1);
426         end_page();
427         exit;
428 }
429
430 //--------------------------------------------------------------------------------
431
432 function create_cart($type, $trans_no)
433 {
434         processing_start();
435         $doc_type = $type;
436
437         if($type != 30 && $trans_no != 0) { // this is template
438                 $doc_type = 30;
439
440                 $doc = new Cart(30, array($trans_no));
441                 $doc->trans_type = $type;
442                 $doc->trans_no = 0;
443                 $doc->document_date = Today(); // 2006-06-15. Added so Invoices and Deliveries get current day
444                 if ($type == 10) {
445                         $doc->due_date = get_invoice_duedate($doc->customer_id, $doc->document_date);
446                         $doc->pos = user_pos();
447                         $pos = get_sales_point($doc->pos);
448                         $doc->cash = $pos['cash_sale'];
449                         if (!$pos['cash_sale'] || !$pos['credit_sale']) 
450                                 $doc->pos = -1; // mark not editable payment type
451                         else
452                                 $doc->cash = date_diff($doc->due_date, Today(), 'd')<2;
453                 } else
454                         $doc->due_date = $doc->document_date;
455                 $doc->reference = references::get_next($doc->trans_type);
456                 $doc->Comments='';
457                 foreach($doc->line_items as $line_no => $line) {
458                         $doc->line_items[$line_no]->qty_done = 0;
459                 }
460                 $_SESSION['Items'] = $doc;
461         } else
462                 $_SESSION['Items'] = new Cart($type,array($trans_no));
463         copy_from_cart();
464 }
465
466 //--------------------------------------------------------------------------------
467
468 if (isset($_POST['CancelOrder']))
469         handle_cancel_order();
470
471 $id = find_submit('Delete');
472 if ($id!=-1)
473         handle_delete_item($id);
474
475 if (isset($_POST['UpdateItem']))
476         handle_update_item();
477
478 if (isset($_POST['AddItem']))
479         handle_new_item();
480
481 if (isset($_POST['CancelItemChanges'])) {
482         line_start_focus();
483 }
484
485 //--------------------------------------------------------------------------------
486 check_db_has_stock_items(_("There are no inventory items defined in the system."));
487
488 check_db_has_customer_branches(_("There are no customers, or there are no customers with branches. Please define customers and customer branches."));
489
490 if ($_SESSION['Items']->trans_type == 10) {
491         $idate = _("Invoice Date:");
492         $orderitems = _("Sales Invoice Items");
493         $deliverydetails = _("Enter Delivery Details and Confirm Invoice");
494         $cancelorder = _("Cancel Invoice");
495         $porder = _("Place Invoice");
496 } elseif ($_SESSION['Items']->trans_type == 13) {
497         $idate = _("Delivery Date:");
498         $orderitems = _("Delivery Note Items");
499         $deliverydetails = _("Enter Delivery Details and Confirm Dispatch");
500         $cancelorder = _("Cancel Delivery");
501         $porder = _("Place Delivery");
502 } else {
503         $idate = _("Order Date:");
504         $orderitems = _("Sales Order Items");
505         $deliverydetails = _("Enter Delivery Details and Confirm Order");
506         $cancelorder = _("Cancel Order");
507         $porder = _("Place Order");
508         $corder = _("Commit Order Changes");
509 }
510 start_form(false, true);
511 hidden('cart_id');
512
513 $customer_error = display_order_header($_SESSION['Items'],
514         ($_SESSION['Items']->any_already_delivered() == 0), $idate);
515
516 if ($customer_error == "") {
517         start_table("$table_style width=80%", 10);
518         echo "<tr><td>";
519         display_order_summary($orderitems, $_SESSION['Items'], true);
520         echo "</td></tr>";
521         echo "<tr><td>";
522         display_delivery_details($_SESSION['Items']);
523         echo "</td></tr>";
524         end_table(1);
525
526         if ($_SESSION['Items']->trans_no == 0) {
527
528                 submit_center_first('ProcessOrder', $porder,
529                     _('Check entered data and save document'), true, ICON_OK);
530         } else {
531                 submit_center_first('ProcessOrder', $corder,
532                     _('Validate changes and update document'), true, ICON_OK);
533         }
534
535         submit_center_last('CancelOrder', $cancelorder,
536            _('Cancels document entry or removes sales order when editing an old document'),
537            true, ICON_CANCEL);
538 } else {
539         display_error($customer_error);
540 }
541 end_form();
542 end_page();
543
544 ?>