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