Sending location email when below reorder also in Itmes Transfer and Adjustment
[fa-stable.git] / sales / includes / db / sales_order_db.inc
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 function add_sales_order(&$order)
14 {
15         global $loc_notification, $path_to_root, $Refs;
16
17         begin_transaction();
18         hook_db_prewrite($order, $order->trans_type);
19         $order_no = get_next_trans_no($order->trans_type);
20         $del_date = date2sql($order->due_date);
21         $order_type = 0; // this is default on new order
22         $total = $order->get_trans_total();
23         $sql = "INSERT INTO ".TB_PREF."sales_orders (order_no, type, debtor_no, trans_type, branch_code, customer_ref, reference, comments, ord_date,
24                 order_type, ship_via, deliver_to, delivery_address, contact_phone,
25                 freight_cost, from_stk_loc, delivery_date, payment_terms, total)
26                 VALUES (" .db_escape($order_no) . "," .db_escape($order_type) . "," . db_escape($order->customer_id) .
27                  ", " .db_escape($order->trans_type) . "," .db_escape($order->Branch) . ", ".
28                         db_escape($order->cust_ref) .",". 
29                         db_escape($order->reference) .",". 
30                         db_escape($order->Comments) .",'" . 
31                         date2sql($order->document_date) . "', " .
32                         db_escape($order->sales_type) . ", " .
33                         db_escape($order->ship_via)."," . 
34                         db_escape($order->deliver_to) . "," .
35                         db_escape($order->delivery_address) . ", " .
36                         db_escape($order->phone) . ", " . 
37                         db_escape($order->freight_cost) .", " . 
38                         db_escape($order->Location) .", " .
39                         db_escape($del_date) . "," .
40                         db_escape($order->payment) . "," .
41                         db_escape($total). ")";
42
43         db_query($sql, "order Cannot be Added");
44
45         $order->trans_no = array($order_no=>0);
46
47         if ($loc_notification == 1)
48         {
49                 include_once($path_to_root . "/inventory/includes/inventory_db.inc");
50                 $st_ids = array();
51                 $st_names = array();
52                 $st_num = array();
53                 $st_reorder = array();
54         }
55         foreach ($order->line_items as $line)
56         {
57                 if ($loc_notification == 1 && is_inventory_item($line->stock_id))
58                         $loc = calculate_reorder_level($order->Location, $line, $st_ids, $st_names, $st_num, $st_reorder); 
59
60                 $sql = "INSERT INTO ".TB_PREF."sales_order_details (order_no, trans_type, stk_code, description, unit_price, quantity, discount_percent) VALUES (";
61                 $sql .= $order_no . ",".$order->trans_type .
62                                 ",".db_escape($line->stock_id).", "
63                                 .db_escape($line->item_description).", $line->price,
64                                 $line->quantity,
65                                 $line->discount_percent)";
66                 db_query($sql, "order Details Cannot be Added");
67
68         // Now mark quotation line as processed
69                 if ($order->trans_type == ST_SALESORDER && $line->src_id)
70                         update_parent_line(ST_SALESORDER, $line->src_id, $line->qty_dispatched); // clear all the quote despite all or the part was ordered
71         } /* inserted line items into sales order details */
72         add_audit_trail($order->trans_type, $order_no, $order->document_date);
73         $Refs->save($order->trans_type, $order_no, $order->reference);
74
75         hook_db_postwrite($order, $order->trans_type);
76         commit_transaction();
77
78         if ($loc_notification == 1 && count($st_ids) > 0)
79                 send_reorder_email($loc, $st_ids, $st_names, $st_num, $st_reorder);
80         return $order_no;
81 }
82
83 //----------------------------------------------------------------------------------------
84
85 function delete_sales_order($order_no, $trans_type)
86 {
87         begin_transaction();
88         hook_db_prevoid($trans_type, $order_no);
89
90         $sql = "DELETE FROM ".TB_PREF."sales_orders WHERE order_no=" . db_escape($order_no) 
91                 . " AND trans_type=".db_escape($trans_type);
92
93         db_query($sql, "order Header Delete");
94
95         $sql = "DELETE FROM ".TB_PREF."sales_order_details WHERE order_no =" 
96                 .db_escape($order_no) . " AND trans_type=".db_escape($trans_type);
97         db_query($sql, "order Detail Delete");
98
99         delete_reference($trans_type, $order_no);
100
101         add_audit_trail($trans_type, $order_no, Today(), _("Deleted."));
102         commit_transaction();
103 }
104
105 //----------------------------------------------------------------------------------------
106 // Mark changes in sales_order_details
107 //
108 function update_sales_order_version($order)
109 {
110   foreach ($order as $so_num => $so_ver) {
111   $sql= 'UPDATE '.TB_PREF.'sales_orders SET version=version+1 WHERE order_no='. db_escape($so_num).
112         ' AND version='.$so_ver . " AND trans_type=30";
113   db_query($sql, 'Concurrent editing conflict while sales order update');
114   }
115 }
116
117 //----------------------------------------------------------------------------------------
118
119 function update_sales_order($order)
120 {
121         global $loc_notification, $path_to_root, $Refs;
122
123         $del_date = date2sql($order->due_date);
124         $ord_date = date2sql($order->document_date);
125         $order_no =  key($order->trans_no);
126         $version= current($order->trans_no);
127         $total = $order->get_trans_total();
128
129         begin_transaction();
130         hook_db_prewrite($order, $order->trans_type);
131
132         $sql = "UPDATE ".TB_PREF."sales_orders SET type =".db_escape($order->so_type)." ,
133                 debtor_no = " . db_escape($order->customer_id) . ",
134                 branch_code = " . db_escape($order->Branch) . ",
135                 customer_ref = ". db_escape($order->cust_ref) .",
136                 reference = ". db_escape($order->reference) .",
137                 comments = ". db_escape($order->Comments) .",
138                 ord_date = " . db_escape($ord_date) . ",
139                 order_type = " .db_escape($order->sales_type) . ",
140                 ship_via = " . db_escape($order->ship_via) .",
141                 deliver_to = " . db_escape($order->deliver_to) . ",
142                 delivery_address = " . db_escape($order->delivery_address) . ",
143                 contact_phone = " .db_escape($order->phone) . ",
144                 freight_cost = " .db_escape($order->freight_cost) .",
145                 from_stk_loc = " .db_escape($order->Location) .",
146                 delivery_date = " .db_escape($del_date). ",
147                 version = ".($version+1).",
148                 payment_terms = " .db_escape($order->payment). ",
149                 total = ". db_escape($total) ."
150          WHERE order_no=" . db_escape($order_no) ."
151          AND trans_type=".$order->trans_type." AND version=".$version;
152         db_query($sql, "order Cannot be Updated, this can be concurrent edition conflict");
153
154         $id_tokeep = array();
155         foreach ($order->line_items as $line) {
156                 array_push($id_tokeep , $line->id);
157         }
158         $id_list = implode(', ', $id_tokeep);
159         
160         $sql = "DELETE FROM ".TB_PREF."sales_order_details WHERE order_no =" . db_escape($order_no) . " AND trans_type=".$order->trans_type;
161         $sql .= " AND id NOT IN ($id_list)";
162
163         db_query($sql, "Old order Cannot be Deleted");
164
165         if ($loc_notification == 1)
166         {
167                 include_once($path_to_root . "/inventory/includes/inventory_db.inc");
168                 $st_ids = array();
169                 $st_names = array();
170                 $st_num = array();
171                 $st_reorder = array();
172         }
173         foreach ($order->line_items as $line)
174         {
175                 if ($loc_notification == 1 && is_inventory_item($line->stock_id))
176                         $loc = calculate_reorder_level($order->Location, $line, $st_ids, $st_names, $st_num, $st_reorder); 
177                 if($line->id) {
178                         $sql = "UPDATE ".TB_PREF."sales_order_details
179                                                 SET description = ".db_escape($line->item_description) . ", 
180                                                                 unit_price = ".db_escape($line->price) . ",
181                                                                 quantity = ".db_escape($line->quantity) . ",
182                                                                 discount_percent = ".db_escape($line->discount_percent) . "
183                                                 WHERE id = {$line->id}";
184                 }
185                 else {
186                 $sql = "INSERT INTO ".TB_PREF."sales_order_details
187                  (id, order_no, trans_type, stk_code,  description, unit_price, quantity,
188                   discount_percent, qty_sent)
189                  VALUES (";
190                 $sql .= db_escape($line->id ? $line->id : 0) . ","
191                   .$order_no . ",".$order->trans_type.","
192                   .db_escape($line->stock_id) . ","
193                   .db_escape($line->item_description) . ", "
194                   .db_escape($line->price) . ", "
195                   .db_escape($line->quantity) . ", "
196                   .db_escape($line->discount_percent) . ", "
197                   .db_escape($line->qty_done) ." )";
198                 }
199
200                 db_query($sql, "Old order Cannot be Inserted");
201
202         } /* inserted line items into sales order details */
203
204         add_audit_trail($order->trans_type, $order_no, $order->document_date, _("Updated."));
205         $Refs->save($order->trans_type, $order_no, $order->reference);
206
207         hook_db_postwrite($order, $order->trans_type);
208         commit_transaction();
209         if ($loc_notification == 1 && count($st_ids) > 0)
210                 send_reorder_email($loc, $st_ids, $st_names, $st_num, $st_reorder);
211 }
212
213 //----------------------------------------------------------------------------------------
214
215 function get_sales_order_header($order_no, $trans_type)
216 {
217         $sql = "SELECT sorder.*, "
218           ."cust.name, "
219           ."cust.curr_code, "
220           ."cust.address, "
221           ."loc.location_name, "
222           ."cust.discount, "
223           ."stype.sales_type, "
224           ."stype.id AS sales_type_id, "
225           ."stype.tax_included, "
226           ."stype.factor, "
227           ."ship.shipper_name, "
228           ."tax_group.name AS tax_group_name , "
229           ."tax_group.id AS tax_group_id, "
230           ."cust.tax_id "
231         ."FROM ".TB_PREF."sales_orders sorder LEFT JOIN ".TB_PREF."shippers ship ON  ship.shipper_id = sorder.ship_via,"
232           .TB_PREF."debtors_master cust,"
233           .TB_PREF."sales_types stype, "
234           .TB_PREF."tax_groups tax_group, "
235           .TB_PREF."cust_branch branch,"
236           .TB_PREF."locations loc
237         WHERE sorder.order_type=stype.id
238                 AND branch.branch_code = sorder.branch_code
239                 AND branch.tax_group_id = tax_group.id
240                 AND sorder.debtor_no = cust.debtor_no
241                 AND loc.loc_code = sorder.from_stk_loc
242                 AND sorder.trans_type = " . db_escape($trans_type) ."
243                 AND sorder.order_no = " . db_escape($order_no );
244
245         $result = db_query($sql, "order Retreival");
246
247         $num = db_num_rows($result);
248         if ($num > 1)
249         {
250                 display_warning("You have duplicate document in database: (type:$trans_type, number:$order_no).");
251         }
252         else if ($num == 1)
253         {
254                 return db_fetch($result);
255         }
256         else
257                 display_warning("You have missing or invalid sales document in database (type:$trans_type, number:$order_no).");
258
259 }
260
261 //----------------------------------------------------------------------------------------
262
263 function get_sales_order_details($order_no, $trans_type) {
264         $sql = "SELECT id, stk_code, unit_price, "
265                 .TB_PREF."sales_order_details.description,"
266                 .TB_PREF."sales_order_details.quantity,
267                   discount_percent,
268                   qty_sent as qty_done, "
269                 .TB_PREF."stock_master.units,"
270                 .TB_PREF."stock_master.mb_flag,"
271                 .TB_PREF."stock_master.material_cost + "
272                         .TB_PREF."stock_master.labour_cost + "
273                         .TB_PREF."stock_master.overhead_cost AS standard_cost
274         FROM ".TB_PREF."sales_order_details, ".TB_PREF."stock_master
275         WHERE ".TB_PREF."sales_order_details.stk_code = ".TB_PREF."stock_master.stock_id
276         AND order_no =" . db_escape($order_no) 
277                 ." AND trans_type = " . db_escape($trans_type) . " ORDER BY id";
278
279         return db_query($sql, "Retreive order Line Items");
280 }
281 //----------------------------------------------------------------------------------------
282
283 function read_sales_order($order_no, &$order, $trans_type)
284 {
285
286         $myrow = get_sales_order_header($order_no, $trans_type);
287
288         $order->trans_type = $myrow['trans_type'];
289         $order->so_type =  $myrow["type"];
290         $order->trans_no = array($order_no=> $myrow["version"]);
291
292         $order->set_customer($myrow["debtor_no"], $myrow["name"],
293           $myrow["curr_code"], $myrow["discount"], $myrow["payment_terms"]);
294
295         $order->set_branch($myrow["branch_code"], $myrow["tax_group_id"],
296           $myrow["tax_group_name"], $myrow["contact_phone"]);
297
298         $order->set_sales_type($myrow["sales_type_id"], $myrow["sales_type"], 
299             $myrow["tax_included"], $myrow["factor"]); // no default price calculations on edit
300
301         $order->set_location($myrow["from_stk_loc"], $myrow["location_name"]);
302
303         $order->set_delivery($myrow["ship_via"], $myrow["deliver_to"],
304           $myrow["delivery_address"], $myrow["freight_cost"]);
305
306         $order->cust_ref = $myrow["customer_ref"];
307         $order->sales_type =$myrow["order_type"];
308         $order->reference = $myrow["reference"];
309         $order->Comments = $myrow["comments"];
310         $order->due_date = sql2date($myrow["delivery_date"]);
311         $order->document_date = sql2date($myrow["ord_date"]);
312
313         $result = get_sales_order_details($order_no, $order->trans_type);
314         if (db_num_rows($result) > 0)
315         {
316                 $line_no=0;
317                 while ($myrow = db_fetch($result))
318                 {
319                         $order->add_to_cart($line_no,$myrow["stk_code"],$myrow["quantity"],
320                                 $myrow["unit_price"], $myrow["discount_percent"],
321                                 $myrow["qty_done"], $myrow["standard_cost"], $myrow["description"], $myrow["id"] );
322                 $line_no++;
323                 }
324         }
325
326         return true;
327 }
328
329 //----------------------------------------------------------------------------------------
330
331 function sales_order_has_deliveries($order_no)
332 {
333         $sql = "SELECT SUM(qty_sent) FROM ".TB_PREF.
334         "sales_order_details WHERE order_no=".db_escape($order_no)
335         ." AND trans_type=".ST_SALESORDER;
336
337         $result = db_query($sql, "could not query for sales order usage");
338
339         $row = db_fetch_row($result);
340
341         if ($row[0] > 0)
342                 return true;  // 2010-04-21 added check for eventually voided deliveries, Joe Hunt
343         $sql = "SELECT order_ FROM ".TB_PREF."debtor_trans WHERE type=".ST_CUSTDELIVERY." AND order_=".db_escape($order_no);
344         $result = db_query($sql,"The related delivery notes could not be retreived");
345         return (db_num_rows($result) > 0);      
346 }
347
348 //----------------------------------------------------------------------------------------
349
350 function close_sales_order($order_no)
351 {
352         // set the quantity of each item to the already sent quantity. this will mark item as closed.
353         $sql = "UPDATE ".TB_PREF."sales_order_details
354                 SET quantity = qty_sent WHERE order_no = ".db_escape($order_no)
355                 ." AND trans_type=".ST_SALESORDER;
356
357         db_query($sql, "The sales order detail record could not be updated");
358 }
359
360 //---------------------------------------------------------------------------------------------------------------
361
362 function get_invoice_duedate($terms, $invdate)
363 {
364         if (!is_date($invdate))
365         {
366                 return new_doc_date();
367         }
368         
369         $myrow = get_payment_terms($terms);
370         
371         if (!$myrow)
372                 return $invdate;
373
374         if ($myrow['day_in_following_month'] > 0)
375                 $duedate = add_days(end_month($invdate), $myrow['day_in_following_month']);
376         else
377                 $duedate = add_days($invdate, $myrow['days_before_due']);
378         return $duedate;
379 }
380
381 function get_customer_to_order($customer_id) {
382
383         // Now check to ensure this account is not on hold */
384         $sql = "SELECT cust.name, 
385                   cust.address, "
386                   .TB_PREF."credit_status.dissallow_invoices, 
387                   cust.sales_type AS salestype,
388                   cust.dimension_id,
389                   cust.dimension2_id,
390                   stype.sales_type,
391                   stype.tax_included,
392                   stype.factor,
393                   cust.curr_code,
394                   cust.discount,
395                   cust.payment_terms,
396                   cust.pymt_discount,
397                   cust.credit_limit - Sum(IFNULL(IF(trans.type=11 OR trans.type=12 OR trans.type=2,
398                         -1, 1) * (ov_amount + ov_gst + ov_freight + ov_freight_tax + ov_discount),0)) as cur_credit
399                 FROM ".TB_PREF."debtors_master cust
400                   LEFT JOIN ".TB_PREF."debtor_trans trans ON trans.type!=".ST_CUSTDELIVERY." AND trans.debtor_no = cust.debtor_no,"
401                   .TB_PREF."credit_status, "
402                   .TB_PREF."sales_types stype
403                 WHERE cust.sales_type=stype.id
404                         AND cust.credit_status=".TB_PREF."credit_status.id
405                         AND cust.debtor_no = ".db_escape($customer_id)
406                 ." GROUP by cust.debtor_no";
407
408         $result =db_query($sql,"Customer Record Retreive");
409         return  db_fetch($result);
410 }
411
412 function get_branch_to_order($customer_id, $branch_id) {
413
414         // the branch was also selected from the customer selection so default the delivery details from the customer branches table cust_branch. The order process will ask for branch details later anyway
415                 $sql = "SELECT ".TB_PREF."cust_branch.br_name, "
416                         .TB_PREF."cust_branch.br_address, "
417                         .TB_PREF."cust_branch.br_post_address, "
418                         ." default_location, location_name, default_ship_via, "
419                         .TB_PREF."tax_groups.name AS tax_group_name, "
420                         .TB_PREF."tax_groups.id AS tax_group_id
421                         FROM ".TB_PREF."cust_branch, "
422                           .TB_PREF."tax_groups, "
423                           .TB_PREF."locations
424                         WHERE ".TB_PREF."cust_branch.tax_group_id = ".TB_PREF."tax_groups.id
425                                 AND ".TB_PREF."locations.loc_code=default_location
426                                 AND ".TB_PREF."cust_branch.branch_code=".db_escape($branch_id)."
427                                 AND ".TB_PREF."cust_branch.debtor_no = ".db_escape($customer_id);
428
429             return db_query($sql,"Customer Branch Record Retreive");
430 }
431
432 function get_sql_for_sales_orders_view($selected_customer, $trans_type, $trans_no, $filter, 
433         $stock_item=null, $from='', $to='', $ref='', $location='', $customer_id=ALL_TEXT)
434 {
435
436         $sql = "SELECT 
437                         sorder.order_no,
438                         sorder.reference,
439                         debtor.name,
440                         branch.br_name,"
441                         .($filter=='InvoiceTemplates' 
442                                 || $filter=='DeliveryTemplates' ?
443                          "sorder.comments, " : "sorder.customer_ref, ")
444                         ."sorder.ord_date,
445                         sorder.delivery_date,
446                         sorder.deliver_to,
447                         Sum(line.unit_price*line.quantity*(1-line.discount_percent))+freight_cost AS OrderValue,
448                         sorder.type,
449                         debtor.curr_code,
450                         Sum(line.qty_sent) AS TotDelivered,
451                         Sum(line.quantity) AS TotQuantity
452                 FROM ".TB_PREF."sales_orders as sorder, "
453                         .TB_PREF."sales_order_details as line, "
454                         .TB_PREF."debtors_master as debtor, "
455                         .TB_PREF."cust_branch as branch
456                         WHERE sorder.order_no = line.order_no
457                         AND sorder.trans_type = line.trans_type
458                         AND sorder.trans_type = ".db_escape($trans_type)."
459                         AND sorder.debtor_no = debtor.debtor_no
460                         AND sorder.branch_code = branch.branch_code
461                         AND debtor.debtor_no = branch.debtor_no";
462
463         if (isset($trans_no) && $trans_no != "")
464         {
465                 // search orders with number like 
466                 $number_like = "%".$trans_no;
467                 $sql .= " AND sorder.order_no LIKE ".db_escape($number_like);
468 //                              ." GROUP BY sorder.order_no";
469         }
470         elseif ($ref != "")
471         {
472                 // search orders with reference like 
473                 $number_like = "%".$ref."%";
474                 $sql .= " AND sorder.reference LIKE ".db_escape($number_like);
475 //                              ." GROUP BY sorder.order_no";
476         }
477         else    // ... or select inquiry constraints
478         {
479                 if ($filter!='DeliveryTemplates' && $filter!='InvoiceTemplates' && $filter!='OutstandingOnly')
480                 {
481                         $date_after = date2sql($from);
482                         $date_before = date2sql($to);
483
484                         $sql .=  " AND sorder.ord_date >= '$date_after'"
485                                         ." AND sorder.ord_date <= '$date_before'";
486                 }
487         }
488                 if ($trans_type == ST_SALESQUOTE && !check_value('show_all'))
489                         $sql .= " AND sorder.delivery_date >= '".date2sql(Today())."' AND line.qty_sent=0"; // show only outstanding, not realized quotes
490
491                 if ($selected_customer != -1)
492                         $sql .= " AND sorder.debtor_no=".db_escape($selected_customer);
493
494                 if (isset($stock_item))
495                         $sql .= " AND line.stk_code=".db_escape($stock_item);
496
497                 if ($location)
498                         $sql .= " AND sorder.from_stk_loc = ".db_escape($location);
499
500                 if ($filter=='OutstandingOnly')
501                         $sql .= " AND line.qty_sent < line.quantity";
502
503                 elseif ($filter=='InvoiceTemplates' || $filter=='DeliveryTemplates')
504                         $sql .= " AND sorder.type=1";
505                         
506                 //Chaiatanya : New Filter
507                 if ($customer_id != ALL_TEXT)
508                         $sql .= " AND sorder.debtor_no = ".db_escape($customer_id);             
509
510                 $sql .= " GROUP BY sorder.order_no,
511                                         sorder.debtor_no,
512                                         sorder.branch_code,
513                                         sorder.customer_ref,
514                                         sorder.ord_date,
515                                         sorder.deliver_to";
516         return $sql;
517 }
518 ?>