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