Bug 5676: Currency stored in MySQL DOUBLE Type causes strange error. Fixed by explici...
[fa-stable.git] / sales / includes / db / custalloc_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
14 function add_cust_allocation($amount, $trans_type_from, $trans_no_from,
15         $trans_type_to, $trans_no_to, $person_id, $date_)
16 {
17         $date = date2sql($date_);
18         $sql = "INSERT INTO ".TB_PREF."cust_allocations (
19                 amt, date_alloc,
20                 trans_type_from, trans_no_from, trans_no_to, trans_type_to, person_id)
21                 VALUES ($amount, '$date', ".db_escape($trans_type_from).", ".db_escape($trans_no_from).", ".db_escape($trans_no_to)
22                 .", ".db_escape($trans_type_to).", ".db_escape($person_id).")";
23
24         db_query($sql, "A customer allocation could not be added to the database");
25 }
26
27 //----------------------------------------------------------------------------------------
28
29
30 function delete_cust_allocation($trans_id)
31 {
32         $sql = "DELETE FROM ".TB_PREF."cust_allocations WHERE id = ".db_escape($trans_id);
33         return db_query($sql, "The existing allocation $trans_id could not be deleted");
34 }
35
36 //----------------------------------------------------------------------------------------
37
38 function get_cust_allocation($trans_id)
39 {
40         $sql = "SELECT * FROM ".TB_PREF."cust_allocations WHERE id = ".db_escape($trans_id);
41         return db_fetch(db_query($sql), "Cannot retrieve customer allocation $trans_id");
42 }
43
44 //----------------------------------------------------------------------------------------
45 //      Update debtor trans alloc field according to current status of cust_allocations
46 //
47 function update_debtor_trans_allocation($trans_type, $trans_no, $person_id)
48 {
49         $dec = user_price_dec();
50         $sql = 
51                 "UPDATE `".TB_PREF.($trans_type==ST_SALESORDER ? 'sales_orders' : 'debtor_trans')."` trans,
52                         (SELECT sum(amt) amt FROM ".TB_PREF."cust_allocations
53                                 WHERE person_id=".db_escape($person_id)." AND ((trans_type_to=".db_escape($trans_type)." AND trans_no_to=".db_escape($trans_no).")
54                                 OR (trans_type_from=".db_escape($trans_type)." AND trans_no_from=".db_escape($trans_no)."))) allocated
55                 SET 
56                         trans.alloc=IFNULL(ROUND(allocated.amt, $dec),0)
57                 WHERE trans.debtor_no=".db_escape($person_id)." AND ".($trans_type==ST_SALESORDER ?
58                            "trans.trans_type=".db_escape($trans_type)." AND order_no=".db_escape($trans_no)
59                         :  "trans.type=".db_escape($trans_type)." AND trans_no=".db_escape($trans_no));
60         db_query($sql, "The debtor transaction record could not be modified for the allocation against it");
61 }
62
63 //-------------------------------------------------------------------------------------------------------------
64 //
65 function void_cust_allocations($type, $type_no, $date="")
66 {
67         return clear_cust_alloctions($type, $type_no, null, $date);
68 }
69
70 //-------------------------------------------------------------------------------------------------------------
71 //
72 function clear_cust_alloctions($type, $type_no, $person_id=null, $date="")
73 {
74         $sql = "UPDATE  ".TB_PREF."cust_allocations ca
75                                 LEFT JOIN ".TB_PREF."debtor_trans paym ON ca.trans_type_from=paym.type AND ca.trans_no_from=paym.trans_no AND ca.person_id=paym.debtor_no
76                                 LEFT JOIN ".TB_PREF."debtor_trans dt ON ca.trans_type_to=dt.type AND ca.trans_no_to=dt.trans_no AND ca.person_id=dt.debtor_no
77                                 LEFT JOIN ".TB_PREF."sales_orders so ON ca.trans_type_to=so.trans_type AND ca.trans_no_to=so.order_no AND ca.person_id=so.debtor_no
78                         SET paym.alloc=paym.alloc - ca.amt,
79                                 dt.alloc=dt.alloc -  ca.amt,
80                                 so.alloc=so.alloc -  ca.amt
81                         WHERE  ((ca.trans_type_from=".db_escape($type)." AND ca.trans_no_from=".db_escape($type_no).")
82                                 OR (ca.trans_type_to=".db_escape($type)." AND ca.trans_no_to=".db_escape($type_no)."))";
83         if ($person_id)
84                 $sql .= " AND ca.person_id=".db_escape($person_id);
85         db_query($sql, "could not clear allocation");
86
87         // remove any allocations for this transaction
88         $sql = "DELETE FROM ".TB_PREF."cust_allocations
89                         WHERE  ((trans_type_from=".db_escape($type)." AND trans_no_from=".db_escape($type_no).")
90                                 OR (trans_type_to=".db_escape($type)." AND trans_no_to=".db_escape($type_no)."))";
91         if ($person_id)
92                 $sql .= " AND person_id=".db_escape($person_id);
93
94         db_query($sql, "could not void debtor transactions for type=$type and trans_no=$type_no");
95 // is this necessary?
96 //      if ($date != "")
97 //              exchange_variation($type, $type_no, $row['trans_type_to'], $row['trans_no_to'], $date,
98 //                      $row['amt'], PT_CUSTOMER, true);
99 }
100 //-------------------------------------------------------------------------------------------------------------
101
102 function get_allocatable_from_cust_sql($customer_id, $settled)
103 {
104         $sql = "SELECT
105                 trans.type,
106                 trans.trans_no,
107                 trans.reference,
108                 trans.tran_date,
109                 debtor.name AS DebtorName, 
110                 debtor.curr_code,
111                 ov_amount+ov_gst+ov_freight+ov_freight_tax+ov_discount AS Total,
112                 trans.alloc,
113                 trans.due_date,
114                 debtor.address,
115                 trans.version,
116                 round(abs(ov_amount)+ov_gst+ov_freight+ov_freight_tax+ov_discount-alloc,6) <= 0 AS settled,
117                 trans.debtor_no
118
119          FROM "
120                 .TB_PREF."debtor_trans as trans, "
121                 .TB_PREF."debtors_master as debtor"
122         ." WHERE trans.debtor_no=debtor.debtor_no
123                 AND (((type=".ST_CUSTPAYMENT." OR type=".ST_BANKDEPOSIT.") AND (trans.ov_amount > 0))
124                  OR (type=".ST_CUSTCREDIT. " AND (ov_amount+ov_gst+ov_freight+ov_freight_tax+ov_discount)>0)
125                  OR (type=".ST_JOURNAL. " AND (trans.ov_amount < 0)))";
126
127         if (!$settled)
128                 $sql .= " AND round(abs(ov_amount+ov_gst)+ov_freight+ov_freight_tax+ov_discount-alloc, 6) > 0";
129
130         if ($customer_id != null)
131                 $sql .= " AND trans.debtor_no = ".db_escape($customer_id);
132
133         return $sql;
134 }
135
136 function get_allocatable_sales_orders($customer_id = null, $trans_no=null, $type=null)
137 {
138         $sql = "SELECT
139                 sorder.trans_type as type,
140                 sorder.order_no as trans_no,
141                 sorder.reference,
142                 sorder.ord_date,
143                 debtor.name AS DebtorName, 
144                 debtor.curr_code,
145                 total-IFNULL(invoiced.amount,0) as Total,
146                 sorder.alloc,
147                 sorder.delivery_date as due_date,
148                 debtor.address,
149                 sorder.version,
150                 amt,
151                 sorder.debtor_no,
152                 sorder.branch_code
153                 FROM ".TB_PREF."sales_orders as sorder
154                         LEFT JOIN ".TB_PREF."debtors_master as debtor ON sorder.debtor_no = debtor.debtor_no
155                         LEFT JOIN ".TB_PREF."cust_allocations as alloc 
156                                 ON sorder.order_no = alloc.trans_no_to AND sorder.trans_type = alloc.trans_type_to AND alloc.person_id=sorder.debtor_no
157                         LEFT JOIN (SELECT order_, sum(prep_amount) amount FROM ".TB_PREF."debtor_trans dt
158                         WHERE prep_amount>0 AND dt.type=".ST_SALESINVOICE." GROUP BY order_) as invoiced ON sorder.order_no = invoiced.order_
159                 WHERE sorder.trans_type=".ST_SALESORDER;
160
161         if ($trans_no != null and $type != null)
162         {
163                 $sql .= " AND alloc.trans_no_from=".db_escape($trans_no)."
164                                   AND alloc.trans_type_from=".db_escape($type);
165         }
166         else
167         {
168                 $sql .= " AND round(sorder.prep_amount)>0 and Total>0"; // only sales orders with prepayment level set and no yet fully invoiced
169         }
170         if ($customer_id)
171                 $sql .= " AND sorder.debtor_no=".db_escape($customer_id);
172
173         $sql .= " GROUP BY sorder.order_no";
174
175         return $sql;
176 }
177 //-------------------------------------------------------------------------------------------------------------
178
179 function get_allocatable_to_cust_transactions($customer_id = null, $trans_no=null, $type=null)
180 {
181         $sql = "SELECT
182                 trans.type,
183                 trans.trans_no,
184                 trans.reference,
185                 trans.tran_date,
186                 debtor.name AS DebtorName, 
187                 debtor.curr_code,
188                 IF(prep_amount, prep_amount, ov_amount+ov_gst+ov_freight+ov_freight_tax+ov_discount) AS Total,
189                 trans.alloc,
190                 trans.due_date,
191                 debtor.address,
192                 trans.version,
193                 amt,
194                 trans.debtor_no,
195                 trans.branch_code
196          FROM ".TB_PREF."debtor_trans as trans
197                         LEFT JOIN ".TB_PREF."cust_allocations as alloc
198                                 ON trans.trans_no = alloc.trans_no_to AND trans.type = alloc.trans_type_to AND alloc.person_id=trans.debtor_no,"
199                         .TB_PREF."debtors_master as debtor
200          WHERE
201                  trans.debtor_no=debtor.debtor_no";
202         if ($customer_id)
203                 $sql .= " AND trans.debtor_no=".db_escape($customer_id);
204
205         if ($trans_no != null and $type != null)
206         {
207                 $sql .= " AND alloc.trans_no_from=".db_escape($trans_no)."
208                                   AND alloc.trans_type_from=".db_escape($type);
209         }
210         else
211         {
212                 $sql .= "
213                                  AND (
214                                         trans.type='".ST_SALESINVOICE."'
215                                         AND round(IF(prep_amount, prep_amount, ov_amount+ov_gst+ov_freight+ov_freight_tax+ov_discount)-alloc,6) > 0
216                                         OR
217                                         trans.type='". ST_CUSTCREDIT."'
218                                         AND round(-IF(prep_amount, prep_amount, ov_amount+ov_gst+ov_freight+ov_freight_tax+ov_discount)-alloc,6) > 0
219                                         OR
220                                         trans.type = '". ST_JOURNAL."'
221                                         AND ov_amount+ov_gst+ov_freight+ov_freight_tax+ov_discount>0
222                                         OR
223                                         trans.type = '". ST_BANKPAYMENT."'
224                                         AND ov_amount+ov_gst+ov_freight+ov_freight_tax+ov_discount>0
225                                 )";
226                 $sql .= " GROUP BY type, trans_no";
227         }
228
229         $orders = get_allocatable_sales_orders($customer_id, $trans_no, $type);
230         $sql = "($sql ORDER BY trans_no) \nUNION \n($orders)";
231
232         return db_query($sql, "Cannot retreive alloc to transactions");
233 }
234
235 //-------------------------------------------------------------------------------------------------------------
236
237 function get_allocatable_from_cust_transactions($customer_id, $trans_no=null, $type=null)
238 {
239
240         $sql = "SELECT
241                 trans.type,
242                 trans.trans_no,
243                 trans.reference,
244                 trans.tran_date,
245                 debtor.name AS DebtorName, 
246                 debtor.curr_code,
247                 ov_amount+ov_gst+ov_freight+ov_freight_tax+ov_discount AS Total,
248                 trans.alloc,
249                 trans.due_date,
250                 debtor.address,
251                 trans.version,
252                 amt,
253                 trans.debtor_no
254          FROM  ".TB_PREF."debtor_trans as trans,"
255                         .TB_PREF."debtors_master as debtor,"
256                         .TB_PREF."cust_allocations as alloc
257          WHERE trans.debtor_no=debtor.debtor_no
258                         AND trans.trans_no = alloc.trans_no_from
259                         AND trans.type = alloc.trans_type_from
260                         AND trans.debtor_no = alloc.person_id";
261
262         if ($trans_no != null and $type != null)
263         {
264                 $sql .= " AND alloc.trans_no_to=".db_escape($trans_no)."
265                                   AND alloc.trans_type_to=".db_escape($type);
266         }
267         else
268         {
269                 $sql .= " AND round(abs(ov_amount)+ov_gst+ov_freight+ov_freight_tax+ov_discount-alloc,6) > 0
270                         AND trans.type NOT IN (".implode(',',array(ST_CUSTPAYMENT,ST_BANKDEPOSIT,ST_CUSTCREDIT,ST_CUSTDELIVERY)).")";
271                 $sql .= " GROUP BY type, trans_no";
272         }
273
274         if($customer_id)
275                 $sql .= " AND trans.debtor_no=".db_escape($customer_id);
276
277         return db_query($sql." ORDER BY trans_no", "Cannot retreive alloc to transactions");
278 }
279
280 function get_sql_for_customer_allocation_inquiry($from, $to, $customer, $filterType, $settled)
281 {
282         $data_after = date2sql($from);
283         $date_to = date2sql($to);
284
285         $sql = "SELECT 
286                 trans.type,
287                 trans.trans_no,
288                 trans.reference,
289                 trans.order_,
290                 trans.tran_date,
291                 trans.due_date,
292                 debtor.name,
293                 debtor.curr_code,
294         (trans.ov_amount + trans.ov_gst + trans.ov_freight 
295                         + trans.ov_freight_tax + trans.ov_discount)     AS TotalAmount,
296                 trans.alloc AS Allocated,
297                 ((trans.type = ".ST_SALESINVOICE.")
298                         AND trans.due_date < '" . date2sql(Today()) . "') AS OverDue,
299                 trans.debtor_no
300         FROM "
301                         .TB_PREF."debtor_trans as trans, "
302                         .TB_PREF."debtors_master as debtor
303         WHERE debtor.debtor_no = trans.debtor_no
304                         AND (trans.ov_amount + trans.ov_gst + trans.ov_freight 
305                                 + trans.ov_freight_tax + trans.ov_discount != 0)
306                 AND trans.tran_date >= '$data_after'
307                 AND trans.tran_date <= '$date_to'";
308
309         if ($customer != ALL_TEXT)
310                 $sql .= " AND trans.debtor_no = ".db_escape($customer);
311
312         if (isset($filterType) && $filterType != ALL_TEXT)
313         {
314                 if ($filterType == '1' || $filterType == '2')
315                 {
316                         $sql .= " AND trans.type = ".ST_SALESINVOICE." ";
317                 }
318                 elseif ($filterType == '3')
319                 {
320                         $sql .= " AND trans.type = " . ST_CUSTPAYMENT;
321                 }
322                 elseif ($filterType == '4')
323                 {
324                         $sql .= " AND trans.type = ".ST_CUSTCREDIT." ";
325                 }
326                 elseif ($filterType == '6')
327                 {
328                         $sql .= " AND trans.type = ".ST_JOURNAL." ";
329                 }
330
331         if ($filterType == '2')
332         {
333                 $today =  date2sql(Today());
334                 $sql .= " AND trans.due_date < '$today'
335                                 AND (round(abs(trans.ov_amount) + "
336                                 ."trans.ov_gst + trans.ov_freight + "
337                                 ."trans.ov_freight_tax + trans.ov_discount - trans.alloc,6) > 0) ";
338         }
339         }
340         else
341         {
342             $sql .= " AND trans.type <> ".ST_CUSTDELIVERY." ";
343         }
344
345
346         if (!$settled)
347         {
348                 $sql .= " AND (ROUND(IF(trans.prep_amount,trans.prep_amount, ABS(trans.ov_amount) + trans.ov_gst + "
349                 ."trans.ov_freight + trans.ov_freight_tax + "
350                 ."trans.ov_discount) - trans.alloc,6) != 0) ";
351         }
352         return $sql;
353 }
354
355 function credit_sales_invoice_allocate($invoice_no, $credit_no, $amount, $date)
356 {
357
358         $sql = "SELECT ov_freight+ov_gst+ov_amount+ov_freight_tax as total, alloc, debtor_no FROM ".TB_PREF."debtor_trans
359                 WHERE (`type`=".ST_SALESINVOICE." AND trans_no=".db_escape($invoice_no).")";
360         $result = db_query($sql, "can't retrieve invoice totals");
361         $invoice = db_fetch($result);
362         $free = $invoice['total'] - $invoice['alloc'];
363
364         if ($free < $amount) {
365          // if there is not enough unallocated amount - remove some payment allocations
366                 $sql = "SELECT * FROM ".TB_PREF."cust_allocations
367                         WHERE (trans_type_to=".ST_SALESINVOICE." AND trans_no_to=".db_escape($invoice_no)." AND person_id=".db_escape($invoice['debtor_no']).")
368                         AND trans_type_from <> ".ST_CUSTCREDIT;
369                 $result = db_query($sql, "can't retrieve invoice allocations");
370
371                 while(($free < $amount) && ($alloc = db_fetch($result))) {
372                         $unalloc = min($alloc['amt'], $amount-$free);
373
374                         delete_cust_allocation($alloc['id']);
375                         if ($unalloc < $alloc['amt'])
376                                 add_cust_allocation($alloc['amt']-$unalloc, $alloc['trans_type_from'],
377                                         $alloc['trans_no_from'], ST_SALESINVOICE, $invoice_no, $invoice['debtor_no'], $date);
378
379                         update_debtor_trans_allocation($alloc['trans_type_to'], $alloc['trans_no_to'], $invoice['debtor_no']);
380                         update_debtor_trans_allocation($alloc['trans_type_from'], $alloc['trans_no_from'], $invoice['debtor_no']);
381                         $free += $unalloc;
382                 }
383         }
384         if (floatcmp($free, $amount)<0) {
385                 // this should never happen unless sparse credit notices were allocated to 
386                 // the invoice, or summarized freight costs on credit notes is more than those on invoice.
387                 display_error(_("Unsuspected overallocation happened due to sparse credit notes exists for this invoice.
388  Check all credit notes allocated to this invoice for summarized freight charges."));
389                 return false;
390         }
391         add_cust_allocation($amount, ST_CUSTCREDIT, $credit_no, ST_SALESINVOICE, $invoice_no, $invoice['debtor_no'], $date);
392         update_debtor_trans_allocation(ST_SALESINVOICE, $invoice_no, $invoice['debtor_no']);
393         update_debtor_trans_allocation(ST_CUSTCREDIT, $credit_no, $invoice['debtor_no']);
394
395         exchange_variation(ST_CUSTCREDIT, $credit_no, ST_SALESINVOICE, $invoice_no, $date,
396                 $amount, PT_CUSTOMER);
397         return true;
398 }