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