Ejemplo n.º 1
0
 function user_in_store_team($whid, $user_id)
 {
     if (user_is_admin($user_id)) {
         return true;
     }
     $sql = "SELECT team_id FROM exten.warehouses WHERE whid='{$whid}'";
     $wh_rslt = db_exec($sql) or errDie("Unable to retrieve stores.");
     $team_id = pg_fetch_result($wh_rslt, 0);
     return user_in_team($team_id, $user_id);
 }
function printCust()
{
    global $_SESSION;
    extract($_REQUEST);
    if (!isset($action)) {
        $action = "listcust";
    }
    /* session var prefix */
    $SPRE = "custview_";
    /* max number of customers in list */
    if (isset($viewall_cust)) {
        $offset = 0;
        define("ACT_SHOW_LIMIT", 2147483647);
    } else {
        define("ACT_SHOW_LIMIT", SHOW_LIMIT);
    }
    if (!isset($fval) && isset($_SESSION["{$SPRE}fval"])) {
        $fval = $_SESSION["{$SPRE}fval"];
    }
    if (!isset($filter) && isset($_SESSION["{$SPRE}filter"])) {
        $filter = $_SESSION["{$SPRE}filter"];
    }
    if (!isset($all) && isset($_SESSION["{$SPRE}all"]) && !isset($filter) && !isset($fval)) {
        $all = $_SESSION["{$SPRE}all"];
    }
    if (isset($filter) && isset($fval) && !isset($all)) {
        if (strlen($filter) > 0) {
            if ($filter == "all") {
                $sqlfilter = " AND (lower(accno) LIKE lower('%{$fval}%') OR lower(surname) LIKE lower('%{$fval}%') OR lower(paddr1) LIKE lower('%{$fval}%') OR lower(addr1) LIKE lower('%{$fval}%') OR lower(del_addr1) LIKE lower('%{$fval}%') OR lower(bustel) LIKE lower('%{$fval}%') OR lower(email) LIKE lower('%{$fval}%') OR lower(vatnum) LIKE lower('%{$fval}%') OR lower(contname) LIKE lower('%{$fval}%') OR lower(tel) LIKE lower('%{$fval}%') OR lower(cellno) LIKE lower('%{$fval}%') OR lower(fax) LIKE lower('%{$fval}%') OR lower(url) LIKE lower('%{$fval}%') OR lower(comments) LIKE lower('%{$fval}%') OR lower(bankname) LIKE lower('%{$fval}%') OR lower(branname) LIKE lower('%{$fval}%') OR lower(brancode) LIKE lower('%{$fval}%') OR lower(bankaccno) LIKE lower('%{$fval}%') OR lower(bankaccname) LIKE lower('%{$fval}%') OR lower(bankacctype) LIKE lower('%{$fval}%'))";
            } else {
                $sqlfilter = " AND lower({$filter}) LIKE lower('%{$fval}%')";
            }
        } else {
            $sqlfilter = "";
        }
        if (isset($_SESSION["{$SPRE}all"])) {
            unset($_SESSION["{$SPRE}all"]);
        }
        $_SESSION["{$SPRE}fval"] = $fval;
        $_SESSION["{$SPRE}filter"] = $filter;
    } else {
        if (isset($_SESSION["{$SPRE}fval"])) {
            unset($_SESSION["{$SPRE}fval"]);
        }
        if (isset($_SESSION["{$SPRE}filter"])) {
            unset($_SESSION["{$SPRE}filter"]);
        }
        $filter = "";
        $fval = "";
        $_SESSION["{$SPRE}all"] = "true";
        $sqlfilter = "";
    }
    $filterarr = array("all" => "Detailed", "surname" => "Company/Name", "init" => "Initials", "accno" => "Account Number", "deptname" => "Department", "category" => "Category", "class" => "Classification");
    $filtersel = extlib_cpsel("filter", $filterarr, $filter, "onChange='applyFilter();'");
    if (isset($export)) {
        $pure = true;
    } else {
        $pure = false;
    }
    if (!$pure) {
        # Set up table to display in
        $printCust_begin = "\n\t    <h3>" . (isset($findcust) ? "Find" : "Current") . " Customers</h3>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t<input type='hidden' name='action' value='{$action}' />\n\t\t<tr>\n\t\t\t<th>.: Filter :.</th>\n\t\t\t<th colspan='2'>.: Search :.</th>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td>{$filtersel}</td>\n\t\t\t<td><input type='text' size='20' id='fval' value='{$fval}'></td>\n\t\t\t<td align='center'><input type='button' value='Search' onClick='applyFilter();' /></td>\n\t\t</tr>\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td align='center'><input type='button' name='all' value='View All' onClick='viewAll();' /></td>\n\t\t</tr>\n\t\t</table>\n\t\t<script>\n\t\t\t/* CRM CODE */\n\t\t\tfunction updateAccountInfo(id, name) {\n\t\t\t\twindow.opener.document.frm_con.accountname.value=name;\n\t\t\t\twindow.opener.document.frm_con.account_id.value=id;\n\t\t\t\twindow.opener.document.frm_con.account_type.value='Customer';\n\t\t\t\twindow.close();\n\t\t\t}\n\n\t\t\t/* AJAX filter code */\n\t\t\tfunction viewAll() {\n\t\t\t\tajaxRequest('" . SELF . "', 'cust_list', AJAX_SET, 'all=t');\n\t\t\t}\n\n\t\t\tfunction applyFilter() {\n\t\t\t\tfilter = getObject('filter').value;\n\t\t\t\tfval = getObject('fval').value;\n\n\t\t\t\tajaxRequest('" . SELF . "', 'cust_list', AJAX_SET, 'filter=' + filter + '&fval=' + fval);\n\t\t\t}\n\n\t\t\tfunction updateOffset(noffset, viewall) {\n\t\t\t\tif (viewall && !noffset) {\n\t\t\t\t\tajaxRequest('" . SELF . "', 'cust_list', AJAX_SET, 'viewall_cust=t');\n\t\t\t\t} else {\n\t\t\t\t\tajaxRequest('" . SELF . "', 'cust_list', AJAX_SET, 'offset=' + noffset);\n\t\t\t\t}\n\t\t\t}\n\t\t</script>\n\t\t<p>\n\t\t<div id='cust_list'>";
    } else {
        $printCust_begin = "";
    }
    /* FIND CUSTOMER START */
    if (!isset($findcust)) {
        $ajaxCust = "";
        if (!$pure) {
            $ajaxCust .= "\n\t\t<form action='statements-email.php' method='get'>\n\t\t<input type='hidden' name='key' value='confirm' />";
        }
        if (!isset($offset) && isset($_SESSION["{$SPRE}offset"])) {
            $offset = $_SESSION["{$SPRE}offset"];
        } else {
            if (!isset($offset)) {
                $offset = 0;
            }
        }
        $_SESSION["{$SPRE}offset"] = $offset;
        # connect to database
        db_connect();
        # counting the number of possible entries
        $sql = "SELECT * FROM customers\n    \t\tWHERE (div = '" . USER_DIV . "' OR  ddiv = '" . USER_DIV . "') {$sqlfilter}\n    \t\tORDER BY surname ASC";
        $rslt = db_exec($sql) or errDie("Error counting matching customers.");
        $custcount = pg_num_rows($rslt);
        # Query server
        $tot = 0;
        $totoverd = 0;
        $i = 0;
        if (!isset($ajaxCust)) {
            $ajaxCust = "";
        }
        /* view offsets */
        if ($offset > 0) {
            $poffset = $offset >= ACT_SHOW_LIMIT ? $offset - ACT_SHOW_LIMIT : 0;
            $os_prev = "<a class='nav' href='javascript: updateOffset(\"{$poffset}\");'>Previous</a>";
        } else {
            $os_prev = "&nbsp;";
        }
        if ($offset + ACT_SHOW_LIMIT > $custcount) {
            $os_next = "&nbsp;";
        } else {
            $noffset = $offset + ACT_SHOW_LIMIT;
            $os_next = "<a class='nav' href='javascript: updateOffset(\"{$noffset}\");'>Next</a>";
        }
        if ($os_next != "&nbsp;" || $os_prev != "&nbsp;") {
            $os_viewall = "| <a class='nav' href='javascript: updateOffset(false, true);'>View All</a>";
        } else {
            $os_viewall = "";
        }
        $ajaxCust .= "\n\t<table " . TMPL_tblDflts . ">\n\t<tr>\n\t\t<td colspan='20'>\n\t\t<table width='100%' border='0'>\n\t\t<tr>\n\t\t\t<td align='right' width='50%'>{$os_prev}</td>\n\t\t\t<td align='left' width='50%'>{$os_next} {$os_viewall}</td>\n\t\t</tr>\n\t\t</table>\n\t\t</td>\n\t</tr>\n\t<tr>\n\t\t<th>Acc no.</th>\n\t\t<th>Company/Name</th>\n\t\t<th>Tel</th>\n\t\t<th>Category</th>\n\t\t<th>Class</th>\n\t\t<th colspan='2'>Balance</th>\n\t\t<th>Overdue</th>\n\t\t" . ($pure ? "" : "<th colspan='11'>Options</th>") . "\n\t</tr>";
        /* query object for cashbook */
        $cashbook = new dbSelect("cashbook", "cubit");
        $custRslt = new dbSelect("customers", "cubit", grp(m("where", "(div ='" . USER_DIV . "' or ddiv='" . USER_DIV . "') {$sqlfilter}"), m("order", "surname ASC"), m("offset", $offset), m("limit", ACT_SHOW_LIMIT)));
        $custRslt->run();
        if ($custRslt->num_rows() < 1) {
            $ajaxCust .= "\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td colspan='20'><li>There are no Customers matching the criteria entered.</li></td>\n\t\t</tr>";
        } else {
            while ($cust = $custRslt->fetch_array()) {
                if (!user_in_team($cust["team_id"], USER_ID)) {
                    continue;
                }
                # Check type of age analisys
                if (div_isset("DEBT_AGE", "mon")) {
                    $overd = ageage($cust['cusnum'], $cust['overdue'] / 30 - 1, $cust['location']);
                } else {
                    $overd = age($cust['cusnum'], $cust['overdue'] - 1, $cust['location']);
                }
                if ($overd < 0) {
                    $overd = 0;
                }
                if ($overd > $cust['balance']) {
                    $overd = $cust['balance'];
                }
                if ($cust["location"] == "int") {
                    $cur = qryCurrency($cust["fcid"], "rate");
                    $rate = $cur["rate"];
                    if ($rate != 0) {
                        $totoverd += $overd * $rate;
                    } else {
                        $totoverd += $overd;
                    }
                } else {
                    $totoverd += $overd;
                }
                if (!$pure) {
                    /* check if customer may be removed */
                    $cashbook->setOpt(grp(m("where", "cusnum='{$cust['cusnum']}' AND banked='no' AND div='" . USER_DIV . "'")));
                    $cashbook->run();
                    if ($cashbook->num_rows() <= 0 && $cust['balance'] == 0) {
                        $rm = "<td><a href='cust-rem.php?cusnum={$cust['cusnum']}'>Remove</a></td>";
                    } else {
                        $rm = "<td></td>";
                    }
                }
                if (strlen(trim($cust['bustel'])) < 1) {
                    $cust['bustel'] = $cust['tel'];
                }
                $cust['balance'] = sprint($cust['balance']);
                if ($cust["location"] == "int") {
                    if ($rate != 0.0) {
                        $tot = $tot + $cust['fbalance'] * $rate;
                    } else {
                        $tot = $tot + $cust['balance'];
                    }
                } else {
                    $tot = $tot + $cust['balance'];
                }
                /* determine which template to use when printing customer invoices */
                if (templateScript("invoices") != "pdf/cust-pdf-print-invoices.php") {
                    $template = "pdf/pdf-tax-invoice.php?type=cusprintinvoices";
                } else {
                    $template = "pdf/pdf-tax-invoice.php?type=cusprintinvoices";
                }
                $inv = "";
                $inv = "\n\t\t\t<td>\n\t\t\t\t<a href='{$template}&cusnum={$cust['cusnum']}' target='_blank'>Print Invoices</a>\n\t\t\t</td>";
                # Locations drop down
                $locs = array("loc" => "Local", "int" => "International", "" => "");
                $loc = $locs[$cust['location']];
                $fbal = "--";
                $ocurr = CUR;
                $trans = "\n\t\t\t<td>\n\t\t\t\t<a href='core/cust-trans.php?cusnum={$cust['cusnum']}'>Transaction</a>\n\t\t\t</td>";
                if ($cust['location'] == 'int') {
                    $fbal = "{$cust['currency']} {$cust['fbalance']}";
                    $ocurr = CUR;
                    $trans = "\n\t\t\t\t<td>\n\t\t\t\t\t<a href='core/intcust-trans.php?cusnum={$cust['cusnum']}'>Transaction</a>\n\t\t\t\t</td>";
                    $receipt = "<a href='bank/bank-recpt-inv-int.php?cusid={$cust['cusnum']}&amp;cash=yes'>Add Receipt</a>";
                } else {
                    $receipt = "<a href='bank/bank-recpt-inv.php?cusnum={$cust['cusnum']}&amp;cash=yes'>Add Receipt</a>";
                }
                # alternate bgcolor
                $bgColor = bgcolor($i);
                $ajaxCust .= "<tr class='" . bg_class() . "'>";
                if ($action == "contact_acc") {
                    $updatelink = "javascript: updateAccountInfo(\"{$cust['cusnum']}\", \"{$cust['accno']}\");";
                    $ajaxCust .= "\n\t\t\t\t\t<td><a href='{$updatelink}'>{$cust['accno']}</a></td>\n\t\t\t\t\t<td><a href='{$updatelink}'>{$cust['surname']}</a></td>";
                } else {
                    if ($action == "select") {
                        $ajaxCust .= "\n\t\t\t\t\t<td><a href='" . SELF . "?key=select&cusnum={$cust['cusnum']}&" . frmupdate_passon(true) . "'>{$cust['accno']}</a></td>\n\t\t\t\t\t<td><a href='" . SELF . "?key=select&cusnum={$cust['cusnum']}&" . frmupdate_passon(true) . "'>{$cust['surname']}</a></td>";
                    } else {
                        $ajaxCust .= "\n\t\t\t\t\t<td>{$cust['accno']}</td>\n\t\t\t\t\t<td>{$cust['surname']}</td>";
                    }
                }
                $ajaxCust .= "\n\t\t\t\t\t<td>{$cust['bustel']}</td>\n\t\t\t\t\t<td>{$cust['catname']}</td>\n\t\t\t\t\t<td>{$cust['classname']}</td>\n\t\t\t\t\t<td align='right' nowrap>{$ocurr} {$cust['balance']}</td>\n\t\t\t\t\t<td align='center' nowrap>{$fbal}</td>\n\t\t\t\t\t<td align='right' nowrap>{$ocurr} {$overd}</td>";
                if (!$pure) {
                    if ($action == "listcust") {
                        $ajaxCust .= "\n\t\t\t\t\t\t<td>{$receipt}</td>\n\t\t\t\t\t\t<td><a href='delnote-report.php?cusnum={$cust['cusnum']}'>Outstanding Stock</a></td>\n\t\t\t\t\t\t<td><a href='cust-det.php?cusnum={$cust['cusnum']}'>Details</a></td>\n\t\t\t\t\t\t<td><a href='customers-new.php?cusnum={$cust['cusnum']}'>Edit</a></td>\n\t\t\t\t\t\t<td><a href='#' onClick='openPrintWin(\"cust-stmnt.php?cusnum={$cust['cusnum']}\");'>Statement</a></td>\n\t\t\t\t\t\t{$trans} {$inv}";
                        if ($cust['blocked'] == 'yes') {
                            $ajaxCust .= "<td><a href='cust-unblock.php?cusnum={$cust['cusnum']}'>Unblock</a></td>";
                        } else {
                            $ajaxCust .= "<td><a href='cust-block.php?cusnum={$cust['cusnum']}'>Block</a></td>";
                        }
                        $ajaxCust .= "<td><a href='transheks/pricelist_send.php?cusnum={$cust['cusnum']}'>Send Pricelist</a></td>";
                        $ajaxCust .= "{$rm} <td><a href='conper-add.php?type=cust&amp;id={$cust['cusnum']}'>Add Contact</a></td>\n\t\t\t\t\t<td><input type='checkbox' name='cids[]' value='{$cust['cusnum']}' /></td>";
                    } else {
                        $ajaxCust .= "\n\t\t\t\t\t\t<td align=center>\n\t\t\t\t\t\t\t<a href='javascript: popupSized(\"cust-det.php?cusnum={$cust['cusnum']}\", \"custdetails\", 550, 400, \"\");'>Details</a>\n\t\t\t\t\t\t</td>";
                    }
                }
                $ajaxCust .= "</tr>";
            }
            $bgColor = bgcolor($i);
            $tot = sprint($tot);
            $totoverd = sprint($totoverd);
            $i--;
            $ajaxCust .= "\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td colspan='5'>Total Amount Outstanding, from {$i} " . ($i > 1 ? "clients" : "client") . "</td>\n\t\t\t<td align='right' nowrap>" . CUR . " {$tot}</td>\n\t\t\t<td></td>\n\t\t\t<td align='right' nowrap>" . CUR . " {$totoverd}</td>\n\t\t\t" . ($pure ? "" : "<td colspan='11' align='right'><input type='submit' value='Email Statements' /></td>") . "\n\t\t</tr>";
            if (!$pure) {
                $ajaxCust .= "\n\t\t\t<tr>\n\t\t\t\t<td colspan='20'>\n\t\t\t\t<table width='100%' border='0'>\n\t\t\t\t<tr>\n\t\t\t\t\t<td align='right' width='50%'>{$os_prev}</td>\n\t\t\t\t\t<td align='left' width='50%'>{$os_next} {$os_viewall}</td>\n\t\t\t\t</tr>\n\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>";
            }
        }
        if ($pure) {
            $ajaxCust .= "</table>";
        } else {
            $ajaxCust .= "\n\t\t" . TBL_BR . "\n\t\t</table>\n\t\t</form>\n\t\t<form action='" . SELF . "' method='post'>\n\t\t<table>\n\t\t\t<input type='hidden' name='export' value='yes' />\n\t\t\t<input type='hidden' name='filter' value='{$filter}' />\n\t\t\t<input type='hidden' name='fval' value='{$fval}' />\n\t\t\t<tr>\n\t\t\t\t<td colspan='3'><input type='submit' value='Export to Spreadsheet' /></td>\n\t\t\t</tr>\n\t\t</table>\n\t\t</form>";
        }
        /* FIND CUSTOMER END */
    } else {
        $ajaxCust = "";
    }
    $printCust_end = "\n\t</div>";
    if (!$pure) {
        $printCust_end .= mkQuickLinks(ql("customers-new.php", "Add New Customer"));
    }
    if (AJAX) {
        return $ajaxCust;
    } else {
        return "{$printCust_begin}{$ajaxCust}{$printCust_end}";
    }
}
Ejemplo n.º 3
0
function listLeads()
{
    global $_GET, $_SESSION;
    global $mail_sender;
    extract($_GET);
    $OUTPUT = "";
    // store unset variables so different commands remember previous values
    // this way u can search, and go through leads, suppliers and customers with the same search
    $fields = array();
    $fields["key"] = "";
    $fields["fields"] = "";
    $fields["filter"] = "";
    $fields["offset"] = 0;
    $fields["action"] = "viewcon";
    $fields["frm_day"] = "";
    $fields["frm_month"] = "";
    $fields["frm_year"] = "";
    $fields["to_day"] = "";
    $fields["to_month"] = "";
    $fields["to_year"] = "";
    $fields["salespn"] = "";
    foreach ($fields as $var_name => $value) {
        if (!isset(${$var_name})) {
            ${$var_name} = $value;
        }
    }
    $offset += 0;
    $pass_filter = $filter;
    // stores the filter so it can be passed on cleanly
    // format the filter
    if (!isset($filter) || $filter == 'all') {
        $filter = "()";
    } else {
        if (isset($key) && $key == "search") {
            $filter = "(" . str_replace(" ", "|", $filter) . ")";
        } else {
            $filter = "^({$filter})";
        }
    }
    // create the fields array
    if (!isset($field) || !isset($key) || $key != "search") {
        $fields_look[] = "surname";
    } else {
        $fields_look = explode(",", $field);
    }
    // set the $ref var
    //if ( ! isset($ref) )
    $ref = "leads";
    // select the type of lead to view
    if ($ref == "suppliers") {
        $pgref = "ref='Supplier'";
    } elseif ($ref == "customers") {
        $pgref = "ref='Customer'";
    } else {
        $pgref = "ref <> 'Supplier' AND ref <> 'Customer'";
    }
    // create the actual conditions
    $sql_filters = array();
    foreach ($fields_look as $arr => $arrval) {
        $sql_filters[] = "{$arrval} ~* '{$filter}'";
    }
    $sql_filters = "(" . implode(" OR ", $sql_filters) . ")";
    // count the results first
    $sql = "SELECT COUNT(id) FROM leads\r\n\t\tWHERE {$pgref}\r\n\t\t\tAND {$sql_filters}\r\n\t\t\tAND ( (\r\n\t\t\t\tassigned_to = '{$_SESSION['USER_NAME']}'\r\n\t\t\t\tAND con = 'Yes'\r\n\t\t\t) OR (\r\n\t\t\t\tcon = 'No'\r\n\t\t\t) )";
    db_conn("crm");
    $rslt = db_exec($sql);
    $result_count = pg_fetch_result($rslt, 0, 0);
    // execute the query
    $sql = "SELECT id, name, surname, title, accountname, tell, team_id, email FROM leads\r\n\t\tWHERE {$pgref}\r\n\t\t\tAND {$sql_filters}\r\n\t\t\tAND ( (\r\n\t\t\t\tassigned_to = '{$_SESSION['USER_NAME']}'\r\n\t\t\t\tAND con = 'Yes'\r\n\t\t\t) OR (\r\n\t\t\t\tcon = 'No'\r\n\t\t\t) ) ORDER BY surname LIMIT " . CONTACT_DISPLAY_AMOUNT . " OFFSET {$offset}";
    db_conn("crm");
    $rslt = db_exec($sql);
    // temp vars
    $cellcolor[0] = TMPL_tblDataColor1;
    $cellcolor[1] = TMPL_tblDataColor2;
    $cellcolor[2] = TMPL_tblDataColorOver;
    // generate the leads list from Cubit results
    $lead_data = "";
    $i = 0;
    while ($row = pg_fetch_array($rslt)) {
        if (!user_in_team($row["team_id"], USER_ID)) {
            continue;
        }
        // create the event data for the row
        $rowname = "conrow_{$row['id']}";
        $mmove_events = "\r\n\t\t\tonMouseOver = 'javascript: changeLeadRowColor(\"{$rowname}\",\"{$cellcolor['2']}\");'\r\n\t\t\tonMouseOut = 'javascript: changeLeadRowColor(\"{$rowname}\",\"{$cellcolor[$i]}\");'";
        // create the row with it's information
        $fullname = "";
        if (!empty($row["name"])) {
            $fullname .= "{$row['name']} ";
        }
        $fullname .= "{$row['surname']}";
        if ($action == "viewcon") {
            $href_action = "javascript: viewLead(\"{$row['id']}\")";
        } else {
            if ($action == "reportsto") {
                $href_action = "javascript: updateReportsTo(\"{$row['id']}\", \"{$fullname}\")";
            }
        }
        $lead_data .= "\r\n\t\t\t<tr id='{$rowname}' {$mmove_events} bgcolor='{$cellcolor[$i]}'>\r\n\t\t\t\t<td><a href='{$href_action}'>{$fullname}</a></td>";
        $lead_data .= "\r\n\t\t\t\t<td>{$row['title']}</td>\r\n\t\t\t\t<td>{$row['accountname']}</td>\r\n\t\t\t\t<td>{$row['tell']}</td>\r\n\t\t\t\t<td align=center><a href='{$mail_sender}{$row['email']}' target=rightframe>{$row['email']}</a></td>\r\n\t\t\t\t<td>\r\n\t\t\t\t\t<a href='../groupware/today.php?key=future'>\r\n\t\t\t\t\t\tDate/s to be contacted\r\n\t\t\t\t\t</a>\r\n\t\t\t\t</td>\r\n\t\t\t</tr>";
        $i = ++$i % 2;
        // select the color of the next row (this way is neat little formula i just thought up)
    }
    // if no data has been found, make a default cell telling this
    if ($lead_data == "") {
        $lead_data = "<tr bgcolor='{$cellcolor['0']}'><td colspan=6>No leads found</td></tr>";
    }
    // the select filter list
    $flist = "<font size=2><b>";
    $flist .= "<a class=nav href='leads_list.php?ref={$ref}&action={$action}&filter=0";
    for ($i = ord('1'); $i <= ord('9'); $i++) {
        $flist .= "|" . chr($i);
    }
    $flist .= "'>#</a> ";
    for ($i = ord('A'); $i <= ord('Z'); $i++) {
        $flist .= "<a class=nav href='leads_list.php?ref={$ref}&action={$action}&filter=" . chr($i) . "|" . chr($i + 32) . "'>" . chr($i) . "</a> ";
    }
    $flist .= "<a class=nav href='leads_list.php?ref={$ref}&action={$action}'>All</a></b></font>";
    // set which is selected under the lead type selection box
    $refselected_leads = "";
    $refselected_suppliers = "";
    $refselected_customers = "";
    if ($ref == "suppliers") {
        $refselected_suppliers = "selected";
    } else {
        if ($ref == "customers") {
            $refselected_customers = "selected";
        } else {
            $refselected_leads = "selected";
        }
    }
    // Sales person
    db_conn("exten");
    $sql = "SELECT * FROM salespeople WHERE div='" . USER_DIV . "' ORDER BY salesp ASC";
    $rslt = db_exec($sql) or errDie("Unable to retrieve sales people from Cubit.");
    $salespn_out = "<select name='salespn' style='width: 100%'>";
    while ($salespn_data = pg_fetch_array($rslt)) {
        if ($salespn == $salespn_data["salespid"]) {
            $selected = "selected";
        } else {
            $selected = "";
        }
        $salespn_out .= "<option value='{$salespn_data['salespid']}'>{$salespn_data['salesp']}</option>";
    }
    $salespn_out .= "</select>";
    // create the output
    $OUTPUT = "\r\n\t<script>\r\n\t\t// leads scripts\r\n\t\tfunction changeLeadRowColor(obj, tocolor) {\r\n\t\t\tgetObjectById(obj).style.background=tocolor;\r\n\t\t}\r\n\r\n\t\tfunction viewLead(id) {\r\n\t\t\tpopupOpen('leads_view.php?id=' + id,'lead_popup','scrollbars=yes,width=720,height=600');\r\n\t\t}\r\n\r\n\t\tfunction updateReportsTo(id, name) {\r\n\t\t\twindow.opener.document.frm_con.reports_to.value=name;\r\n\t\t\twindow.opener.document.frm_con.reports_to_id.value=id;\r\n\t\t\twindow.close();\r\n\t\t}\r\n\t</script>\r\n\t<center>\r\n\t<table " . TMPL_tblDflts . ">\r\n\t\t<tr class='" . bg_class() . "'>\r\n\t\t\t<td colspan='4'>\r\n\t\t\t\t<form method='POST' action='" . SELF . "'>\r\n\t\t\t\t\t<input type='hidden' name='key' value='search'>\r\n\t\t\t\t\t<input type='hidden' name='field' value='name,surname,comp,email,padd,hadd'>\r\n\t\t\t\t\t<input type='hidden' name='ref' value='{$ref}'>\r\n\t\t\t\t\t<input type='hidden' name='action' value='{$action}'>\r\n\t\t\t\t\t<input type='text' name='filter' value='' style='width: 100%'>\r\n\t\t\t</td>\r\n\t\t\t<td>\r\n\t\t\t\t\t<input type='submit' value='search' style='width: 100%'>\r\n\t\t\t\t</form>\r\n\t\t\t</td>\r\n\t\t</tr>\r\n\t</table>\r\n\r\n\t<table width='100%' " . TMPL_tblDflts . ">\r\n\t<tr>\r\n\t\t<td align='left' nowrap><font size='2'><b>";
    if ($action == "viewcon") {
        $OUTPUT .= "<a class='nav' href=\"leads_new.php\">New Lead</a></b></font>";
    }
    $OUTPUT .= "\r\n\t\t</td>\r\n\t</tr>\r\n\t<tr>\r\n\t\t<td width='80%' align='center' nowrap>\r\n\t\t\t{$flist}\r\n\t\t</td>\r\n\t\t<td width='20%' align='right' nowrap>\r\n\t\t\t<form method='POST' action='" . SELF . "'>\r\n\t\t\t\t<input type='hidden' name='filter' value='{$pass_filter}'>\r\n\t\t\t\t<input type='hidden' name='key' value='{$key}'>\r\n\t\t\t\t<input type='hidden' name='fields' value='{$fields}'>\r\n\t\t\t\t<input type='hidden' name='action' value='{$action}'>\r\n\t\t\t</form>\r\n\t\t</td>\r\n\t</tr>\r\n\t<tr>\r\n\t\t<td width='100%' colspan='2'>\r\n\t\t<table width='100%' cellpadding='1' cellspacing='0'>";
    // previous images
    if ($offset < CONTACT_DISPLAY_AMOUNT) {
        $go_previous = "\r\n\t\t\t<font color='#9C999C'>\r\n\t\t\t<img src='go_start_off.gif'> Start\r\n\t\t\t<img src='go_previous_off.gif'> Previous\r\n\t\t\t</font>";
    } else {
        $go_previous = "\r\n\t\t\t<a href='" . SELF . "?ref={$ref}&action={$action}&key={$key}&fields={$fields}&filter={$pass_filter}&offset=0'\r\n\t\t\t\t\tid=leads_nextprevious>\r\n\t\t\t\t<img border=0 src='go_start.gif'> Start\r\n\t\t\t</a>\r\n\t\t\t<a href='" . SELF . "?ref={$ref}&action={$action}&key={$key}&fields={$fields}&filter={$pass_filter}&offset=" . ($offset - CONTACT_DISPLAY_AMOUNT) . "'\r\n\t\t\t\t\tid=leads_nextprevious>\r\n\t\t\t\t<img border=0 src='go_previous.gif'> Previous\r\n\t\t\t</a>";
    }
    if ($offset + CONTACT_DISPLAY_AMOUNT >= $result_count) {
        $go_next = "\r\n\t\t\t<font color='#9C999C'>\r\n\t\t\tNext <img src='go_next_off.gif'>\r\n\t\t\tEnd <img src='go_end_off.gif'>\r\n\t\t\t</font>";
    } else {
        $go_next = "\r\n\t\t\t<a href='" . SELF . "?ref={$ref}&action={$action}&key={$key}&fields={$fields}&filter={$pass_filter}&offset=" . ($offset + CONTACT_DISPLAY_AMOUNT) . "'\r\n\t\t\t\t\tid=leads_nextprevious>\r\n\t\t\t\tNext <img border=0 src='go_next.gif'>\r\n\t\t\t</a>\r\n\t\t\t<a href='" . SELF . "?ref={$ref}&action={$action}&key={$key}&fields={$fields}&filter={$pass_filter}&offset=" . ($result_count - CONTACT_DISPLAY_AMOUNT) . "'\r\n\t\t\t\t\tid=leads_nextprevious>\r\n\t\t\t\tEnd <img border=0 src='go_end.gif'>\r\n\t\t\t</a>";
    }
    $OUTPUT .= "<tr>\r\n\t\t\t<td colspan=6 bgcolor='#eeeeee' height='15' align=right>\r\n\t\t\t\t{$go_previous}&nbsp;&nbsp;\r\n\t\t\t\t(" . ($offset + 1) . " - " . ($offset + CONTACT_DISPLAY_AMOUNT <= $result_count ? $offset + CONTACT_DISPLAY_AMOUNT : $result_count) . " of {$result_count})\r\n\t\t\t\t&nbsp;&nbsp;{$go_next}\r\n\t\t\t</td>\r\n\t\t</tr>\r\n\t\t<tr>";
    // table heading style
    $head_s = "background='header_bg2.gif' height=20 align=left";
    $OUTPUT .= "\t<td {$head_s}><b>Company/Name</b></td>\r\n\t\t\t<td {$head_s}><b>Title</b></td>\r\n\t\t\t<td {$head_s}><b>Account</b></td>\r\n\t\t\t<td {$head_s}><b>Tel</b></td>\r\n\t\t\t<td {$head_s}><b>Email</b></td>\r\n\t\t\t<td {$head_s}><b>Options</b></td>";
    // finish the output
    $OUTPUT .= "\t\t</tr>\r\n\t\t\t\t{$lead_data}\r\n\t\t\t</table>\r\n\t\t</td>\r\n\t</tr>\r\n\t</table>";
    return $OUTPUT;
}
function printCust()
{
    global $_SESSION;
    extract($_REQUEST);
    if (!isset($action)) {
        $action = "listcust";
    }
    $sqlfilter = "";
    $printCust_begin = "<h2>View Customers</h2>";
    $ajaxCust = "";
    $ajaxCust .= "\n\t<form action='statements-email.php' method='get'>\n\t<input type='hidden' name='key' value='confirm' />";
    if (!isset($offset) && isset($_SESSION["offset"])) {
        $offset = $_SESSION["offset"];
    } else {
        if (!isset($offset)) {
            $offset = 0;
        }
    }
    $_SESSION["offset"] = $offset;
    # connect to database
    db_connect();
    # counting the number of possible entries
    $sql = "SELECT * FROM customers\n    \t\tWHERE (div = '" . USER_DIV . "' OR  ddiv = '" . USER_DIV . "') {$sqlfilter}\n    \t\tORDER BY surname ASC";
    $rslt = db_exec($sql) or errDie("Error counting matching customers.");
    $custcount = pg_num_rows($rslt);
    # Query server
    $tot = 0;
    $totoverd = 0;
    $i = 0;
    $ajaxCust .= "\n\t<table " . TMPL_tblDflts . ">\n\n\t<tr>\n\t\t<th>Acc no.</th>\n\t\t<th>Company/Name</th>\n\t\t<th>Tel</th>\n\t\t<th>Category</th>\n\t\t<th>Class</th>\n\t\t<th colspan='2'>Balance</th>\n\t\t<th>Overdue</th>\n\t</tr>";
    /* query object for cashbook */
    $cashbook = new dbSelect("cashbook", "cubit");
    $custRslt = new dbSelect("customers", "cubit", grp(m("where", "(div ='" . USER_DIV . "' or ddiv='" . USER_DIV . "') {$sqlfilter}"), m("order", "surname ASC"), m("offset", $offset), m("limit", 100)));
    $custRslt->run();
    if ($custRslt->num_rows() < 1) {
        $ajaxCust .= "\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td colspan='20'><li>There are no Customers matching the criteria entered.</li></td>\n\t\t</tr>";
    } else {
        while ($cust = $custRslt->fetch_array()) {
            if (!user_in_team($cust["team_id"], USER_ID)) {
                continue;
            }
            # Check type of age analisys
            if (div_isset("DEBT_AGE", "mon")) {
                $overd = ageage($cust['cusnum'], $cust['overdue'] / 30 - 1, $cust['location']);
            } else {
                $overd = age($cust['cusnum'], $cust['overdue'] - 1, $cust['location']);
            }
            if ($overd < 0) {
                $overd = 0;
            }
            if ($overd > $cust['balance']) {
                $overd = $cust['balance'];
            }
            if ($cust["location"] == "int") {
                $cur = qryCurrency($cust["fcid"], "rate");
                $rate = $cur["rate"];
                if ($rate != 0) {
                    $totoverd += $overd * $rate;
                } else {
                    $totoverd += $overd;
                }
            } else {
                $totoverd += $overd;
            }
            /* check if customer may be removed */
            $cashbook->setOpt(grp(m("where", "cusnum='{$cust['cusnum']}' AND banked='no' AND div='" . USER_DIV . "'")));
            $cashbook->run();
            if (strlen(trim($cust['bustel'])) < 1) {
                $cust['bustel'] = $cust['tel'];
            }
            $cust['balance'] = sprint($cust['balance']);
            if ($cust["location"] == "int") {
                if ($rate != 0.0) {
                    $tot = $tot + $cust['fbalance'] * $rate;
                } else {
                    $tot = $tot + $cust['balance'];
                }
            } else {
                $tot = $tot + $cust['balance'];
            }
            # Locations drop down
            $locs = array("loc" => "Local", "int" => "International", "" => "");
            $loc = $locs[$cust['location']];
            $fbal = "--";
            $ocurr = CUR;
            # alternate bgcolor
            $bgColor = bgcolor($i);
            $ajaxCust .= "<tr class='" . bg_class() . "'>";
            if ($action == "contact_acc") {
                $updatelink = "javascript: updateAccountInfo(\"{$cust['cusnum']}\", \"{$cust['accno']}\");";
                $ajaxCust .= "\n\t\t\t\t\t<td><a href='{$updatelink}'>{$cust['accno']}</a></td>\n\t\t\t\t\t<td><a href='{$updatelink}'>{$cust['surname']}</a></td>";
            } else {
                if ($action == "select") {
                    $ajaxCust .= "\n\t\t\t\t\t<td><a href='" . SELF . "?key=select&cusnum={$cust['cusnum']}&" . frmupdate_passon(true) . "'>{$cust['accno']}</a></td>\n\t\t\t\t\t<td><a href='" . SELF . "?key=select&cusnum={$cust['cusnum']}&" . frmupdate_passon(true) . "'>{$cust['surname']}</a></td>";
                } else {
                    $ajaxCust .= "\n\t\t\t\t\t<td>{$cust['accno']}</td>\n\t\t\t\t\t<td>{$cust['surname']}</td>";
                }
            }
            $ajaxCust .= "\n\t\t\t\t\t<td>{$cust['bustel']}</td>\n\t\t\t\t\t<td>{$cust['catname']}</td>\n\t\t\t\t\t<td>{$cust['classname']}</td>\n\t\t\t\t\t<td align='right' nowrap>{$ocurr} {$cust['balance']}</td>\n\t\t\t\t\t<td align='center' nowrap>{$fbal}</td>\n\t\t\t\t\t<td align='right' nowrap>{$ocurr} {$overd}</td>";
            $ajaxCust .= "</tr>";
        }
        $bgColor = bgcolor($i);
        $tot = sprint($tot);
        $totoverd = sprint($totoverd);
        $i--;
        $ajaxCust .= "\n\t\t<tr class='" . bg_class() . "'>\n\t\t\t<td colspan='5'>Total Amount Outstanding, from {$i} " . ($i > 1 ? "clients" : "client") . "</td>\n\t\t\t<td align='right' nowrap>" . CUR . " {$tot}</td>\n\t\t\t<td></td>\n\t\t\t<td align='right' nowrap>" . CUR . " {$totoverd}</td>\n\t\t</tr>";
    }
    $ajaxCust .= "\n\t\t" . TBL_BR . "\n\t\t</table>\n\t\t</form>";
    $printCust_end = "\n\t</div>";
    if (AJAX) {
        return $ajaxCust;
    } else {
        return "{$printCust_begin}{$ajaxCust}{$printCust_end}";
    }
}