function preprocess() { global $FANNIE_PLUGIN_LIST, $FANNIE_PLUGIN_SETTINGS; if (!isset($FANNIE_PLUGIN_LIST) || !in_array('CoopCred', $FANNIE_PLUGIN_LIST)) { $this->errors .= _("Error: The Coop Cred Plugin is not enabled."); return True; } if (!array_key_exists('CoopCredDatabase', $FANNIE_PLUGIN_SETTINGS) || $FANNIE_PLUGIN_SETTINGS['CoopCredDatabase'] == "") { $this->errors .= _("Error: Coop Cred Database not named in Plugin Settings."); return True; } /* Get values from the Whole-Project (Plugin) config table. */ $this->first = 0; if (FormLib::get_form_value('action') == '') { $dbc = FannieDB::get($FANNIE_PLUGIN_SETTINGS['CoopCredDatabase']); $config = new CCredConfigModel($dbc); $id = FormLib::get_form_value('configno') != '' ? (int) FormLib::get_form_value('configno') : 1; $config->configID($id); if (!$config->load()) { // Create the initial config record with default values. $saved = $config->save(); if ($saved === False) { $this->errors .= _("Error: Could not create initial " . "Coop Cred configuration record."); return True; } } $this->first = 1; } $this->authUserNumber = 0; $authName = FannieAuth::checkLogin(); if (!($authName == 'null' || $authName == 'init' || $authName == False)) { $this->authUserNumber = FannieAuth::getUID($authName); } /* The first (unless this is an update) time proceed directly to edit. */ if ($this->first) { return True; } /* Support ajax calls to this program. * If there is a form submission with an action go do it. * The form submission may be via AJAX instead of <form ...> * with action= in the query string with other parameters. */ if (FormLib::get_form_value('action') !== '') { $this->ajax_response(FormLib::get_form_value('action')); /* How to handle errors/problems esp. in save? * Possibly code readinessCheck() */ return False; } /* If the call was not by form, e.g. from the initial menu * or the <form action=> is '' (when does that happen?) * FanniePage::draw_page() continues to $this->body_content() * which returns the the program-select form. */ return True; // preprocess() }
/** Log page load in usageStats table @param $dbc [SQLManager] database connection @return [boolean] success / fail */ protected static function logUsage(SQLManager $dbc, $op_db) { if (php_sapi_name() === 'cli') { // don't log cli usage return false; } $user = FannieAuth::checkLogin(); if ($user === false) { $user = '******'; } $prep = $dbc->prepare('INSERT INTO usageStats (tdate, pageName, referrer, userHash, ipHash) VALUES (?, ?, ?, ?, ?)'); $args = array(date('Y-m-d H:i:s'), basename(filter_input(INPUT_SERVER, 'PHP_SELF'))); $referrer = isset($_SERVER['HTTP_REFERER']) ? basename($_SERVER['HTTP_REFERER']) : 'n/a'; $referrer = filter_input(INPUT_SERVER, 'HTTP_REFERER'); $args[] = $referrer === null ? 'n/a' : basename($referrer); $args[] = sha1($user); $ip_addr = filter_input(INPUT_SERVER, 'REMOTE_ADDR'); $args[] = sha1($ip_addr); return $dbc->execute($prep, $args); }
function preprocess() { global $FANNIE_PLUGIN_LIST, $FANNIE_PLUGIN_SETTINGS; if (!isset($FANNIE_PLUGIN_LIST) || !in_array('CoopCred', $FANNIE_PLUGIN_LIST)) { $this->errors .= _("Error: The Coop Cred Plugin is not enabled."); return True; } if (!array_key_exists('CoopCredDatabase', $FANNIE_PLUGIN_SETTINGS) || $FANNIE_PLUGIN_SETTINGS['CoopCredDatabase'] == "") { $this->errors .= _("Error: Coop Cred Database not named in Plugin Settings."); return True; } /* Get values from the Whole-Project (Plugin) config table. */ $dbc = FannieDB::get($FANNIE_PLUGIN_SETTINGS['CoopCredDatabase']); $config = new CCredConfigModel($dbc); $config->configID(1); if (!$config->load()) { $this->errors .= _("Error: Coop Cred configuration not available."); return True; } $this->dummyTenderCode = $config->dummyTenderCode(); $this->dummyDepartment = $config->dummyDepartment(); $this->deptMin = $config->deptMin(); $this->deptMax = $config->deptMax(); $this->dummyBanker = $config->dummyBanker(); $this->bankerMin = $config->bankerMin(); $this->bankerMax = $config->bankerMax(); /* For CCredPrograms.modifiedBy */ $this->authUserNumber = 0; $authName = FannieAuth::checkLogin(); if (!($authName == 'null' || $authName == 'init' || $authName == False)) { $this->authUserNumber = FannieAuth::getUID($authName); } /* Support ajax calls to this program. * If there is a form submission with an action go do it. * The form submission may be via AJAX instead of <form ...> * with action= in the query string with other parameters. */ if (FormLib::get_form_value('action') !== '') { $this->ajax_response(FormLib::get_form_value('action')); /* How to handle errors/problems esp. in save? * Possibly code readinessCheck() */ return False; } /* If the call was not by form, e.g. from the initial menu * or the <form action=> is '' (when does that happen?) * FanniePage::draw_page() continues to $this->body_content() * which returns the the program-select form. */ return True; // preprocess() }
function post_u_view() { global $FANNIE_OP_DB, $FANNIE_URL; $this->addScript('from-search.js'); $ret = '<form action="BatchFromSearch.php" method="post">'; $ret .= '<div class="form-group form-inline">'; $dbc = FannieDB::get($FANNIE_OP_DB); $types = $dbc->query('SELECT batchTypeID, typeDesc, discType FROM batchType'); $discTypes = array(); $ret .= '<select name="batchType" id="batchType" class="form-control" onchange="discountTypeFixup()">'; while ($row = $dbc->fetch_row($types)) { $ret .= sprintf('<option value="%d">%s</option>', $row['batchTypeID'], $row['typeDesc']); $discTypes[] = $row; } $ret .= '</select>'; foreach ($discTypes as $row) { $ret .= sprintf('<input type="hidden" id="discType%d" value="%d" />', $row['batchTypeID'], $row['discType']); } $name = FannieAuth::checkLogin(); $ret .= ' <label>Name</label>: '; $ret .= '<input type="text" class="form-control" name="batchName" value="' . ($name ? $name : 'Batch') . ' ' . date('M j') . '" />'; $ret .= ' <label>Start</label>: <input type="text" class="form-control date-field" id="startDate" value="' . date('Y-m-d') . '" name="startDate" /> '; $ret .= ' <label>End</label>: <input type="text" class="form-control date-field" id="endDate" value="' . date('Y-m-d') . '" name="endDate" /> </div>'; $owners = $dbc->query('SELECT super_name FROM MasterSuperDepts GROUP BY super_name ORDER BY super_name'); $ret .= '<div class="form-group form-inline"> <label>Owner</label>: <select name="batchOwner" class="form-control" id="batchOwner"><option value=""></option>'; while ($row = $dbc->fetch_row($owners)) { $ret .= '<option>' . $row['super_name'] . '</option>'; } $ret .= '<option>IT</option></select> <button type="submit" name="createBatch" value="1" class="btn btn-default">Create Batch</button> </div>'; $ret .= '<hr />'; list($in_sql, $args) = $dbc->safeInClause($this->upcs); $query = 'SELECT p.upc, p.description, p.normal_price, m.superID, MAX(CASE WHEN v.srp IS NULL THEN 0.00 ELSE v.srp END) as srp FROM products AS p LEFT JOIN vendorItems AS v ON p.upc=v.upc AND p.default_vendor_id=v.vendorID LEFT JOIN MasterSuperDepts AS m ON p.department=m.dept_ID WHERE p.upc IN ( ' . $in_sql . ') GROUP BY p.upc, p.description, p.normal_price, m.superID ORDER BY p.upc'; $prep = $dbc->prepare($query); $result = $dbc->execute($prep, $args); $ret .= '<div id="saleTools" class="form-group form-inline">'; $ret .= '<label>Markdown</label> <div class="input-group"> <input type="text" id="mdPercent" class="form-control" value="10" onchange="markDown(this.value);" /> <span class="input-group-addon">%</span> </div> <button type="submit" class="btn btn-default" onclick="markDown($(\'#mdPercent\').val()); return false">Go</button>'; $ret .= ' '; $ret .= '<label>or</label> <div class="input-group"> <span class="input-group-addon">$</span> <input type="text" id="mdDollar" class="form-control" value="0.00" onchange="discount(this.value);" /> </div> <button type="submit" class="btn btn-default" onclick="discount($(\'#mdDollar\').val()); return false">Go</button>'; $ret .= '</div>'; $ret .= '<div id="priceChangeTools" class="form-group form-inline">'; $ret .= '<button type="submit" class="btn btn-default" onclick="useSRPs(); return false;">Use Vendor SRPs</button>'; $ret .= ' '; $ret .= '<select name="preferredVendor" class="form-control" onchange="reCalcSRPs();"> <option value="0">Auto Choose Vendor</option>'; $vendors = new VendorsModel($dbc); foreach ($vendors->find('vendorName') as $vendor) { $ret .= sprintf('<option value="%d">%s</option>', $vendor->vendorID(), $vendor->vendorName()); } $ret .= '</select>'; $ret .= ' '; $ret .= '<label>Markup</label> <div class="input-group"> <input type="text" id="muPercent" class="form-control" value="10" onchange="markUp(this.value);" /> <span class="input-group-addon">%</span> </div> <button type="submit" class="btn btn-default" onclick="markUp($(\'#muPercent\').val()); return false">Go</button>'; $ret .= ' '; $ret .= '<label>Tags</label> <select name="tagset" class="form-control" id="tagset"><option value="">No Tags</option>'; $queues = new ShelfTagQueuesModel($dbc); $ret .= $queues->toOptions(); $ret .= '</select>'; $ret .= '</div>'; $ret .= '<table class="table">'; $ret .= '<tr><th>UPC</th><th>Description</th><th>Retail</th> <th id="newPriceHeader">Sale Price</th></tr>'; $superDetect = array(); while ($row = $dbc->fetch_row($result)) { $ret .= sprintf('<tr class="batchItem"> <td><input type="hidden" name="upc[]" class="itemUPC" value="%s" />%s</td> <td>%s</td> <td>$%.2f<input type="hidden" class="currentPrice" value="%.2f" /></td> <td><div class="input-group"> <span class="input-group-addon">$</span> <input type="text" name="price[]" class="itemPrice form-control" value="0.00" /> <input type="hidden" class="itemSRP" value="%.2f" /> </div> </td> </tr>', $row['upc'], $row['upc'], $row['description'], $row['normal_price'], $row['normal_price'], $row['srp']); if (!isset($superDetect[$row['superID']])) { $superDetect[$row['superID']] = 0; } $superDetect[$row['superID']]++; } $ret .= '</table>'; $ret .= '</form>'; // auto-detect likely owner & tag set by super department $tagPage = array_search(max($superDetect), $superDetect); if ($tagPage !== false) { $this->add_onload_command("\$('#tagset').val({$tagPage});\n"); $this->add_onload_command("\$('#batchOwner').val(\$('#tagset option:selected').text());\n"); } // show sale or price change tools as appropriate $this->add_onload_command('discountTypeFixup();'); // don't let enter key on these fields trigger form submission $this->add_onload_command("\$('#mdPercent').bind('keypress', noEnter);\n"); $this->add_onload_command("\$('#mdDollar').bind('keypress', noEnter);\n"); $this->add_onload_command("\$('#muPercent').bind('keypress', noEnter);\n"); return $ret; }
/** Log updates to many products at once @param $upcs [array] of UPCs @param $type [string] update type @param $user [string] username @return [boolean] success */ public function logManyUpdates($upcs, $type = 'UNKNOWN', $user = false) { if (count($upcs) == 0) { // nothing to log return true; } $col_map = array('upc' => 'p.upc', 'description' => 'description', 'price' => 'normal_price', 'salePrice' => 'special_price', 'cost' => 'cost', 'dept' => 'department', 'tax' => 'tax', 'fs' => 'foodstamp', 'scale' => 'scale', 'modified' => 'modified', 'forceQty' => 'qttyEnforced', 'noDisc' => 'discount', 'inUse' => 'inUse', 'likeCode' => 'likeCode', 'storeID' => 'store_id'); if (!$user) { $user = FannieAuth::getUID(FannieAuth::checkLogin()); } $select_cols = '?,?,'; $insert_cols = 'updateType,' . $this->connection->identifier_escape('user') . ','; foreach ($col_map as $insert => $select) { $insert_cols .= $this->connection->identifier_escape($insert) . ','; // identifier escape does not handle alias prefix $select_cols .= ($select == 'p.upc' ? $select : $this->connection->identifier_escape($select)) . ','; } $insert_cols = substr($insert_cols, 0, strlen($insert_cols) - 1); $select_cols = substr($select_cols, 0, strlen($select_cols) - 1); $args = array($type, $user); $upc_in = ''; foreach ($upcs as $upc) { $args[] = $upc; $upc_in .= '?,'; } $upc_in = substr($upc_in, 0, strlen($upc_in) - 1); $query = 'INSERT INTO prodUpdate (' . $insert_cols . ') SELECT ' . $select_cols . ' FROM products AS p LEFT JOIN upcLike AS u ON p.upc=u.upc WHERE p.upc IN (' . $upc_in . ')'; $prep = $this->connection->prepare($query); $res = $this->connection->execute($prep, $args); return $res ? true : false; }
public function get_view() { $dbc = $this->connection; $dbc->selectDB($this->config->get('OP_DB')); $TRANS = $this->config->get('TRANS_DB') . $dbc->sep(); $oids = FormLib::get('oids', array()); if (!is_array($oids) || count($oids) == 0) { return '<div class="alert alert-danger">No order(s) selected</div>'; } ?> <script type="text/javascript"> function toggleChecked(status){ $(".cbox").each( function() { $(this).attr("checked",status); }); } </script> <?php echo '<form method="get">'; echo '<input type="checkbox" id="sa" onclick="toggleChecked(this.checked);" />'; echo '<label for="sa"><b>Select All</b></label>'; echo '<table class="table table-bordered table-striped small">'; $username = FannieAuth::checkLogin(); $cachepath = sys_get_temp_dir() . "/ordercache/"; if (file_exists("{$cachepath}{$username}.prints")) { $prints = unserialize(file_get_contents("{$cachepath}{$username}.prints")); foreach ($prints as $oid => $data) { if (!in_array($oid, $_REQUEST['oids'])) { $_REQUEST['oids'][] = $oid; } } } $infoP = $dbc->prepare_statement("SELECT min(datetime) as orderDate,sum(total) as value,\n count(*)-1 as items,\n CASE WHEN MAX(p.card_no)=0 THEN MAX(o.lastName) ELSE MAX(c.LastName) END as name\n FROM {$TRANS}PendingSpecialOrder AS p\n LEFT JOIN custdata AS c ON c.CardNo=p.card_no AND personNum=p.voided\n LEFT JOIN {$TRANS}SpecialOrders AS o ON o.specialOrderID=p.order_id \n WHERE p.order_id=?"); $itemP = $dbc->prepare_statement("SELECT description,department,quantity,ItemQtty,total,trans_id\n FROM {$TRANS}PendingSpecialOrder WHERE order_id=? AND trans_id > 0"); foreach ($_REQUEST['oids'] as $oid) { $r = $dbc->exec_statement($infoP, array($oid)); $w = $dbc->fetch_row($r); printf('<tr><td colspan="2">Order #%d (%s, %s)</td><td>Amt: $%.2f</td> <td>Items: %d</td><td> </td></tr>', $oid, $w['orderDate'], $w['name'], $w['value'], $w['items']); $r = $dbc->exec_statement($itemP, array($oid)); while ($w = $dbc->fetch_row($r)) { if ($w['department'] == 0) { echo '<tr><td> </td>'; echo '<td colspan="4">'; echo 'No department set for: ' . $w['description']; echo '</td></tr>'; } else { printf('<tr><td> </td><td>%s (%d)</td><td>%d x %d</td> <td>$%.2f</td> <td><input type="checkbox" class="cbox" name="toIDs[]" value="%d:%d" /></td> </tr>', $w['description'], $w['department'], $w['ItemQtty'], $w['quantity'], $w['total'], $w['trans_id'], $oid); } } } echo '</table>'; echo '<p>'; echo '<button type="submit" class="btn btn-default">Print Tags</button>'; echo '</p>'; echo '</form>'; }
/** Check if the user is logged in */ public function checkAuth() { foreach ($this->auth_classes as $class) { $try = false; if (is_array($class) && count($class) == 3) { $try = FannieAuth::validateUserQuiet($class[0], $class[1], $class[2]); } else { $try = FannieAuth::validateUserQuiet($class); } if ($try) { $this->current_user = $try; return true; } } $try = FannieAuth::checkLogin(); if ($try && empty($this->auth_classes)) { $this->current_user = $try; return true; } return false; }
public static function batchNotification($batchID, $upc, $type, $is_likecode = false) { $conf = \FannieConfig::factory(); $dbc = \FannieDB::getReadOnly($conf->get('OP_DB')); $likecode = ''; $desc = ''; $dept = 0; if ($is_likecode) { if (substr($upc, 0, 2) == 'LC') { $likecode = substr($upc, 2); } else { $likecode = $upc; } // upc is a like code. find the description // and a valid upc (hence inner join) $infoQ = 'SELECT p.department, l.likeCodeDesc FROM upcLike AS u ' . DTrans::joinProducts('u', 'p', 'INNER') . ' LEFT JOIN likeCodes AS l ON u.likeCode=l.likeCode WHERE u.likeCode=?'; $infoP = $dbc->prepare($infoQ); $infoR = $dbc->execute($infoP, array($likecode)); if ($dbc->num_rows($infoR) == 0) { // invalid like code return false; } $infoW = $dbc->fetch_row($infoR); $desc = $infoW['likeCodeDesc']; $dept = $infoW['department']; } else { $product = new \ProductsModel($dbc); $product->upc($upc); $product->load(); $desc = $product->description(); $dept = $product->department(); } $to_addr = self::getAddresses($dept); if ($to_addr === false) { // no one set to receive notices return false; } $batch = new \BatchesModel($dbc); $batch->batchID($batchID); $batch->load(); $batchList = new \BatchListModel($dbc); $batchList->upc($upc); $batchList->batchID($batchID); $batchList->load(); $subject = "Batch Update notification: " . $batch->batchName(); $message = "Batch " . $batch->batchName() . " has been changed\n"; if ($is_likecode) { $message .= 'Like code ' . $likecode . '(' . $desc . ') '; } else { $message .= 'Item ' . $upc . '(' . $desc . ') '; } switch ($type) { case self::BATCH_ADD: $message .= "has been added to the batch\n"; $message .= 'Sale Price: $' . $batchList->salePrice() . "\n"; break; case self::BATCH_EDIT: $message .= "has been re-priced\n"; $message .= 'Sale Price: $' . $batchList->salePrice() . "\n"; break; case self::BATCH_DELETE: $message .= "has been deleted from the batch\n"; break; default: $message .= "may have experienced unknown changes\n"; return false; // remove after testing; don't send lots of these in error break; } $message .= "\n"; $message .= "View this batch:\n"; $url = $conf->get('URL'); $server_name = filter_input(INPUT_SERVER, 'SERVER_NAME'); $message .= "http://{$server_name}{$url}batches/newbatch/EditBatchPage.php?id={$batchID}\n"; $message .= "\n"; $message .= "View this item:\n"; $message .= "http://{$server_name}/{$url}item/ItemEditorPage.php?searchupc={$upc}\n"; $message .= "\n"; $username = \FannieAuth::checkLogin(); if (!$username) { $username = '******'; } $message .= "This change was made by user {$username}\n"; $from = "From: automail\r\n"; mail($to_addr, $subject, $message, $from); return true; }
private function createEmptyOrder() { global $FANNIE_OP_DB, $TRANS, $FANNIE_SERVER_DBMS, $FANNIE_TRANS_DB; $dbc = $this->connection; $dbc->selectDB($this->config->get('OP_DB')); $TRANS = $this->config->get('TRANS_DB') . $dbc->sep(); $user = FannieAuth::checkLogin(); $orderID = 1; $values = $this->config->get('SERVER_DBMS') != "MSSQL" ? "VALUES()" : "DEFAULT VALUES"; $dbc->query('INSERT ' . $TRANS . 'SpecialOrders ' . $values); $orderID = $dbc->insert_id(); /** @deprecated 24Apr14 New SpecialOrders table is standard now */ if ($dbc->table_exists($TRANS . 'SpecialOrderID')) { $soP = $dbc->prepare('INSERT INTO ' . $TRANS . 'SpecialOrderID (id) VALUES (?)'); $soR = $dbc->execute($soP, array($orderID)); } $ins_array = $this->genericRow($orderID); $ins_array['numflag'] = 2; $ins_array['mixMatch'] = $user; $dbc->smart_insert("{$TRANS}PendingSpecialOrder", $ins_array); $note_vals = array('order_id' => $orderID, 'notes' => "", 'superID' => 0); $status_vals = array('order_id' => $orderID, 'status_flag' => 3, 'sub_status' => time()); $dbc->selectDB($this->config->get('TRANS_DB')); $s_order = new SpecialOrdersModel($dbc); $s_order->specialOrderID($orderID); $s_order->statusFlag($status_vals['status_flag']); $s_order->subStatus($status_vals['sub_status']); $s_order->notes(trim($note_vals['notes'], "'")); $s_order->noteSuperID($note_vals['superID']); $s_order->save(); $dbc->selectDB($this->config->get('TRANS_DB')); // switch back to previous if ($dbc->table_exists($TRANS . 'SpecialOrderStatus')) { $dbc->smart_insert("{$TRANS}SpecialOrderStatus", $status_vals); } $this->createContactRow($orderID); return $orderID; }
public function get_id_view() { global $FANNIE_OP_DB; $uid = FannieAuth::getUID(FannieAuth::checkLogin()); $dbc = CalendarPluginDB::get(); $event = new MonthviewEventsModel($dbc); $event->eventID($this->id); $event->load(); list($date, $time) = explode(' ', $event->eventDate()); $ret = '<h3>' . $date . '</h3>'; $ret .= '<div class="eventDesc">' . $event->eventText() . '</div>'; $ret .= '<hr />'; $attending = false; $ret .= '<h3>Attendees</h3>'; $ret .= '<ol>'; $query = 'SELECT m.uid, u.real_name FROM attendees AS m INNER JOIN ' . $FANNIE_OP_DB . $dbc->sep() . 'Users AS u ON m.uid=u.uid WHERE m.eventID=? ORDER BY attendeeID'; $prep = $dbc->prepare($query); $result = $dbc->execute($prep, $this->id); $num = $result ? $dbc->num_rows($result) : 0; while ($row = $dbc->fetch_row($result)) { $ret .= '<li>' . $row['real_name'] . '</li>'; if ($row['uid'] == $uid) { $attending = true; } } $ret .= '</ol>'; if (!$attending && $num < $event->attendeeLimit()) { $ret .= sprintf('<a href="CalendarAttendedEventPage.php?id=%d&join_id=%d">Sign up for this Event</a>', $this->id, $uid); } else { if (!$attending) { $ret .= 'This event is at capacity'; } else { $ret .= sprintf('<a href="CalendarAttendedEventPage.php?id=%d&leave_id=%d">Take myself off the List</a>', $this->id, $uid); } } $ret .= '<div style="margin-top:20px"><a href="CalendarMainPage.php">Home</a></div>'; return $ret; }
public function run($args = array()) { global $FANNIE_URL; $data = array(); $action = FormLib::get_form_value('action'); if ($action !== '') { $data[] = $action; switch ($action) { case 'save_or_add_event': $calID = FormLib::get('id', 0); $text = FormLib::get('text'); $text = str_replace('<br>', "\n", $text); $text = htmlspecialchars($text); $text = str_replace("\n", '<br>', $text); $db = CalendarPluginDB::get(); $event = new MonthviewEventsModel($db); $eventID = FormLib::get('eventID', false); if ($eventID !== false) { $event->eventID($eventID); $event->eventText($text); if (!empty($text)) { $event->save(); } else { $event->delete(); } } else { $date = FormLib::get('datestr'); $uid = FormLib::get('uid'); $event->eventDate($date); $event->calendarID($calID); $event->uid($uid); $event->eventText($text); if (!empty($text)) { $eventID = $event->save(); $data = array(); echo $eventID; } } $calendar = new CalendarsModel($db); $calendar->calendarID($calID); $calendar->modified(1); $calendar->save(); break; case 'monthview_save': $date = FormLib::get_form_value('date'); $id = FormLib::get_form_value('id', 0); $text = FormLib::get_form_value('text'); $uid = FormLib::get_form_value('uid', 0); $db = CalendarPluginDB::get(); $chkP = $db->prepare_statement("SELECT calendarID FROM monthview_events \n WHERE eventDate=? and uid=? and calendarID=?"); $rowCheck = $db->exec_statement($chkP, array($date, $uid, $id)); if ($db->num_rows($rowCheck) <= 0 && $text != "") { $insP = $db->prepare_statement("INSERT INTO monthview_events \n (calendarID, eventDate, eventText, uid) VALUES (?,?,?,?)"); $db->exec_statement($insP, array($id, $date, $text, $uid)); } else { if ($text == "") { $delP = $db->prepare_statement("DELETE FROM monthview_events WHERE\n calendarID=? AND eventDate=?\n AND uid=?"); $db->exec_statement($delP, array($id, $date, $uid)); } else { $upP = $db->prepare_statement("UPDATE monthview_events SET\n eventText=?\n WHERE calendarID=? AND eventDate=?\n AND uid=?"); $db->exec_statement($upP, array($text, $id, $date, $uid)); } } $calendar = new CalendarsModel($db); $calendar->calendarID($id); $calendar->modified(1); $calendar->save(); break; case 'createCalendar': $name = FormLib::get_form_value('name'); $uid = FormLib::get_form_value('uid', 0); $db = CalendarPluginDB::get(); $p = $db->prepare_statement("INSERT INTO calendars (name) VALUES (?)"); $db->exec_statement($p, array($name)); $id = $db->insert_id(); $p = $db->prepare_statement("INSERT INTO permissions (calendarID,uid,classID)\n VALUES (?,?,4)"); $db->exec_statement($p, array($id, $uid)); $data[] = "<p class=\"index\"><a href=\"?calID={$id}&view=month\">{$name}</a></p>"; break; case 'createSubscription': $db = CalendarPluginDB::get(); $name = FormLib::get('name'); $url = FormLib::get('url'); $uid = FormLib::get_form_value('uid', 0); $subscription = new CalendarSubscriptionsModel($db); $subscription->url($url); $subscriptionID = $subscription->save(); $calendar = new CalendarsModel($db); $calendar->name($name); $calendar->calendarSubscriptionID($subscriptionID); $calendarID = $calendar->save(); $permissions = new PermissionsModel($db); $permissions->calendarID($calendarID); $permissions->uid($uid); $permissions->classID(4); $permissions->save(); $data[] = 'Subscribed'; break; case 'savePrefs': $calID = FormLib::get_form_value('calID'); $name = str_replace("'", "''", $_GET['name']); $name = FormLib::get_form_value('name'); $viewers = FormLib::get_form_value('viewers', array()); $writers = FormLib::get_form_value('writers', array()); $db = CalendarPluginDB::get(); $calendar = new CalendarsModel($db); $calendar->calendarID($calID); $calendar->load(); $calendar->name($name); $calendar->save(); $p = $db->prepare_statement("DELETE FROM permissions WHERE calendarID=? and classID < 4"); $db->exec_statement($p, array($calID)); $insP = $db->prepare_statement("INSERT INTO permissions (calendarID,uid,classID) VALUES (?,?,?)"); if ($viewers != "") { foreach (explode(",", $viewers) as $v) { $db->exec_statement($insP, array($calID, $v, 1)); } } if ($writers != "") { foreach (explode(",", $writers) as $w) { $db->exec_statement($insP, array($calID, $w, 2)); } } if (FormLib::get('url')) { $url = FormLib::get('url'); $sub = new CalendarSubscriptionsModel($db); $sub->calendarSubscriptionID($calendar->calendarSubscriptionID()); $sub->url($url); $sub->save(); } break; case 'weekview_save': $timestamp = FormLib::get_form_value('ts'); $date = date('Y-m-d H:i:00', $timestamp); $calID = FormLib::get_form_value('id', 0); $text = trim(FormLib::get_form_value('text')); $eID = FormLib::get('eventID', false); $uid = FannieAuth::getUID(FannieAuth::checkLogin()); $pat = '/#(\\d+)/'; $rep = '<a href="' . $FANNIE_URL . 'modules/plugins2.0/PIKiller/PIMemberPage.php?id=${1}" onclick="noBubble(event);">#${1}</a>'; $text = preg_replace($pat, $rep, $text); $db = CalendarPluginDB::get(); $model = new MonthviewEventsModel($db); if ($eID) { $model->eventID($eID); } if (empty($text) && $eID) { // delete empty event // no eID implies event doesn't exist // just opened/closed w/o content $model->delete(); } else { if (!empty($text)) { $model->uid($uid); $model->eventDate($date); $model->eventText($text); $model->calendarID($calID); $newID = $model->save(); if (!$eID) { $data[] = $newID; } } } break; } } return $data; }
public function get_view() { $dbc = $this->connection; $dbc->selectDB($this->config->get('OP_DB')); $TRANS = $this->config->get('TRANS_DB') . $dbc->sep(); $cachepath = sys_get_temp_dir() . "/ordercache/"; if (!is_dir($cachepath)) { mkdir($cachepath); } $key = dechex(str_replace(" ", "", str_replace(".", "", microtime()))); $prints = array(); $username = FannieAuth::checkLogin(); if (file_exists("{$cachepath}{$username}.prints")) { $prints = unserialize(file_get_contents("{$cachepath}{$username}.prints")); } else { $fp = fopen("{$cachepath}{$username}.prints", 'w'); fwrite($fp, serialize($prints)); fclose($fp); } $f1 = FormLib::get('f1'); $f2 = FormLib::get('f2'); $f3 = FormLib::get('f3'); $ret = ''; if ($this->card_no) { $ret .= sprintf('(<a href="%s?f1=%s&f2=%s&f3=%s&order=%s">Back to All Owners</a>)<br />', $_SERVER['PHP_SELF'], $f1, $f2, $f3, FormLib::get('order')); } $status = array(0 => "New, No Call", 3 => "New, Call", 1 => "Called/waiting", 2 => "Pending", 4 => "Placed", 5 => "Arrived"); /** Lookup list of super departments for filtering purposes */ $assignments = array(); $q = $dbc->prepare("\n SELECT superID,\n super_name \n FROM MasterSuperDepts\n WHERE superID > 0\n GROUP BY superID,\n super_name \n ORDER BY superID"); $r = $dbc->exec_statement($q); while ($w = $dbc->fetch_row($r)) { $assignments[$w['superID']] = $w['super_name']; } unset($assignments[0]); /** Lookup list of vendors for filtering purposes These are vendors mentioned in an order which may not overlap perfectly with the actual vendors table */ $suppliers = array(''); $q = $dbc->prepare("\n SELECT mixMatch \n FROM {$TRANS}PendingSpecialOrder \n WHERE trans_type='I'\n GROUP BY mixMatch \n ORDER BY mixMatch"); $r = $dbc->exec_statement($q); while ($w = $dbc->fetch_row($r)) { $suppliers[] = $w['mixMatch']; } $filterstring = ""; $filterargs = array(); if ($f1 !== '') { $f1 = (int) $f1; $filterstring .= ' AND statusFlag=?'; $filterargs[] = $f1; } $ret .= '<a href="index.php">Main Menu</a>'; $ret .= " "; $ret .= "Current Orders"; $ret .= " "; $ret .= sprintf('<a href="OldSpecialOrdersPage.php%s">Old Orders</a>', $this->card_no ? '?card_no=' . $this->card_no : ''); $ret .= " "; $ret .= " "; $ret .= '<input type="checkbox" id="acbx" onclick="$(\'tr.arrived\').each(function(){$(this).toggle();});" />'; $ret .= '<label for="acbx">Hide Printed</label>'; $ret .= '<p />'; $ret .= '<div class="form-inline">'; $ret .= "<b>Status</b>: "; $ret .= '<select id="f_1" class="form-control input-sm" onchange="refilter();">'; $ret .= '<option value="">All</option>'; foreach ($status as $k => $v) { $ret .= sprintf("<option %s value=\"%d\">%s</option>", $k === $f1 ? 'selected' : '', $k, $v); } $ret .= '</select>'; $ret .= ' '; $ret .= '<b>Buyer</b>: <select id="f_2" class="form-control input-sm" onchange="refilter();">'; $ret .= '<option value="">All</option>'; foreach ($assignments as $k => $v) { $ret .= sprintf("<option %s value=\"%d\">%s</option>", $k == $f2 ? 'selected' : '', $k, $v); } $ret .= sprintf('<option %s value="2%%2C8">Meat+Cool</option>', $f2 == "2,8" ? 'selected' : ''); $ret .= '</select>'; $ret .= ' '; $ret .= '<b>Supplier</b>: <select id="f_3" class="form-control input-sm" onchange="refilter();">'; foreach ($suppliers as $v) { $ret .= sprintf("<option %s>%s</option>", $v === $f3 ? 'selected' : '', $v); } $ret .= '</select>'; $ret .= '</div>'; /** Also filter by member number if applicable */ if ($this->card_no) { $filterstring .= " AND p.card_no=?"; $filterargs[] = $this->card_no; $ret .= sprintf('<input type="hidden" id="cardno" value="%d" />', $this->card_no); } $q = "SELECT min(datetime) as orderDate,p.order_id,sum(total) as value,\n count(*)-1 as items,\n o.statusFlag AS status_flag,\n o.subStatus AS sub_status,\n CASE WHEN MAX(p.card_no)=0 THEN MAX(o.lastName) ELSE MAX(c.LastName) END as name,\n MIN(CASE WHEN trans_type='I' THEN charflag ELSE 'ZZZZ' END) as charflag,\n MAX(p.card_no) AS card_no\n FROM {$TRANS}PendingSpecialOrder as p\n LEFT JOIN custdata AS c ON c.CardNo=p.card_no AND personNum=p.voided\n LEFT JOIN {$TRANS}SpecialOrders AS o ON p.order_id=o.specialOrderID\n WHERE 1=1 {$filterstring}\n GROUP BY p.order_id,statusFlag,subStatus\n HAVING \n count(*) > 1 OR\n SUM(CASE WHEN o.notes LIKE '' THEN 0 ELSE 1 END) > 0\n ORDER BY MIN(datetime)"; $p = $dbc->prepare($q); $r = $dbc->execute($p, $filterargs); $orders = array(); $valid_ids = array(); while ($w = $dbc->fetch_row($r)) { $orders[] = $w; $valid_ids[$w['order_id']] = true; } if ($f2 !== '' || $f3 !== '') { $filter = ""; $args = array(); if ($f2 !== '') { $filter .= "AND (m.superID IN (?) OR o.noteSuperID IN (?))"; $args = array($f2, $f2); } if ($f3 !== '') { $filter .= "AND p.mixMatch=?"; $args[] = $f3; } $q = "SELECT p.order_id FROM {$TRANS}PendingSpecialOrder AS p\n LEFT JOIN MasterSuperDepts AS m ON p.department=m.dept_ID\n LEFT JOIN {$TRANS}SpecialOrders AS o ON p.order_id=o.specialOrderID\n WHERE 1=1 {$filter}\n GROUP BY p.order_id"; $p = $dbc->prepare($q); $r = $dbc->execute($p, $args); $valid_ids = array(); while ($w = $dbc->fetch_row($r)) { $valid_ids[$w['order_id']] = true; } /** This may be redundant. Notes tagged by super department should be captured in the previous query. */ if ($f2 !== '' && $f3 === '') { $q2 = $dbc->prepare_statement("\n SELECT o.specialOrderID \n FROM {$TRANS}SpecialOrders AS o\n WHERE o.noteSuperID IN (?)\n GROUP BY o.specialOrderID"); $r2 = $dbc->exec_statement($q2, array($f2)); while ($w2 = $dbc->fetch_row($r2)) { $valid_ids[$w2['specialOrderID']] = true; } } } /** Turn the list of valid order IDs into query parameters. Next step is to look up line items in the each order to list all items and vendors on the order summary row */ $oids = "("; $oargs = array(); foreach ($valid_ids as $id => $nonsense) { $oids .= "?,"; $oargs[] = $id; } $oids = rtrim($oids, ",") . ")"; if (empty($oargs)) { $oids = '(?)'; $oargs = array(-1); // avoid invalid query } $itemsQ = $dbc->prepare_statement("\n SELECT order_id,\n description,\n mixMatch \n FROM {$TRANS}PendingSpecialOrder \n WHERE order_id IN {$oids}\n AND trans_id > 0"); $itemsR = $dbc->exec_statement($itemsQ, $oargs); $items = array(); $suppliers = array(); while ($itemsW = $dbc->fetch_row($itemsR)) { if (!isset($items[$itemsW['order_id']])) { $items[$itemsW['order_id']] = $itemsW['description']; } else { $items[$itemsW['order_id']] .= "; " . $itemsW['description']; } if (!empty($itemsW['mixMatch'])) { if (!isset($suppliers[$itemsW['order_id']])) { $suppliers[$itemsW['order_id']] = $itemsW['mixMatch']; } else { $suppliers[$itemsW['order_id']] .= "; " . $itemsW['mixMatch']; } } } $lenLimit = 10; foreach ($items as $id => $desc) { if (strlen($desc) <= $lenLimit) { continue; } $min = substr($desc, 0, $lenLimit); $rest = substr($desc, $lenLimit); $desc = sprintf('%s<span id="exp%d" style="display:none;">%s</span> <a href="" onclick="$(\'#exp%d\').toggle();return false;">+</a>', $min, $id, $rest, $id); $items[$id] = $desc; } $lenLimit = 10; foreach ($suppliers as $id => $desc) { if (strlen($desc) <= $lenLimit) { continue; } $min = substr($desc, 0, $lenLimit); $rest = substr($desc, $lenLimit); $desc = sprintf('%s<span id="sup%d" style="display:none;">%s</span> <a href="" onclick="$(\'#sup%d\').toggle();return false;">+</a>', $min, $id, $rest, $id); $suppliers[$id] = $desc; } $ret .= '<p />'; $ret .= '<form id="pdfform" action="SpecialOrderTags.php" method="get">'; $ret .= sprintf('<table class="table table-bordered table-striped tablesorter tablesorter-core"> <thead> <tr> <th>Order Date</th> <th>Name</th> <th>Desc</th> <th>Supplier</th> <th>Items</th> <th>$</th> <th>Status</th> <th>Printed</th>', base64_encode("min(datetime)"), base64_encode("CASE WHEN MAX(p.card_no)=0 THEN MAX(o.lastName) ELSE MAX(c.LastName) END"), base64_encode("sum(total)"), base64_encode("count(*)-1"), base64_encode("statusFlag")); $ret .= sprintf('<td><img src="%s" alt="Print" onclick="$(\'#pdfform\').submit();" /></td>', $this->config->get('URL') . 'src/img/buttons/action_print.gif'); $ret .= '</tr></thead><tbody>'; $fp = fopen($cachepath . $key, "w"); foreach ($orders as $w) { $id = $w['order_id']; if (!isset($valid_ids[$id])) { continue; } $ret .= '<tr class="' . ($w['charflag'] == 'P' ? 'arrived' : 'notarrived') . '">'; list($date, $time) = explode(' ', $w['orderDate'], 2); $ret .= sprintf('<td><a href="OrderViewPage.php?orderID=%d&k=%s">%s</a></td>', $id, $key, $date); $ret .= sprintf('<td><a href="" onclick="applyMemNum(%d); return false;">%s</a></td>', $w['card_no'], $w['name']); $ret .= '<td class="small">' . (isset($items[$id]) ? $items[$id] : ' ') . '</td>'; $ret .= '<td class="small">' . (isset($suppliers[$id]) ? $suppliers[$id] : ' ') . '</td>'; $ret .= sprintf('<td>%d</td>', $w['items']); $ret .= sprintf('<td>%.2f</td>', $w['value']); $ret .= '<td class="form-inline"> <select id="s_status" class="form-control input-sm" onchange="updateStatus(' . $w['order_id'] . ',$(this).val());">'; foreach ($status as $k => $v) { $ret .= sprintf('<option %s value="%d">%s</option>', $w['status_flag'] == $k ? 'selected' : '', $k, $v); } $ret .= "</select> <span id=\"statusdate{$id}\">" . ($w['sub_status'] == 0 ? 'No Date' : date('m/d/Y', $w['sub_status'])) . "</span></td>"; $ret .= "<td align=center>" . ($w['charflag'] == 'P' ? 'Yes' : 'No') . "</td>"; $ret .= sprintf('<td><input type="checkbox" %s name="oids[]" value="%d" onclick="togglePrint(\'%s\',%d);" /></td>', isset($prints[$id]) ? 'checked' : '', $id, $username, $id); $ret .= '</tr>'; fwrite($fp, $w['order_id'] . "\n"); } fclose($fp); $ret .= "</tbody></table>"; $this->add_script('../src/javascript/tablesorter/jquery.tablesorter.js'); $this->add_onload_command("\$('.tablesorter').tablesorter();"); return $ret; }
function body_content() { global $FANNIE_URL; $user = FannieAuth::checkLogin(); ob_start(); ?> <form style='margin-top:1.0em;' id="osForm" onsubmit="setdate(); return false;" > <div class="form-group form-inline"> <label>Date</label>:<input class="form-control date-field" type=text id=date name=arg /> <select class="form-control" name="mode"> <option value="cashier">Cashier</option> <option value="drawer">Drawer</option> </select> <?php $_REQUEST['store'] = 1; $sp = FormLib::storePicker(); echo $sp['html']; ?> <button type=submit class="btn btn-default">Set</button> <input type=hidden id=user value="<?php if (isset($user)) { echo $user; } ?> " /> </div> </form> <div id="loading-bar" class="collapse"> <?php echo \COREPOS\Fannie\API\lib\FannieUI::loadingBar(); ?> </div> <div id="forms"></div> <?php return ob_get_clean(); }
public static function weekView($id, $year, $week) { $sql = CalendarPluginDB::get(); $calendarModel = new CalendarsModel($sql); $calendarModel->calendarID($id); $calendarModel->load(); $name = $calendarModel->name(); $uid = FannieAuth::getUID(FannieAuth::checkLogin()); $EDIT = CalendarPluginPermissions::can_write($uid, $id); $OWNER = CalendarPluginPermissions::is_owner($uid, $id); $startTS = strtotime($year . '-W' . str_pad($week, 2, '0', STR_PAD_LEFT) . '-1'); $endTS = mktime(0, 0, 0, date('n', $startTS), date('j', $startTS) + 6, date('Y', $startTS)); $query = 'SELECT eventDate, eventText, eventID FROM monthview_events WHERE calendarID=? AND eventDate BETWEEN ? AND ?'; $prep = $sql->prepare($query); $args = array($id, date('Y-m-d 00:00:00', $startTS), date('Y-m-d 23:59:59', $endTS)); $result = $sql->execute($prep, $args); $cal_data = array(); while ($row = $sql->fetch_row($result)) { $cal_ts = strtotime($row['eventDate']); $cal_data[$cal_ts] = array('id' => $row['eventID'], 'text' => $row['eventText']); } $startT = 7; $endT = 21; $prevWeek = mktime(0, 0, 0, date('n', $startTS), date('j', $startTS) - 7, date('Y', $startTS)); $nextWeek = mktime(0, 0, 0, date('n', $startTS), date('j', $startTS) + 7, date('Y', $startTS)); $ret = '<table cellpadding="4" cellspacing="0" border="1">'; // paging $ret .= '<tr>'; $ret .= sprintf('<td colspan="3" align="left"> <a href="?view=week&calID=%d&week=%d&year=%d">Prev</a></td>', $id, date('W', $prevWeek), date('Y', $prevWeek)); $ret .= '<td align="center">' . date('Y', $startTS) . '</td>'; $ret .= sprintf('<td colspan="4" align="right"> <a href="?view=week&calID=%d&week=%d&year=%d">Next</a></td>', $id, date('W', $nextWeek), date('Y', $nextWeek)); $ret .= '</tr>'; $ret .= '<tr><th>' . $name . '</th>'; for ($i = 0; $i < 7; $i++) { $ts = mktime(0, 0, 0, date('n', $startTS), date('j', $startTS) + $i, date('Y', $startTS)); $ret .= '<th>' . date('M j', $ts) . '<br />' . date('l', $ts) . '</th>'; } $ret .= '</tr>'; for ($hour = $startT; $hour < $endT; $hour++) { $ret .= '<tr>'; $ret .= '<td>' . date('h:i A', mktime($hour, 0)) . '</td>'; for ($i = 0; $i < 7; $i++) { $entry_ts = mktime($hour, 0, 0, date('n', $startTS), date('j', $startTS) + $i, date('Y', $startTS)); if ($EDIT) { $ret .= sprintf('<td id="weekEntry%d" class="weekEntry" onclick="weekClickCallback(%d);" ondblclick="saveCallback(%d);"> <input type="hidden" class="weekEntryTS" value="%d" /> <span class="weekEntryContent">%s</span>', $entry_ts, $entry_ts, $entry_ts, $entry_ts, isset($cal_data[$entry_ts]) ? $cal_data[$entry_ts]['text'] : ''); if (isset($cal_data[$entry_ts])) { $ret .= sprintf('<input type="hidden" class="weekEntryEventID" value="%d" />', $cal_data[$entry_ts]['id']); } } else { $ret .= '<td class="weekEntry"><span class="weekEntryContent">'; $ret .= isset($cal_data[$entry_ts]) ? $cal_data[$entry_ts]['text'] : ''; $ret .= '</span>'; } $ret .= '</td>'; } $ret .= '</tr>'; $ret .= '<tr>'; $ret .= '<td>' . date('h:i A', mktime($hour, 30)) . '</td>'; for ($i = 0; $i < 7; $i++) { $entry_ts = mktime($hour, 30, 0, date('n', $startTS), date('j', $startTS) + $i, date('Y', $startTS)); if ($EDIT) { $ret .= sprintf('<td id="weekEntry%d" class="weekEntry" onclick="weekClickCallback(%d);" ondblclick="saveCallback(%d);"> <input type="hidden" class="weekEntryTS" value="%d" /> <span class="weekEntryContent">%s</span>', $entry_ts, $entry_ts, $entry_ts, $entry_ts, isset($cal_data[$entry_ts]) ? $cal_data[$entry_ts]['text'] : ''); if (isset($cal_data[$entry_ts])) { $ret .= sprintf('<input type="hidden" class="weekEntryEventID" value="%d" />', $cal_data[$entry_ts]['id']); } } else { $ret .= '<td class="weekEntry"><span class="weekEntryContent">'; $ret .= isset($cal_data[$entry_ts]) ? $cal_data[$entry_ts]['text'] : ''; $ret .= '</span>'; } $ret .= '</td>'; } $ret .= '</tr>'; } $ret .= '</table>'; $ret .= '<input type="hidden" id="calendarID" value="' . $id . '" />'; return $ret; }
function getFooter() { global $FANNIE_URL; $ret = '</table>'; if (FannieAuth::checkLogin() !== false) { $ret .= '<p><span id="logininfo" style="top:50px;">'; $ret .= 'Logged in as: ' . FannieAuth::checkLogin(); $ret .= ' ['; $ret .= ' <a href="' . $FANNIE_URL . 'auth/ui/loginform.php?logout=yes">Logout</a> ]'; $ret .= '</span></p>'; } else { $ret .= FannieAuth::checkLogin(); } $ret .= '</body></html>'; return $ret; }