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