Merged changes in main trunk up to 2.0.6 (see CHANGELOG)
[fa-stable.git] / sales / includes / sales_db.inc
1 <?php
2
3 include_once($path_to_root . "/includes/banking.inc");
4 include_once($path_to_root . "/includes/db/inventory_db.inc");
5 include_once($path_to_root . "/sales/includes/db/sales_order_db.inc");
6 include_once($path_to_root . "/sales/includes/db/sales_credit_db.inc");
7 include_once($path_to_root . "/sales/includes/db/sales_invoice_db.inc");
8 include_once($path_to_root . "/sales/includes/db/sales_delivery_db.inc");
9 include_once($path_to_root . "/sales/includes/db/sales_types_db.inc");
10 include_once($path_to_root . "/sales/includes/db/sales_points_db.inc");
11 include_once($path_to_root . "/sales/includes/db/custalloc_db.inc");
12 include_once($path_to_root . "/sales/includes/db/cust_trans_db.inc");
13 include_once($path_to_root . "/sales/includes/db/cust_trans_details_db.inc");
14 include_once($path_to_root . "/sales/includes/db/payment_db.inc");
15 include_once($path_to_root . "/sales/includes/db/branches_db.inc");
16 include_once($path_to_root . "/sales/includes/db/customers_db.inc");
17
18 //----------------------------------------------------------------------------------------
19 // $price in customer's currency
20 // $quantity is used as is (if it's neg it's neg, if it's pos it's pos)
21 // $std_cost is in home currency
22 // $show_or_hide 1 show this item in invoice/credit views, 0 to hide it (used for write-off items)
23 // $type is 10 (invoice) or 11 (credit)
24
25 function add_stock_move_customer($type, $stock_id, $trans_id, $location, $date_, $reference,
26         $quantity, $std_cost, $show_or_hide=1, $price=0, $discount_percent=0)
27 {
28         return add_stock_move($type, $stock_id, $trans_id, $location, $date_, $reference,
29                 $quantity, $std_cost, 0, $show_or_hide, $price, $discount_percent,
30                 "The customer stock movement record cannot be inserted");
31 }
32
33 //----------------------------------------------------------------------------------------
34 // add a debtor-related gl transaction
35 // $date_ is display date (non-sql)
36 // $amount is in CUSTOMER'S currency
37
38 function add_gl_trans_customer($type, $type_no, $date_, $account, $dimension, $dimension2,
39         $amount, $customer_id, $err_msg="", $rate=0)
40 {
41         if ($err_msg == "")
42                 $err_msg = "The customer GL transaction could not be inserted";
43
44         return add_gl_trans($type, $type_no, $date_, $account, $dimension, $dimension2, "", $amount,
45                 get_customer_currency($customer_id),
46                 payment_person_types::customer(), $customer_id, $err_msg, $rate);
47 }
48
49 //----------------------------------------------------------------------------------------
50
51 function get_price ($stock_id, $currency, $sales_type_id, $factor=null, $date=null)
52 {
53         if ($date == null)
54             $date = Today();
55
56         if ($factor === null) 
57         {
58                 $myrow = get_sales_type($sales_type_id);
59                 $factor = $myrow['factor'];
60         }
61             
62         $sql = "SELECT price
63                 FROM ".TB_PREF."prices
64                 WHERE stock_id = '" . $stock_id . "' "
65                 ." AND sales_type_id = " . $sales_type_id
66                 ." AND curr_abrev = '$currency'";
67
68         $msg = "There was a problem retrieving the pricing information for the part $stock_id for customer";
69         $result = db_query($sql, $msg);
70
71         if (db_num_rows($result) != 0) 
72         {
73                 $myrow = db_fetch_row($result);
74                 return $myrow[0];
75         }
76         if ($factor == 0) return false; // auto price calculations off
77
78         $base_id = get_base_sales_type();
79         if ($base_id <= 0) return 0; // auto price calculations off
80         
81     $home_curr = get_company_currency();
82
83     // get all prices which we can use to guess the price.
84     // alternative is make up to 2 additional sql queries
85         $sql = "SELECT price, curr_abrev, sales_type_id
86                 FROM ".TB_PREF."prices
87                 WHERE stock_id = '" . $stock_id . "' "
88                 ." AND (sales_type_id = " . $sales_type_id
89                 ." OR sales_type_id = " . $base_id.")"
90                 ." AND (curr_abrev = '$currency'"
91                 ." OR curr_abrev = '$home_curr')";
92
93         $result = db_query($sql, $msg);
94
95         $prices = array();
96         while($myrow = db_fetch($result)) 
97         {
98             $prices[$myrow['sales_type_id']][$myrow['curr_abrev']] = $myrow['price'];
99         }
100         
101         $rate = round(get_exchange_rate_from_home_currency($currency, $date),
102             user_exrate_dec());
103         $price = false;
104         
105         if (isset($prices[$sales_type_id][$home_curr])) 
106         {
107             $price = $prices[$sales_type_id][$home_curr] / $rate;
108         }
109         elseif (isset($prices[$base_id][$currency])) 
110         {
111             $price = $prices[$base_id][$currency] * $factor;
112         }
113         elseif (isset($prices[$base_id][$home_curr])) 
114         {
115             $price = $prices[$base_id][$home_curr] * $factor / $rate;
116         }
117         
118         return $price === false ? false : round($price, user_price_dec());
119 }
120 //----------------------------------------------------------------------------------------
121 //
122 //      Get price for given item or kit.
123 //  When $std==true price is calculated as a sum of all included stock items,
124 //      otherwise all prices set for kits and items are accepted.
125 //
126 function get_kit_price($item_code, $currency, $sales_type_id, $factor=null, 
127         $date=null, $std = false)
128 {
129         $kit_price = 0.00;
130         if (!$std) {
131                 $kit_price = get_price( $item_code, $currency, $sales_type_id, 
132                         $factor, $date);
133
134                 if ($kit_price !== false) {
135                         return $kit_price;
136                 }
137         }       
138         // no price for kit found, get total value of all items
139         $kit = get_item_kit($item_code);
140         
141         while($item = db_fetch($kit)) {
142                 if ($item['item_code'] != $item['stock_id']) {
143                         // foreign/kit code
144                         $kit_price += $item['quantity'] * get_kit_price( $item['stock_id'], 
145                                 $currency, $sales_type_id, $factor, $date, $std);
146
147                 } else {
148                         // stock item
149                         $kit_price += $item['quantity'] * get_price( $item['stock_id'], 
150                                 $currency, $sales_type_id, $factor, $date);
151                 }
152         }
153         return $kit_price;
154 }
155
156 //-----------------------------------------------------------------------------
157
158 function set_document_parent($cart)
159 {
160         $inv_no = key($cart->trans_no);
161
162         if (count($cart->src_docs) == 1) {
163
164         // if this child document has only one parent - update child link
165         $del_no = reset(array_keys($cart->src_docs));
166
167         $sql = 'UPDATE '.TB_PREF.'debtor_trans SET trans_link = ' . $del_no .
168                 ' WHERE type='.$cart->trans_type.' AND trans_no='. $inv_no ;
169         db_query($sql, 'Child document link cannot be updated');
170
171         }
172         if ($cart->trans_type != 10)
173                 return 0;
174
175         // the rest is batch invoice specific
176
177         foreach ($cart->line_items as $line) {
178                 if ($line->quantity != $line->qty_dispatched) {
179                         return 1;       // this is partial invoice
180                 }
181         }
182
183         $sql = 'UPDATE '.TB_PREF.'debtor_trans SET trans_link = ' . $inv_no .
184         ' WHERE type='.get_parent_type($cart->trans_type).' AND (';
185
186         $deliveries = array_keys($cart->src_docs);
187
188         foreach ($deliveries as $key=>$del)
189                 $deliveries[$key] = 'trans_no='.$del;
190
191         $sql .= implode(' OR ', $deliveries) . ')';
192         db_query($sql, 'Delivery links cannot be updated');
193
194         return 0; // batch or complete invoice
195 }
196
197 //--------------------------------------------------------------------------------------------------
198 function get_parent_type($type)
199 {
200         $parent_types = array( 11=>10, 10=>13, 13=>30 );
201         return isset($parent_types[$type]) ?  $parent_types[$type] : 0;
202 }
203
204 //--------------------------------------------------------------------------------------------------
205 function update_parent_line($doc_type, $line_id, $qty_dispatched)
206 {
207         $doc_type = get_parent_type($doc_type);
208
209 //      echo "update line: $line_id, $doc_type, $qty_dispatched";
210         if ($doc_type==0)
211                 return false;
212         else {
213                 if ($doc_type==30)
214                         $sql = "UPDATE ".TB_PREF."sales_order_details
215                                 SET qty_sent = qty_sent + $qty_dispatched
216                                 WHERE id=$line_id";
217                 else
218                         $sql = "UPDATE ".TB_PREF."debtor_trans_details
219                                 SET qty_done = qty_done + $qty_dispatched
220                                 WHERE id=$line_id";
221         }
222         db_query($sql, "The parent document detail record could not be updated");
223         return true;
224 }
225
226 //--------------------------------------------------------------------------------------------------
227 // find inventory location for given transaction
228 //
229 function get_location(&$cart)
230 {
231         $sql = "SELECT ".TB_PREF."locations.* FROM ".TB_PREF."stock_moves,"
232                 .TB_PREF."locations".
233                 " WHERE type=".$cart->trans_type.
234                 " AND trans_no=".key($cart->trans_no).
235                 " AND qty!=0 ".
236                 " AND ".TB_PREF."locations.loc_code=".TB_PREF."stock_moves.loc_code";
237         $result = db_query($sql, 'Retreiving inventory location');
238
239
240         if (db_num_rows($result)) {
241                 return db_fetch($result);
242         }
243         return null;
244 }
245 //--------------------------------------------------------------------------------------------------
246 // Generic read debtor transaction into cart
247 //
248 //      $trans_no - array of trans nums; special case trans_no==0 - new doc
249 //
250 function read_sales_trans($doc_type, $trans_no, &$cart)
251 {
252         if (!is_array($trans_no) && $trans_no)
253                         $trans_no = array($trans_no);
254
255         $cart->trans_type = $doc_type;
256         if (!$trans_no) { // new document
257                 $cart->trans_no = $trans_no;
258         } else {
259                 // read header data from first document
260                 $myrow = get_customer_trans($trans_no[0],$doc_type);
261                 if (count($trans_no)>1)
262                         $cart->trans_no = get_customer_trans_version($doc_type, $trans_no);
263                 else
264                         $cart->trans_no = array($trans_no[0]=>$myrow["version"]);
265
266                 $cart->set_sales_type($myrow["tpe"], $myrow["sales_type"], $myrow["tax_included"],0);
267
268                 $cart->set_customer($myrow["debtor_no"], $myrow["DebtorName"],
269                         $myrow["curr_code"], $myrow["discount"]);
270
271                 $cart->set_branch($myrow["branch_code"], $myrow["tax_group_id"],
272                         $myrow["tax_group_name"],       $myrow["phone"], $myrow["email"]);
273
274                 $cart->reference = $myrow["reference"];
275                 $cart->order_no = $myrow["order_"];
276                 $cart->trans_link = $myrow["trans_link"];
277                 $cart->due_date = sql2date($myrow["due_date"]);
278                 $cart->document_date = sql2date($myrow["tran_date"]);
279                 $cart->dimension_id = $myrow['dimension_id']; // added 2.1 Joe Hunt 2008-11-12
280                 $cart->dimension2_id = $myrow['dimension2_id'];
281                 $cart->Comments = '';
282                 foreach ( $trans_no as $trans ) {
283                         $coms =  get_comments($doc_type,$trans);
284                         while($row=db_fetch($coms)) {
285                                 $text = $row['memo_'];
286                                 if ($text!='') {
287                                         if ($cart->Comments!='')
288                                                 $cart->Comments .= "\n";
289                                         $cart->Comments .= $text;
290                                 }
291                         }
292                 }
293
294                 // FIX this should be calculated sum() for multiply parents
295
296                 $cart->set_delivery($myrow["ship_via"], $myrow["br_name"],
297                 $myrow["br_address"], $myrow["ov_freight"]);
298
299                 $location = 0;
300                 $myrow = get_location($cart); // find location from movement
301
302                 if($myrow!=null) {
303                         $cart->set_location($myrow['loc_code'], $myrow['location_name']);
304                 }
305
306                 $result = get_customer_trans_details($doc_type,$trans_no);
307                 if (db_num_rows($result) > 0) {
308                         for($line_no=0; $myrow = db_fetch($result); $line_no++) {
309                                 $cart->line_items[$line_no] = new line_details(
310                                         $myrow["stock_id"],$myrow["quantity"],
311                                         $myrow["unit_price"], $myrow["discount_percent"],
312                                         $myrow["qty_done"], $myrow["standard_cost"],
313                                         $myrow["StockDescription"],$myrow["id"], $myrow["debtor_trans_no"]);
314                         }
315                 }
316         } // !newdoc
317
318         return true;
319 }
320 //----------------------------------------------------------------------------------------
321 ?>