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