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