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 include_once($path_to_root . "/admin/db/voiding_db.inc");
13 include_once($path_to_root . "/includes/types.inc");
15 //--------------------------------------------------------------------------------------
17 function get_supplier_trans_view_str($type, $trans_no, $label="", $icon=false,
20 $viewer = "purchasing/view/";
21 if ($type == ST_PURCHORDER)
22 $viewer .= "view_po.php";
23 elseif ($type == ST_SUPPINVOICE)
24 $viewer .= "view_supp_invoice.php";
25 elseif ($type == ST_SUPPCREDIT)
26 $viewer .= "view_supp_credit.php";
27 elseif ($type == ST_SUPPAYMENT)
28 $viewer .= "view_supp_payment.php";
29 elseif ($type == ST_SUPPRECEIVE)
30 $viewer .= "view_grn.php";
33 $viewer .= "?trans_no=$trans_no";
38 return viewer_link($label, $viewer, $class, $id, $icon);
41 //--------------------------------------------------------------------------------------
43 function get_gl_view_str($type, $trans_no, $label="", $force=false, $class='', $id='')
45 if (!$force && !user_show_gl_info())
54 $url = ($type == ST_WORKORDER) ? "manufacturing/view/wo_costs_view.php?trans_no=$trans_no"
55 : "gl/view/gl_trans_view.php?type_id=$type&trans_no=$trans_no";
57 return viewer_link($label, $url, $class, $id, $icon);
60 //--------------------------------------------------------------------------------------
62 function get_gl_view_str_cell($type, $trans_no, $label="")
64 $str = get_gl_view_str($type, $trans_no, $label);
66 return "<td>$str</td>";
69 //--------------------------------------------------------------------------------------
71 function get_customer_trans_view_str($type, $trans_no, $label="", $icon=false,
74 $viewer = "sales/view/";
76 if ($type == ST_SALESINVOICE)
77 $viewer .= "view_invoice.php";
78 elseif ($type == ST_CUSTCREDIT)
79 $viewer .= "view_credit.php";
80 elseif ($type == ST_CUSTPAYMENT)
81 $viewer .= "view_receipt.php";
82 elseif ($type == ST_CUSTDELIVERY)
83 $viewer .= "view_dispatch.php";
84 elseif ($type == ST_SALESORDER || $type == ST_SALESQUOTE)
85 $viewer .= "view_sales_order.php";
89 if(!is_array($trans_no)) $trans_no = array($trans_no);
94 foreach($trans_no as $trans) {
97 if($preview_str!='') $preview_str .= ',';
99 $preview_str .= viewer_link($lbl, $viewer."?trans_no=$trans&trans_type=$type",
106 //--------------------------------------------------------------------------------------
108 function get_banking_trans_view_str($type, $trans_no, $label="",
109 $icon=false, $class='', $id='')
114 if ($type == ST_BANKTRANSFER)
115 $viewer = "bank_transfer_view.php";
116 elseif ($type == ST_BANKPAYMENT)
117 $viewer = "gl_payment_view.php";
118 elseif ($type == ST_BANKDEPOSIT)
119 $viewer = "gl_deposit_view.php";
123 return viewer_link($label, "gl/view/$viewer?trans_no=$trans_no",
127 //--------------------------------------------------------------------------------------
129 function get_inventory_trans_view_str($type, $trans_no, $label="",
130 $icon=false, $class='', $id='')
132 $viewer = "inventory/view/";
134 if ($type == ST_INVADJUST)
135 $viewer .= "view_adjustment.php";
136 elseif ($type == ST_LOCTRANSFER)
137 $viewer .= "view_transfer.php";
140 $viewer .= "?trans_no=$trans_no";
145 return viewer_link($label, $viewer, $class, $id, $icon);
148 //--------------------------------------------------------------------------------------
150 function get_manufacturing_trans_view_str($type, $trans_no, $label="",
151 $icon=false, $class='', $id='')
153 $viewer = "manufacturing/view/";
155 if ($type == ST_MANUISSUE)
156 $viewer .= "wo_issue_view.php";
157 elseif ($type == ST_MANURECEIVE)
158 $viewer .= "wo_production_view.php";
159 elseif ($type == ST_WORKORDER)
160 $viewer .= "work_order_view.php";
164 $viewer .= "?trans_no=$trans_no";
169 return viewer_link($label, $viewer, $class, $id, $icon);
172 //--------------------------------------------------------------------------------------
174 function get_dimensions_trans_view_str($type, $trans_no, $label="", $icon=false,
177 if ($type == ST_DIMENSION)
178 $viewer = "dimensions/view/view_dimension.php?trans_no=$trans_no";
185 return viewer_link($label, $viewer, $class, $id, $icon);
188 Journal entry or cost update postings link
190 function get_journal_trans_view_str($type, $trans_no, $label="", $icon=false,
193 if ($type == ST_JOURNAL || $type == ST_COSTUPDATE)
194 $viewer = "gl/view/gl_trans_view.php?type_id=$type&trans_no=$trans_no";
201 return viewer_link($label, $viewer, $class, $id, $icon);
204 //--------------------------------------------------------------------------------------
206 function get_package_view_str($pkg, $label="", $icon=false, $class='', $id='')
213 return viewer_link($label, "admin/view/view_package.php?id=$pkg", $class, $id, $icon);
217 //--------------------------------------------------------------------------------------
219 function get_trans_view_str($type, $trans_no, $label="", $icon=false,
222 $view_str = get_customer_trans_view_str($type, $trans_no, $label, $icon, $class, $id);
223 if ($view_str != null)
226 $view_str = get_supplier_trans_view_str($type, $trans_no, $label, $icon, $class, $id);
227 if ($view_str != null)
230 $view_str = get_banking_trans_view_str($type, $trans_no, $label, $icon, $class, $id);
231 if ($view_str != null)
234 $view_str = get_inventory_trans_view_str($type, $trans_no, $label, $icon, $class, $id);
235 if ($view_str != null)
238 $view_str = get_manufacturing_trans_view_str($type, $trans_no, $label, $icon, $class, $id);
239 if ($view_str != null)
242 $view_str = get_dimensions_trans_view_str($type, $trans_no, $label, $icon, $class, $id);
243 if ($view_str != null)
246 $view_str = get_journal_trans_view_str($type, $trans_no, $label, $icon, $class, $id);
247 if ($view_str != null)
254 Helper for ui drawing functions.
255 Checks whether any of input function parameters has changed or page is called with GET method (first page display).
258 function check_ui_refresh($name=null)
260 $bt = debug_backtrace();
262 $name = $bt[1]['function'];
263 $old = @$_SESSION['ui_context'][$name];
264 $new = $_SESSION['ui_context'][$name] = $bt[1]['args'];
265 return ($new != $old);
268 //--------------------------------------------------------------------------------------
269 // Displays currency exchange rate for given date.
270 // When there is no exrate for today,
271 // gets it form ECB and stores in local database.
273 function exchange_rate_display($from_currency=null, $to_currency=null, $date_, $force_edit=false)
275 global $Ajax, $SysPrefs;
279 if ($from_currency != $to_currency)
281 $rate = input_num('_ex_rate');
282 if (check_ui_refresh() || !$rate) { // readonly or ui context changed
283 $comp_currency = get_company_currency();
285 if (!isset($from_currency))
286 $from_currency = $comp_currency;
287 if (!isset($to_currency))
288 $to_currency = $comp_currency;
290 if ($from_currency == $comp_currency)
291 $currency = $to_currency;
293 $currency = $from_currency;
295 $rate = get_date_exchange_rate($currency, $date_); // try local
298 $readonly = true; // if we have already local exrate keep it unchanged
300 if (!$rate) { // retry from remote service
301 $row = get_currency($currency);
303 if ($row['auto_update']) // autoupdate means use remote service & store exrate on first transaction.
305 $rate = retrieve_exrate($currency, $date_);
307 display_warning(sprintf(_("Cannot retrieve exchange rate for currency %s. Please adjust approximate rate if needed."), $currency));
308 elseif ($SysPrefs->xr_provider_authoritative) {
309 // if the remote exrate is considered authoritative we can store the rate here,
310 // otherwise exrate will be stored during transaction write
312 add_new_exchange_rate($currency, $date_, $rate);
316 if (!$rate) { // get and edit latest available
317 $rate = get_exchange_rate_from_home_currency($currency, $date_);
319 if ($from_currency != $comp_currency)
320 $rate = 1 / ($rate / get_exchange_rate_from_home_currency($to_currency, $date_));
321 $Ajax->activate('_ex_rate_span');
324 $rate = number_format2($rate, user_exrate_dec());
326 if ($force_edit || !$readonly)
327 $ctrl = "<input type=\"text\" name=\"_ex_rate\" size=\"8\" maxlength=\"8\" value=\"$rate\">";
329 $ctrl = "<span id=\"_ex_rate\">$rate</span>";
331 label_row(_("Exchange Rate:"), $span = "<span style='vertical-align:top;' id='_ex_rate_span'>$ctrl $from_currency = 1 $to_currency</span>" );
333 $Ajax->addUpdate('_ex_rate_span', '_ex_rate_span', $span);
337 //--------------------------------------------------------------------------------------
339 function is_voided_display($type, $id, $label)
341 $void_entry = get_voided_entry($type, $id);
343 if ($void_entry == null)
346 start_table(TABLESTYLE, "width='50%'");
347 echo "<tr><td align=center><font color=red>$label</font><br>";
348 echo "<font color=red>" . _("Date Voided:") . " " . sql2date($void_entry["date_"]) . "</font><br>";
349 if (strlen($void_entry["memo_"]) > 0)
350 echo "<center><font color=red>" . _("Memo:") . " " . $void_entry["memo_"] . "</font></center><br>";
357 //--------------------------------------------------------------------------------------
359 function comments_display_row($type, $id)
361 $comments = get_comments($type, $id);
362 if ($comments and db_num_rows($comments))
364 echo "<tr><td colspan=15>";
365 while ($comment = db_fetch($comments))
367 echo nl2br($comment["memo_"]) . "<br>";
373 //--------------------------------------------------------------------------------------
375 function get_comments_string($type, $type_no)
378 $result = get_comments($type, $type_no);
379 while ($comment = db_fetch($result))
381 if (strlen($str_return))
382 $str_return = $str_return . " \n";
383 $str_return = $str_return . $comment["memo_"];
388 //--------------------------------------------------------------------------------------
390 function view_stock_status($stock_id, $description=null, $echo=true)
392 global $path_to_root;
394 $preview_str = "<a target='_blank' href='$path_to_root/inventory/inquiry/stock_status.php?stock_id=$stock_id&popup=1' onclick=\"javascript:openWindow(this.href,this.target); return false;\" >". (user_show_codes()?$stock_id . " - ":"") . $description."</a>";
396 $preview_str = "<a target='_blank' href='$path_to_root/inventory/inquiry/stock_status.php?stock_id=$stock_id&popup=1' onclick=\"javascript:openWindow(this.href,this.target); return false;\" >$stock_id</a>";
402 function view_stock_status_cell($stock_id, $description=null)
405 view_stock_status($stock_id, $description);
409 //--------------------------------------------------------------------------------------
411 function display_debit_or_credit_cells($value, $bold=false)
413 $value = round2($value, user_price_dec());
416 amount_cell($value, $bold);
422 amount_cell(abs($value), $bold);
426 //--------------------------------------------------------------------------------------
428 function display_customer_trans_tax_details($tax_items, $columns)
433 while ($tax_item = db_fetch($tax_items))
435 if (!$tax_item['amount'])
438 $tax = number_format2($tax_item['amount'],user_price_dec());
439 if ($SysPrefs->suppress_tax_rates() == 1)
440 $tax_type_name = $tax_item['tax_type_name'];
442 $tax_type_name = $tax_item['tax_type_name']." (".$tax_item['rate']."%) ";
443 if ($tax_item['included_in_price'])
445 if ($SysPrefs->alternative_tax_include_on_docs() == 1)
448 label_row(_("Total Tax Excluded"), number_format2($tax_item['net_amount'], user_price_dec()),
449 "colspan=$columns align=right", "align=right");
450 label_row($tax_type_name, $tax, "colspan=$columns align=right", "align=right");
454 label_row(_("Included") . " " . $tax_type_name
455 . ": $tax", "", "colspan=$columns align=right", "align=right");
458 label_row($tax_type_name, $tax, "colspan=$columns align=right", "align=right");
462 //--------------------------------------------------------------------------------------
464 function display_supp_trans_tax_details($tax_items, $columns)
466 while ($tax_item = db_fetch($tax_items))
468 if (!$tax_item['amount'])
471 $tax = number_format2(abs($tax_item['amount']),user_price_dec());
472 if ($tax_item['included_in_price'])
473 label_row(_("Included") . " " . $tax_item['tax_type_name'] . " (" . $tax_item['rate'] . "%) "
474 . ": $tax", '', "colspan=$columns align=right", "align=right");
476 label_row($tax_item['tax_type_name'] . " (" . $tax_item['rate'] . "%)",
477 $tax, "colspan=$columns align=right", "align=right");
481 //--------------------------------------------------------------------------------------
483 function display_edit_tax_items($taxes, $columns, $tax_included, $rightspan=0, $editable=false)
487 foreach ($taxes as $taxitem)
489 $amount = isset($taxitem['Override']) ? $taxitem['Override'] : $taxitem['Value'];
490 if ($taxitem['Value'] != 0){
492 if (!isset($_POST['mantax['.$taxitem['tax_type_id'].']']))
493 $_POST['mantax['.$taxitem['tax_type_id'].']'] = price_format($amount);
496 $colspan = $columns-1;
497 label_cell(_("Included") . " " . $taxitem['tax_type_name'].":",
498 "colspan={$colspan} align='right'");
499 amount_cells(null, 'mantax['.$taxitem['tax_type_id'].']',
500 null, "colspan=$columns align=right", '<td></td>', user_price_dec());
502 label_cell($taxitem['tax_type_name'], "colspan=$columns align='right'");
503 amount_cells(null, 'mantax['.$taxitem['tax_type_id'].']',
504 null, "colspan=$columns align=right", null, user_price_dec());
505 $total += round2($amount, user_price_dec());
508 label_cell('', "colspan ='$rightspan'");
511 $value = number_format2($taxitem['Value'],user_price_dec());
514 label_row(_("Included") . " " . $taxitem['tax_type_name']
515 . " " . $value , "", "colspan=$columns align=right", "align=right", $rightspan);
519 label_row($taxitem['tax_type_name'],
520 $value, "colspan=$columns align=right", "align=right", $rightspan);
521 $total += round2($taxitem['Value'], user_price_dec());
529 //--------------------------------------------------------------------------------------
531 function display_footer_exit($space=2)
535 end_page(false, false, true);
539 //--------------------------------------------------------------------------------------
541 function display_allocations($alloc_result, $total, $title, $show_summary=true)
543 global $systypes_array;
545 if (!$alloc_result || db_num_rows($alloc_result) == 0)
548 display_heading2($title);
550 start_table(TABLESTYLE, "width='80%'");
552 $th = array( _("Type"), _("Number"), _("Date"), _("Total Amount"),
553 _("Left to Allocate"), _("This Allocation"));
555 $k = $total_allocated = 0;
557 while ($alloc_row = db_fetch($alloc_result))
559 alt_table_row_color($k);
561 label_cell($systypes_array[$alloc_row['type']]);
562 label_cell(get_trans_view_str($alloc_row['type'],$alloc_row['trans_no']));
563 label_cell(sql2date($alloc_row['tran_date']));
564 $alloc_row['Total'] = round2($alloc_row['Total'], user_price_dec());
565 $alloc_row['amt'] = round2($alloc_row['amt'], user_price_dec());
566 amount_cell(abs($alloc_row['Total']));
567 amount_cell(abs($alloc_row['Total']) - $alloc_row['alloc']);
568 amount_cell($alloc_row['amt']);
571 $total_allocated += $alloc_row['amt'];
574 label_cell(_("Total Allocated:"), "align=right colspan=5");
575 amount_cell($total_allocated);
580 label_cell(_("Left to Allocate:"), "align=right colspan=5");
581 $total = round2($total, user_price_dec());
582 amount_cell($total - $total_allocated);
588 //--------------------------------------------------------------------------------------
590 function display_allocations_from($person_type, $person_id, $type, $type_no, $total)
592 switch ($person_type)
595 $alloc_result = get_allocatable_to_cust_transactions(0, $type_no, $type);
596 display_allocations($alloc_result, $total, _("Allocations"));
599 $alloc_result = get_allocatable_to_supp_transactions(0, $type_no, $type);
600 display_allocations($alloc_result, $total, _("Allocations"));
605 //--------------------------------------------------------------------------------------
607 function display_allocations_to($person_type, $person_id, $type, $type_no, $total)
609 switch ($person_type)
612 $alloc_result = get_allocatable_from_cust_transactions($person_id, $type_no, $type);
613 display_allocations($alloc_result, $total, $type == ST_SALESORDER ? _("Pre-Payments") : _("Payments"), false);
616 $alloc_result = get_allocatable_from_supp_transactions($person_id, $type_no, $type);
617 display_allocations($alloc_result, $total, $type == ST_PURCHORDER ? _("Pre-Payments") : _("Payments"), false);
622 //--------------------------------------------------------------------------------------
624 // Expands selected quick entry $id into GL posings and adds to cart.
625 // returns calculated amount posted to bank GL account.
627 function display_quick_entries(&$cart, $id, $base, $type, $descr='')
631 if (!isset($id) || $id == null || $id == "")
633 display_error( _("No Quick Entries are defined."));
634 set_focus('totamount');
638 if ($type == QE_DEPOSIT)
640 if ($type != QE_SUPPINV && $type != QE_JOURNAL) // only one quick entry on journal/bank transaction
641 $cart->clear_items();
643 // as for now tax_group is passed only in QE_SUPPINV
644 $qe_lines = quickentry_calculate($base, $id, @$cart->tax_group_id, $cart->tran_date);
648 display_error( _("No Quick Entry lines are defined."));
649 set_focus('totamount');
651 } elseif ($qe_lines === -1)
653 display_error(_("Cannot post to GL account used by more than one tax type."));
656 foreach($qe_lines as $qe_line)
658 if ($descr != '') $qe_line['descr'] .= ': '.$descr;
659 if ($type != QE_SUPPINV)
660 $cart->add_gl_item($qe_line['code'], $qe_line['dim1'],
661 $qe_line['dim2'], $qe_line['amount'], $qe_line['descr']);
664 $acc_name = get_gl_account_name($qe_line['code']);
665 $cart->add_gl_codes_to_trans($qe_line['code'],
666 $acc_name, $qe_line['dim1'],
667 $qe_line['dim2'], $qe_line['amount'], $qe_line['descr']);
674 //--------------------------------------------------------------------------------------
676 function quickentry_calculate($base, $id, $taxgroup=null, $date=null)
678 $gl_entries = array();
679 $qe = get_quick_entry($id);
682 // quick entry made on account balance is special case.
683 if ($qe['bal_type'] == 1) // if this is quick entry based on balance - calculate it
685 // Note, that this is ugly hack overriding standard field usage
686 // just to make the feature available between major FA releases!
687 $gl_code = $qe['base_desc'];
688 $monthly = $qe['base_amount'] == 1.0;
693 if ($monthly) // marked as monthly
694 $begin = begin_month($date);
697 if (is_account_balancesheet($gl_code)) // total
700 $begin = begin_fiscalyear(); // from fiscalyear begin
702 $base = get_gl_trans_from_to($begin, $date, $gl_code);
706 $result = get_quick_entry_lines($id);
707 if (db_num_rows($result) == 0)
712 // first calculate total rate in case more than one tax is used
714 while ($row = db_fetch($result))
718 switch (strtolower($row['action'])) {
719 case "t": // post taxes calculated on base amount
720 case "t+": // ditto & increase base amount
721 case "t-": // ditto & reduce base amount
722 if (substr($row['action'], 0, 1) != 'T')
723 $totrate += get_tax_type_rate($row['dest_id']);
728 foreach($qe_lines as $qe_line)
730 $gl_code = $qe_line['dest_id'];
731 switch (strtolower($qe_line['action'])) {
732 case "=": // post current base amount to GL account
735 case "a": // post amount to GL account and reduce base
736 $part = $qe_line['amount'];
738 case "a+": // post amount to GL account and increase base
739 $part = $qe_line['amount']; $base += $part;
741 case "a-": // post amount to GL account and reduce base
742 $part = $qe_line['amount']; $base -= $part;
744 case "%": // store acc*amount% to GL account
745 $part = round2($base * $qe_line['amount'] / 100, user_price_dec());
747 case "%+": // ditto & increase base amount
748 $part = round2($base * $qe_line['amount'] / 100, user_price_dec());
751 case "%-": // ditto & reduce base amount
752 $part = round2($base * $qe_line['amount'] / 100, user_price_dec());
755 case "t": // post taxes calculated on base amount
756 case "t+": // ditto & increase base amount
757 case "t-": // ditto & reduce base amount
760 $taxbase = $base/($totrate+100);
764 if (substr($qe_line['action'],0,1) != 'T')
769 $item_tax = get_tax_type($qe_line['dest_id']);
770 //if ($type == QE_SUPPINV && substr($qe_line['action'],0,1) != 'T')
771 if ($type == QE_SUPPINV)
774 $res = get_tax_group_rates($taxgroup);
775 while ($row = db_fetch($res))
776 $rates += $row['rate'];
780 $tax = round2($part * $item_tax['rate'], user_price_dec());
781 if ($tax == 0) continue 2;
782 $gl_code = ($type == QE_DEPOSIT || ($type == QE_JOURNAL && $base < 0))
783 ? $item_tax['sales_gl_code'] : $item_tax['purchasing_gl_code'];
784 if (!is_tax_gl_unique($gl_code)) {
785 return -1; // more than one taxtype used with this GL account
789 if (strpos($qe_line['action'], '+'))
791 elseif (strpos($qe_line['action'], '-'))
794 $gl_entries[] = array(
796 'name' => get_gl_account_name($gl_code),
797 'dim1' => $qe_line['dimension_id'],
798 'dim2' => $qe_line['dimension2_id'],
800 'descr' => $qe_line['memo']
807 //--------------------------------------------------------------------------------------
809 // Simple English version of number to words conversion.
811 function _number_to_words($number)
813 $Bn = floor($number / 1000000000); /* Billions (giga) */
814 $number -= $Bn * 1000000000;
815 $Gn = floor($number / 1000000); /* Millions (mega) */
816 $number -= $Gn * 1000000;
817 $kn = floor($number / 1000); /* Thousands (kilo) */
818 $number -= $kn * 1000;
819 $Hn = floor($number / 100); /* Hundreds (hecto) */
820 $number -= $Hn * 100;
821 $Dn = floor($number / 10); /* Tens (deca) */
822 $n = $number % 10; /* Ones */
827 $res .= _number_to_words($Bn) . " Billion";
829 $res .= (empty($res) ? "" : " ") . _number_to_words($Gn) . " Million";
831 $res .= (empty($res) ? "" : " ") . _number_to_words($kn) . " Thousand";
833 $res .= (empty($res) ? "" : " ") . _number_to_words($Hn) . " Hundred";
835 $ones = array("", "One", "Two", "Three", "Four", "Five", "Six",
836 "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen",
837 "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen",
839 $tens = array("", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty",
840 "Seventy", "Eighty", "Ninety");
847 $res .= $ones[$Dn * 10 + $n];
852 $res .= "-" . $ones[$n];
861 function price_in_words($amount, $document=0)
863 // use local price_in_words() if the hook is defined
864 $price = hook_price_in_words($amount, $document);
868 // Only usefor Remittance and Receipts as default
869 if (!($document == ST_SUPPAYMENT || $document == ST_CUSTPAYMENT || $document == ST_CHEQUE))
871 if ($amount < 0 || $amount > 999999999999)
873 $dec = user_price_dec();
876 $divisor = pow(10, $dec);
877 $frac = round2($amount - floor($amount), $dec) * $divisor;
878 $frac = sprintf("%0{$dec}d", round2($frac, 0));
880 $frac = " $and $frac/$divisor";
884 return _number_to_words(intval($amount)) . $frac;
887 function get_js_open_window($width, $height)
889 $js ="function openWindow(url, title)\n"
891 . " var left = (screen.width - $width) / 2;\n"
892 . " var top = (screen.height - $height) / 2;\n"
893 . " return window.open(url, title, 'width=$width,height=$height,left='+left+',top='+top+',screenX='+left+',screenY='+top+',status=no,scrollbars=yes');\n"
895 $js .= get_js_lookup_window();
899 function get_js_lookup_window() {
900 $js = "function lookupWindow(url, title) {
901 var u = url.split('#');
903 var element = document.getElementById(u[1]);
904 var options = element.options;
905 url = u[0] + '&' + u[1] + '=' + options[element.selectedIndex].value;
907 openWindow(url, title);
912 function get_js_select_combo_item() {
913 $js = "function selectComboItem(doc, client_id, value){
914 var element = doc.getElementById(client_id);
915 if (typeof(element) != 'undefined' && element != null && element.tagName === 'SELECT' ){
916 var options = element.options;
917 for (var i = 0, optionsLength = options.length; i < optionsLength; i++) {
918 if (options[i].value == value) {
919 element.selectedIndex = i;
924 var stock_element = doc.getElementsByName('stock_id');
925 if( stock_element.length > 0) {
926 stock_element.value = value;
927 var stock_id = doc.getElementById('_stock_id_edit');
928 stock_id.value=value;
936 /* for space search option */
937 function get_js_set_combo_item() {
938 $js = "function setComboItem(doc, client_id, value, text){
939 var element = doc.getElementById(client_id);
940 if(typeof(element) != 'undefined' && element != null && element.tagName === 'SELECT') {
941 var options = element.options;
943 var option = doc.createElement('option');
944 option.value = value;
946 element.add(option, 0);
947 element.selectedIndex = 0;
950 var stock_element = doc.getElementsByName('stock_id');
951 if( stock_element.length > 0) {
952 stock_element[0].value = value;
953 var stock_id = doc.getElementById('_stock_id_edit');
954 stock_id.value=value;
964 Setting focus on element $name in $form.
965 If $form<0 $name is element id.
967 function set_focus($name, $form_no=0) {
969 $Ajax->addFocus(true, $name);
970 $_POST['_focus'] = $name;
973 // Set default focus on first field $name if not set yet
974 // Returns unique name if $name=null
976 function default_focus($name=null, $form_no=0) {
979 $name = uniqid('_el',true);
980 if (!isset($_POST['_focus'])) {
986 Reset focus to next control element (e.g. link).
988 function reset_focus()
990 unset($_POST['_focus']);
993 function get_js_date_picker()
995 global $SysPrefs, $tmonths;
997 $fpath = user_js_cache().'/'.'date_picker.js';
999 if (!file_exists($fpath) || $SysPrefs->go_debug) {
1001 $date_system = $SysPrefs->date_system;
1002 $dateseps = $SysPrefs->dateseps;
1003 $how = user_date_format(); // 0 = us/ca, 1 = eu, au, nz, 2 = jp, sw
1004 $sep = $dateseps[user_date_sep()]; // date separator
1005 $wstart = (($date_system == 1 || $date_system == 2 || $date_system == 3) ? 6 : ($how == 0 || $how == 3 ? 0 : 1)); // weekstart (sun = 0, mon = 1)
1006 $months = array(_("January"),_("February"),_("March"),_("April"),_("May"),_("June"),_("July"),_("August"),_("September"),_("October"),_("November"),_("December"));
1007 $wdays = array(_("Su"),_("Mo"),_("Tu"),_("We"),_("Th"),_("Fr"),_("Sa"));
1008 $wno = _("W"); // week no
1010 if ($date_system == 1)
1011 list($cyear, $cmon, $cday) = gregorian_to_jalali(date("Y"), date("n"), date("j"));
1012 elseif ($date_system == 2)
1013 list($cyear, $cmon, $cday) = gregorian_to_islamic(date("Y"), date("n"), date("j"));
1017 function positionInfo(object) {
1019 this.getElementLeft = getElementLeft;
1020 function getElementLeft() {
1023 if(typeof(p_elm) == 'object'){
1026 elm = document.getElementById(p_elm);
1028 while (elm != null) {
1030 elm = elm.offsetParent;
1034 this.getElementWidth = getElementWidth;
1035 function getElementWidth(){
1037 if(typeof(p_elm) == 'object'){
1040 elm = document.getElementById(p_elm);
1042 return parseInt(elm.offsetWidth);
1044 this.getElementRight = getElementRight;
1045 function getElementRight(){
1046 return getElementLeft(p_elm) + getElementWidth(p_elm);
1048 this.getElementTop = getElementTop;
1049 function getElementTop() {
1052 if(typeof(p_elm) == 'object'){
1055 elm = document.getElementById(p_elm);
1057 while (elm != null) {
1059 elm = elm.offsetParent;
1063 this.getElementHeight = getElementHeight;
1064 function getElementHeight(){
1066 if(typeof(p_elm) == 'object'){
1069 elm = document.getElementById(p_elm);
1071 return parseInt(elm.offsetHeight);
1073 this.getElementBottom = getElementBottom;
1074 function getElementBottom(){
1075 return getElementTop(p_elm) + getElementHeight(p_elm);
1079 var calendarId = 'CC';
1080 var currentYear = 0;
1081 var currentMonth = 0;
1083 var selectedYear = 0;
1084 var selectedMonth = 0;
1085 var selectedDay = 0;
1086 var months = ['$months[0]','$months[1]','$months[2]','$months[3]','$months[4]','$months[5]','$months[6]','$months[7]','$months[8]','$months[9]','$months[10]','$months[11]'];
1087 var wdays = ['$wdays[0]', '$wdays[1]', '$wdays[2]', '$wdays[3]', '$wdays[4]', '$wdays[5]', '$wdays[6]'];
1088 var tmonths = ['$tmonths[0]','$tmonths[1]','$tmonths[2]','$tmonths[3]','$tmonths[4]','$tmonths[5]','$tmonths[6]','$tmonths[7]','$tmonths[8]','$tmonths[9]','$tmonths[10]','$tmonths[11]','$tmonths[12]'];
1089 var dateField = null;
1090 function getProperty(p_property){
1091 var p_elm = calendarId;
1093 if(typeof(p_elm) == 'object'){
1096 elm = document.getElementById(p_elm);
1101 if(elm[p_property]){
1102 return elm[p_property];
1111 function setElementProperty(p_property, p_value, p_elmId){
1112 var p_elm = p_elmId;
1114 if(typeof(p_elm) == 'object'){
1117 elm = document.getElementById(p_elm);
1119 if((elm != null) && (elm.style != null)){
1121 elm[ p_property ] = p_value;
1124 function setProperty(p_property, p_value) {
1125 setElementProperty(p_property, p_value, calendarId);
1127 function getDaysInMonth(year, month) {
1129 if ($date_system == 1)
1131 return [31,31,31,31,31,31,30,30,30,30,30,(((((((year - ((year > 0) ? 474 : 473)) % 2820) + 474) + 38) * 682) % 2816) < 682 ? 30 : 29)][month-1];
1133 elseif ($date_system == 2)
1135 return [30,29,30,29,30,29,30,29,30,29,30,(((((11 * year) + 14) % 30) < 11) ? 30 : 29)][month-1];
1139 return [31,((!(year % 4 ) && ( (year % 100 ) || !( year % 400 ) ))?29:28),31,30,31,30,31,31,30,31,30,31][month-1];
1143 function getDayOfWeek(year, month, day) {
1145 if ($date_system == 1 || $date_system == 2)
1150 return a - (b * Math.floor(a / b));
1154 return mod(Math.floor((j + 1.5)), 7);
1157 if ($date_system == 1)
1159 var epbase, epyear, t;
1160 epbase = year - ((year >= 0) ? 474 : 473);
1161 epyear = 474 + mod(epbase, 2820);
1162 t = day + ((month <= 7) ? ((month - 1) * 31) : (((month - 1) * 30) + 6)) +
1163 Math.floor(((epyear * 682) - 110) / 2816) + (epyear - 1) * 365 +
1164 Math.floor(epbase / 2820) * 1029983 + (1948320.5 - 1);
1166 elseif ($date_system == 2)
1169 t = Math.floor((11 * year + 3) / 30) + 354 * year + 30 * month -
1170 Math.floor((month - 1) / 2) + day + 1948440 - 385;
1178 var date = new Date(year,month-1,day)
1179 return date.getDay();
1183 this.clearDate = clearDate;
1184 function clearDate() {
1185 dateField.value = '';
1188 this.getWeek = getWeek;
1189 function getWeek(year, month, day) {
1191 if ($how == 0 || $how == 3)
1194 var date = new Date(year,month-1,day);
1195 var D = date.getDay();
1197 date.setDate(date.getDate() + (4 - D));
1198 var YN = date.getFullYear();
1199 var ZBDoCY = Math.floor((date.getTime() - new Date(YN, 0, 1, -6)) / 86400000);
1200 var WN = 1 + Math.floor(ZBDoCY / 7);
1203 this.setDate = setDate;
1204 function setDate(year, month, day) {
1209 if (month < 10) {month = '0' + month;}
1210 if (day < 10) {day = '0' + day;}
1214 month = tmonths[month];
1216 if ($how == 0 || $how == 3)
1218 var dateString = month+'$sep'+day+'$sep'+year;
1220 elseif ($how == 1 || $how == 4)
1222 var dateString = day+'$sep'+month+'$sep'+year;
1224 elseif ($how == 2 || $how == 5)
1226 var dateString = year+'$sep'+month+'$sep'+day;
1229 dateField.value = dateString;
1230 setFocus(dateField.name);
1231 if(dateField.getAttribute('aspect')=='cdate')
1232 setElementProperty('color', (dateField.value==user.date ? 'black':'red'), dateField);
1233 if (dateField.className=='searchbox')
1239 this.changeMonth = changeMonth;
1240 function changeMonth(change) {
1241 currentMonth += change;
1243 if(currentMonth > 12) {
1246 } else if(currentMonth < 1) {
1250 calendar = document.getElementById(calendarId);
1251 calendar.innerHTML = calendarDrawTable();
1253 this.changeYear = changeYear;
1254 function changeYear(change) {
1255 currentYear += change;
1257 calendar = document.getElementById(calendarId);
1258 calendar.innerHTML = calendarDrawTable();
1260 function getCurrentYear() {
1261 var year = new Date().getYear();
1262 if(year < 1900) year += 1900;
1265 function getCurrentMonth() {
1266 return new Date().getMonth() + 1;
1268 function getCurrentDay() {
1269 return new Date().getDate();
1271 function calendarDrawTable() {
1273 var wstart = $wstart;
1274 var wno = ' $wno ';
1276 var startDayOfWeek = getDayOfWeek(currentYear, currentMonth, dayOfMonth);
1277 var daysInMonth = getDaysInMonth(currentYear, currentMonth);
1278 var css_class = null; //CSS class for each day
1279 var table = \"<table cellspacing='0' cellpadding='0' border='0'>\";
1280 table += \"<tr class='header'>\";
1281 table += \" <td colspan='2' class='previous'><a href='javascript:changeCCMonth(-1);'><</a><br><a href='javascript:changeCCYear(-1);'>«</a></td>\";
1282 table += \" <td colspan='4' class='title'>\" + months[currentMonth-1] + \"<br>\" + currentYear + \"</td>\";
1283 table += \" <td colspan='2' class='next'><a href='javascript:changeCCMonth(1);'>></a><br><a href='javascript:changeCCYear(1);'>»</a></td>\";
1286 table += \"<th class='weekno'>\"+wno+\"</th>\";
1287 for (var n=0; n<7; n++)
1288 table += \"<th>\" + wdays[(wstart+n)%7]+\"</th>\";
1290 for(var week=0; week < 6; week++) {
1292 for(var n=0; n < 7; n++) {
1293 dayOfWeek = (wstart+n)%7;
1294 if(week == 0 && startDayOfWeek == dayOfWeek) {
1296 } else if (validDay == 1 && dayOfMonth > daysInMonth) {
1301 if (dayOfMonth > daysInMonth)
1302 table += \"<td class='empty'> </td>\";
1304 table += \"<td class='weekno'>\"+getWeek(currentYear, currentMonth, dayOfMonth)+\"</td>\";
1307 if (dayOfMonth == selectedDay && currentYear == selectedYear && currentMonth == selectedMonth) {
1308 css_class = 'current';
1310 if ($date_system == 1 || $date_system == 2 || $date_system == 3)
1312 } else if (dayOfWeek == 5) {
1316 } else if (dayOfWeek == 0 || dayOfWeek == 6) {
1319 css_class = 'weekend';
1321 css_class = 'weekday';
1323 table += \"<td><a class='\"+css_class+\"' href=\\\"javascript:setCCDate(\"+currentYear+\",\"+currentMonth+\",\"+dayOfMonth+\")\\\">\"+dayOfMonth+\"</a></td>\";
1326 table += \"<td class='empty'> </td>\";
1331 table += \"<tr class='header'><th colspan='8' style='padding: 3px;text-align:center;'><a href='javascript:hideCC();'>$back</a></td></tr>\";
1332 table += \"</table>\";
1336 function show(field) {
1338 if (dateField == field) {
1345 var dateString = new String(dateField.value);
1346 var dateParts = dateString.split('$sep');
1350 selectedMonth = parseInt(dateParts[0],10);
1351 selectedDay = parseInt(dateParts[1],10);
1352 selectedYear = parseInt(dateParts[2],10);
1356 selectedDay = parseInt(dateParts[0],10);
1357 selectedMonth = parseInt(dateParts[1],10);
1358 selectedYear = parseInt(dateParts[2],10);
1362 selectedYear = parseInt(dateParts[0],10);
1363 selectedMonth = parseInt(dateParts[1],10);
1364 selectedDay = parseInt(dateParts[2],10);
1368 selectedDay = parseInt(dateParts[1],10);
1369 selectedMonth = parseInt(tmonths.indexOf(dateParts[0]),10);
1370 selectedYear = parseInt(dateParts[2],10);
1374 selectedDay = parseInt(dateParts[0],10);
1375 selectedMonth = parseInt(tmonths.indexOf(dateParts[1]),10);
1376 selectedYear = parseInt(dateParts[2],10);
1380 selectedYear = parseInt(dateParts[0],10);
1381 selectedMonth = parseInt(tmonths.indexOf(dateParts[1]),10);
1382 selectedDay = parseInt(dateParts[2],10);
1387 if (!(selectedYear && selectedMonth && selectedDay)) {
1389 if ($date_system == 1 || $date_system == 2)
1392 selectedMonth = $cmon;
1393 selectedDay = $cday;
1394 selectedYear = $cyear;
1400 selectedMonth = getCurrentMonth();
1401 selectedDay = getCurrentDay();
1402 selectedYear = getCurrentYear();
1407 currentMonth = selectedMonth;
1408 currentDay = selectedDay;
1409 currentYear = selectedYear;
1410 if(document.getElementById){
1411 calendar = document.getElementById(calendarId);
1412 calendar.innerHTML = calendarDrawTable(currentYear, currentMonth);
1413 var fieldPos = new positionInfo(dateField);
1414 var calendarPos = new positionInfo(calendarId);
1415 var x = fieldPos.getElementLeft();
1416 var y = fieldPos.getElementBottom();
1417 setProperty('left', x + 'px');
1418 setProperty('top', y + 'px');
1419 setProperty('display', 'block');
1421 setElementProperty('left', x + 'px', 'CCIframe');
1422 setElementProperty('top', y + 'px', 'CCIframe');
1423 setElementProperty('width', calendarPos.getElementWidth() + 'px', 'CCIframe');
1424 setElementProperty('height', calendarPos.getElementHeight() + 'px', 'CCIframe');
1425 setElementProperty('display', 'block', 'CCIframe');
1432 setProperty('display', 'none');
1433 setElementProperty('display', 'none', 'CCIframe');
1437 this.visible = visible;
1438 function visible() {
1441 this.can_hide = can_hide;
1445 function date_picker(textField) {
1453 function setCCDate(year, month, day) {
1454 cC.setDate(year, month, day);
1456 function changeCCYear(change) {
1457 cC.changeYear(change);
1459 function changeCCMonth(change) {
1460 cC.changeMonth(change);
1462 window.addEventListener('click', function(e) {
1463 if (document.getElementById('CC').contains(e.target)){} else {
1470 document.write(\"<iframe id='CCIframe' src='javascript:false;' frameBorder='0' scrolling='no'></iframe>\");
1471 document.write(\"<div id='CC'></div>\");";
1473 cache_js_file($fpath, $js);
1475 add_js_ufile($fpath);
1480 function alert($msg)
1482 echo "\n<script type=\"text/javascript\">\n"
1484 . "alert('$msg');\n"
1489 if (!function_exists('_vd'))
1491 function _vd($mixed, $title = '', $exit = false)
1493 $str = (!empty($title) ? ($title .':') : '') .'<pre>';
1494 $str .= print_r($mixed, true); //var_dump($mixed);
1496 display_notification('<table><tr><td>'.$str.'</td></tr></table>');
1502 function _vl($mixed, $title = '', $exit = false)
1504 error_log((!empty($title) ? ($title .':') : '') . print_r($mixed, true));
1509 function display_backtrace($cond=true, $msg='') {
1512 $str = "<center><span class='headingtext'>$msg</span></center>\n";
1515 $str .= get_backtrace(true);
1516 display_error($str);
1521 // FIXME: $payment_services array will be moved to bank_accounts in 2.4.x
1523 if (!isset($payment_services))
1525 $payment_services = array(
1526 'PayPal' => "https://www.paypal.com/xclick?business=<company_email>&item_name=<comment>&amount=<amount>¤cy_code=<currency>",
1530 * Payment link generation. Options provided during invoice generation:
1531 * company_email, comment, amount, currency
1533 function payment_link($name, $options)
1535 global $payment_services;
1537 $link = @$payment_services[$name];
1539 if (!$link) return null;
1541 $patterns = array();
1542 foreach ($options as $id => $option)
1543 $patterns['<'.$id.'>'] = urlencode($options[$id]);
1545 return strtr($link, $patterns);
1548 function trans_editor_link($type, $trans_no)
1550 global $path_to_root;
1552 $editor_url = array(
1553 ST_JOURNAL => "/gl/gl_journal.php?ModifyGL=Yes&trans_no=%d&trans_type=%d",
1554 ST_BANKPAYMENT => "/gl/gl_bank.php?ModifyPayment=Yes&trans_no=%d&trans_type=%d",
1555 ST_BANKDEPOSIT => "/gl/gl_bank.php?ModifyDeposit=Yes&trans_no=%d&trans_type=%d",
1556 ST_BANKTRANSFER => "/gl/bank_transfer.php?ModifyTransfer=Yes&trans_no=%d&trans_type=%d",
1557 ST_SALESINVOICE => "/sales/customer_invoice.php?ModifyInvoice=%d",
1558 ST_CUSTCREDIT => "/sales/credit_note_entry.php?ModifyCredit=%d", // only for free hand credit notes (debtors_trans.order_==0)
1559 ST_CUSTPAYMENT => "/sales/customer_payments.php?trans_no=%d",
1560 ST_CUSTDELIVERY => "/sales/customer_delivery.php?ModifyDelivery=%d",
1561 // 16=> Location Transfer,
1562 // 17=> Inventory Adjustment,
1563 ST_SUPPINVOICE => "/purchasing/supplier_invoice.php?ModifyInvoice=%d",
1564 ST_SUPPCREDIT => "/purchasing/supplier_credit.php?ModifyCredit=%d",
1565 // 21=> Supplier Credit Note,
1566 // 22=> Supplier Payment,
1567 ST_SUPPRECEIVE => "/purchasing/po_receive_items.php?ModifyGRN=%d",
1568 ST_PURCHORDER => "/purchasing/po_entry_items.php?ModifyOrderNumber=%d",
1569 // 28=> Work Order Issue,
1570 // 29=> Work Order Production",
1571 ST_WORKORDER => "/manufacturing/work_order_entry.php?trans_no=%d",
1572 ST_SALESORDER => "/sales/sales_order_entry.php?ModifyOrderNumber=%d",
1573 ST_SALESQUOTE => "/sales/sales_order_entry.php?ModifyQuotationNumber=%d",
1574 // 35=> Cost Update,
1577 return !isset($editor_url[$type]) ? '--' :
1578 (is_closed_trans($type, $trans_no) ? set_icon(ICON_CLOSED, _('Closed')) :
1579 pager_link(_("Edit"), sprintf($editor_url[$type], $trans_no, $type), ICON_EDIT));