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