/** * Here we use multiple models to gather data for displaying graphs * @param $type type to filter by 'member','team','company' * @param $id id of type to filter by * @return $graph_data gathered graph data */ public function getGraphData($type = null, $id = null) { //set default search data if ($type == null) { $type = 'member'; $id = UsersHelper::getUserId(); } //deal data $model = new Deal(); $model->set('archived', 0); $deals_by_stage = $model->getGraphDeals('stage', $type, $id); $deals_by_status = $model->getGraphDeals('status', $type, $id); $lead_sources = $model->getLeadSources($type, $id); $stage_names = array(); $stage_totals = array(); $status_names = array(); $status_totals = array(); $lead_source_names = array(); $lead_totals = array(); //revenue data $model = new Revenue(); $monthly_revenue = $model->getMonthlyRevenue($type, $id); $yearly_revenue = $model->getYearlyRevenue($type, $id); //commission data $model = new Commission(); $monthly_commissions = $model->getMonthlyCommission($type, $id); $yearly_commissions = $model->getYearlyCommission($type, $id); //get lead source names if (count($lead_sources) > 0) { foreach ($lead_sources as $lead) { $lead_source_names[] = $lead['name']; $lead_totals[] = $lead['y']; } } //get weeks $weeks = array(); $count = 0; if ($monthly_revenue) { foreach ($monthly_revenue as $week) { $count++; $weeks[] = "Week " . $count; } } //get months $months = DateHelper::getMonthNamesShort(); //generate graph data $graph_data = array('deal_stage' => $deals_by_stage, 'stage_names' => $stage_names, 'stage_totals' => $stage_totals, 'deal_status' => $deals_by_status, 'status_names' => $status_names, 'status_totals' => $status_totals, 'lead_sources' => $lead_sources, 'lead_source_names' => $lead_source_names, 'lead_totals' => $lead_totals, 'monthly_revenue' => $monthly_revenue, 'yearly_revenue' => $yearly_revenue, 'monthly_commissions' => $monthly_commissions, 'yearly_commissions' => $yearly_commissions, 'months' => $months, 'weeks' => $weeks); return $graph_data; }
public function __construct() { $this->previousDay = DateHelper::formatDBDate(date('Y-m-d') . " - 1 day"); $this->today = DateHelper::formatDBDate(date('Y-m-d')); $this->access = UsersHelper::getRole($this->person_id); $this->users = $this->getUsers($this->person_id, $this->access); }
/** * Method to store custom field cf data associated with items * @param int $id : The id of the item we wish to store associated data * @param mixed $cf_data : The data to be stored * @return void * */ public static function storeCustomCf($id, $cf_data, $type) { //Get DBO $db = \Cobalt\Container::fetch('db'); $query = $db->getQuery(true); //date generation $date = DateHelper::formatDBDate(date('Y-m-d H:i:s')); //Loop through $cf_data array to update/insert for ($i = 0; $i < count($cf_data); $i++) { //assign the data $row = $cf_data[$i]; $query->clear(); $query->select("COUNT(*)")->from("#__" . $type . "_custom_cf")->where($type . "_id=" . $id . " AND custom_field_id=" . $row['custom_field_id']); $db->setQuery($query); $count = $db->loadResult(); if ($count > 0) { //mysql query $query->clear(); $query->update('#__' . $type . '_custom_cf'); $query->set($type . "_id=" . $id . ",custom_field_id=" . $row['custom_field_id'] . ",value='" . $row['custom_field_value'] . "'" . ",modified='{$date}'"); $query->where($type . "_id={$id} AND custom_field_id=" . $row['custom_field_id']); $db->setQuery($query); $db->query(); } else { $query->clear(); $query->insert('#__' . $type . '_custom_cf'); $query->set($type . "_id=" . $id . ",custom_field_id=" . $row['custom_field_id'] . ",value='" . $row['custom_field_value'] . "'" . ",modified='{$date}'"); $db->setQuery($query); $db->query(); } } }
public function render($tpl = null) { //authenticate the current user to make sure they are an admin UsersHelper::authenticateAdmin(); //display toolbar $this->toolbar = new Toolbar(); $this->toolbar->save(); //document $document = JFactory::getDocument(); $document->addScript(JURI::base() . "/src/Cobalt/media/js/cobalt-admin.js"); /* Menu Links **/ $menu = MenuHelper::getMenuModules(); $this->menu = $menu; //get model $model = new ConfigModel(); $layout = $this->getLayout(); $model->set("_layout", $layout); //get config $config = $model->getConfig(); //generate timezones $list = timezone_identifiers_list(); $timezones = array(); foreach ($list as $zone) { $timezones[$zone] = $zone; } //view references $this->imap_found = function_exists('imap_open') ? TRUE : FALSE; $this->config = $config; $this->timezones = $timezones; $this->time_formats = DateHelper::getTimeFormats(); $this->languages = ConfigHelper::getLanguages(); $this->language = ConfigHelper::getLanguage(); //display return parent::render(); }
public function execute() { //post data $data = $this->getInput()->getArray(); //set date parameters $start_date = DateHelper::formatDBDate(date("Y-m-d 00:00:00", $data['start'])); $end_date = DateHelper::formatDBDate(date("Y-m-d 00:00:00", $data['end'])); //load model $model = new EventModel(); //set model parameters $model->set('start_date', "{$start_date}"); $model->set('end_date', "{$end_date}"); $model->set('loc', "calendar"); //get events $events = $model->getEvents(); echo json_encode($events); }
/** * Method to store a record * @param $_POST data * @return boolean True on success */ public function store() { $app = \Cobalt\Container::fetch('app'); //Load Tables $row = new GoalTable(); $oldRow = new GoalTable(); $data = $app->input->getArray(); //date generation $date = DateHelper::formatDBDate(date('Y-m-d H:i:s')); if (!array_key_exists('id', $data)) { $data['created'] = $date; $status = "created"; } else { $row->load($data['id']); $oldRow->load($data['id']); $status = "updated"; } //assign checkboxes if (array_key_exists('leaderboard', $data)) { $data['leaderboard'] = 1; } else { $data['leaderboard'] = 0; } //assign owner id $data['owner_id'] = UsersHelper::getUserId(); // Bind the form fields to the table if (!$row->bind($data)) { $this->setError($this->db->getErrorMsg()); return false; } // Make sure the record is valid if (!$row->check()) { $this->setError($this->db->getErrorMsg()); return false; } // Store the web link table to the database if (!$row->store()) { $this->setError($this->db->getErrorMsg()); return false; } ActivityHelper::saveActivity($oldRow, $row, 'goal', $status); return true; }
public static function sendMail($layout, $recipient) { $mailer = JFactory::getMailer(); $mailer->isHTML(true); $mailer->Encoding = 'base64'; $config = JFactory::getConfig(); $sender = array($config->getValue('config.mailfrom'), $config->getValue('config.fromname')); $mailer->setSender($sender); $mailer->addRecipient($recipient); $mailer->setSubject(TextHelper::_('COBALT_COFFEE_REPORT_SUBJECT') . ' ' . DateHelper::formatDate(date('Y-m-d'))); ob_start(); $layout->display(); $body = ob_get_contents(); ob_end_clean(); $mailer->setBody($body); $send = $mailer->Send(); if ($send !== true) { echo 'Error sending email: ' . $send->message; } }
/** * Run items through template system */ public function createTemplate() { $template_id = $this->app->input->get('template_id'); $association_id = $this->app->input->get('association_id'); $association_type = $this->app->input->get('association_type'); $template = $this->getTemplate($template_id); $current_date = date("Y-m-d 00:00:00"); if (count($template) > 0) { $event_model = new Event(); foreach ($template as $event) { unset($event['id']); $event['association_id'] = $association_id; $event['association_type'] = $association_type; $event['type'] = "task"; $event['due_date'] = DateHelper::formatDBDate(date("Y-m-d", strtotime($current_date . " +" . $event['day'] . " days")), false); $event['due_date_hour'] = "00:00:00"; if (!$event_model->store($event)) { return false; } } } return true; }
public function store() { //Load Tables $app = \Cobalt\Container::fetch('app'); $row = new BrandingTable(); $data = $app->input->getRequest('post'); //date generation $date = DateHelper::formatDBDate(date('Y-m-d H:i:s')); $data['modified'] = $date; $this->changeDefault($data['id']); $fieldName = 'site_logo'; //any errors the server registered on uploading $fileError = $_FILES[$fieldName]['error']; if ($fileError > 0) { unset($data['site_logo']); } else { //check the file extension is ok $fileName = $_FILES[$fieldName]['name']; $fileTemp = $_FILES[$fieldName]['tmp_name']; $uploadedFileNameParts = explode('.', $fileName); $uploadedFileExtension = array_pop($uploadedFileNameParts); $validFileExts = explode(',', 'jpeg,jpg,png,gif,pdf,doc,docx,odt,rtf,ppt,xls,txt'); //assume the extension is false until we know its ok $extOk = false; //go through every ok extension, if the ok extension matches the file extension (case insensitive) //then the file extension is ok foreach ($validFileExts as $key => $value) { if (preg_match("/{$value}/i", $uploadedFileExtension)) { $extOk = true; } } if ($extOk == false) { echo TextHelper::_('INVALID EXTENSION'); return; } //data generation $hashFilename = md5($fileName . $date) . "." . $uploadedFileExtension; //lose any special characters in the filename //$fileName = preg_replace("[^A-Za-z0-9.]", "-", $fileName); //always use constants when making file paths, to avoid the possibilty of remote file inclusion $uploadPath = JPATH_SITE . '/src/Cobalt/media/logos/' . $hashFilename; if (!File::upload($fileTemp, $uploadPath)) { echo TextHelper::_('ERROR MOVING FILE'); return; } $fileSize = filesize($uploadPath); $this->updateSiteLogo($hashFilename); unset($data['site_logo']); } // Bind the form fields to the table if (!$row->bind($data)) { $this->setError($this->db->getErrorMsg()); return false; } // Make sure the record is valid if (!$row->check()) { $this->setError($this->db->getErrorMsg()); return false; } // Store the web link table to the database if (!$row->store()) { $this->setError($this->db->getErrorMsg()); return false; } return true; }
public static function getElapsedTime($date, $showDays = TRUE, $showMonths = TRUE, $showYears = TRUE, $showHours = TRUE, $showMinutes = TRUE, $showSeconds = FALSE) { $time = time() - strtotime($date); // to get the time since that moment $tokens = array(31536000 => 'year', 2592000 => 'month', 604800 => 'week', 86400 => 'day', 3600 => 'hour', 60 => 'minute', 1 => 'second'); foreach ($tokens as $unit => $text) { if ($time < $unit) { continue; } $numberOfUnits = floor($time / $unit); return $numberOfUnits . ' ' . $text . ($numberOfUnits > 1 ? 's' : ''); } return DateHelper::formatDate($date); }
/** * Prepare HTML field templates for each dataTable column. * * @param string column name * @param object of item * @return string HTML template for propper field */ public function getDataTableFieldTemplate($column, $item) { switch ($column) { case 'id': $template = '<input type="checkbox" class="export" name="ids[]" value="' . $item->id . '" />'; break; case 'name': $template = '<a href="' . RouteHelper::_('index.php?view=deals&layout=deal&id=' . $item->id) . '">' . $item->name . '</a>'; break; case 'company_name': $template = '<a href="' . RouteHelper::_('index.php?view=companies&layout=company&id=' . $item->company_id) . '">' . $item->company_name . '</a>'; break; case 'amount': $template = ConfigHelper::getCurrency() . $item->amount; break; case 'status_name': if (!isset($item->status_id) || !$item->status_id) { $item->status_name = TextHelper::_('COBALT_CLICK_TO_EDIT'); } $statuses = DealHelper::getStatuses(null, true); $template = '<div class="dropdown">'; $template .= ' <a href="#" class="dropdown-toggle update-toggle-html" role="button" data-toggle="dropdown" id="deal_status_' . $item->id . '_link">'; $template .= ' <span class="deal-status-' . $item->status_name . '">' . $item->status_name . '</span>'; $template .= ' </a>'; $template .= ' <ul class="dropdown-menu" aria-labelledby="deal_status_' . $item->id . '" role="menu">'; if (isset($statuses) && count($statuses)) { foreach ($statuses as $id => $name) { $template .= ' <li>'; $template .= ' <a href="#" class="status_select dropdown_item" data-field="status_id" data-item="deal" data-item-id="' . $item->id . '" data-value="' . $id . '">'; $template .= ' <span class="deal-status-' . OutputFilter::stringURLUnicodeSlug($name) . '">' . $name . '</span>'; $template .= ' </a>'; $template .= ' </li>'; } } $template .= ' </ul>'; $template .= ' </div>'; break; case 'stage_name': if (!isset($item->stage_id) || !$item->stage_id) { $item->stage_name = TextHelper::_('COBALT_CLICK_TO_EDIT'); } $stages = DealHelper::getStages(null, true); $template = '<div class="dropdown">'; $template .= ' <a href="#" class="dropdown-toggle update-toggle-html" role="button" data-toggle="dropdown" id="deal_stage_' . $item->id . '_link">'; $template .= ' <span class="deal-stage-' . $item->stage_name . '">' . $item->stage_name . '</span>'; $template .= ' </a>'; $template .= ' <ul class="dropdown-menu" aria-labelledby="deal_stage_' . $item->id . '" role="menu">'; if (isset($stages) && count($stages)) { foreach ($stages as $id => $name) { $template .= ' <li>'; $template .= ' <a href="#" class="stage_select dropdown_item" data-field="stage_id" data-item="deal" data-item-id="' . $item->id . '" data-value="' . $id . '">'; $template .= ' <span class="deal-stage-' . OutputFilter::stringURLUnicodeSlug($name) . '">' . $name . '</span>'; $template .= ' </a>'; $template .= ' </li>'; } } $template .= ' </ul>'; $template .= ' </div>'; break; case 'source_name': if (!isset($item->source_id) || !$item->source_id) { $item->source_name = TextHelper::_('COBALT_CLICK_TO_EDIT'); } $sources = DealHelper::getSources(null, true); $template = '<div class="dropdown">'; $template .= ' <a href="#" class="dropdown-toggle update-toggle-html" role="button" data-toggle="dropdown" id="deal_source_' . $item->id . '_link">'; $template .= ' <span class="deal-source-' . $item->source_name . '">' . $item->source_name . '</span>'; $template .= ' </a>'; $template .= ' <ul class="dropdown-menu" aria-labelledby="deal_source_' . $item->id . '" role="menu">'; if (isset($sources) && count($sources)) { foreach ($sources as $id => $name) { $template .= ' <li>'; $template .= ' <a href="#" class="source_select dropdown_item" data-field="source_id" data-item="deal" data-item-id="' . $item->id . '" data-value="' . $id . '">'; $template .= ' <span class="deal-source-' . OutputFilter::stringURLUnicodeSlug($name) . '">' . $name . '</span>'; $template .= ' </a>'; $template .= ' </li>'; } } $template .= ' </ul>'; $template .= ' </div>'; break; case 'expected_close': if ($item->expected_close == "0000-00-00 00:00:00") { $template = TextHelper::_('COBALT_NOT_SET'); } else { $template = DateHelper::formatDate($item->expected_close); } break; case 'actual_close': if ($item->actual_close == "0000-00-00 00:00:00") { $template = TextHelper::_('COBALT_ACTIVE_DEAL'); } else { $template = DateHelper::formatDate($item->actual_close); } break; case 'action': $template = '<div class="btn-group">'; // @TODO: make these 2 buttons work // $template .= ' <a rel="tooltip" title="'.TextHelper::_('COBALT_VIEW_CONTACTS').'" data-placement="bottom" class="btn" href="javascript:void(0);" onclick="Cobalt.showDealContactsDialogModal('.$item->id.');"><i class="glyphicon glyphicon-user"></i></a>'; // $template .= ' <a rel="tooltip" title="'.TextHelper::_('COBALT_VIEW_NOTES').'" data-placement="bottom" class="btn" href="javascript:void(0);" onclick="openNoteModal(\'.deal->id.\',\'deal\');"><i class="glyphicon glyphicon-file"></i></a>'; $template .= ' <a data-toggle="popover" title="' . TextHelper::_('COBALT_VIEW_DETAILS') . '" data-placement="top" data-html="true" data-content-class="extras-' . $item->id . '" class="btn btn-xs btn-default" href="#" tabindex="0"><i class="glyphicon glyphicon-info-sign"></i></a>'; $template .= '</div>'; $template .= '<div class="extras-' . $item->id . ' hide">'; $template .= ' <b>' . TextHelper::_('COBALT_PRIMARY_CONTACT') . '</b>'; $template .= ' <a href="' . RouteHelper::_('index.php?view=people&layout=person&id=' . $item->primary_contact_id) . '">' . $item->primary_contact_first_name . '</a><br>'; $template .= ' <b>' . TextHelper::_('COBALT_NEXT_ACTION') . '</b><br>'; $template .= '</div>'; break; default: if (isset($column) && isset($item->{$column})) { $template = $item->{$column}; } else { $template = ''; } break; } return $template; }
public function getConversation($id) { //initialize query $query = $this->db->getQuery(true)->select("c.*, u.first_name as owner_first_name, u.last_name as owner_last_name,author.email")->from("#__conversations as c")->where("c.id=" . (int) $id)->where("c.published=" . $this->published)->leftJoin("#__users AS u ON u.id = c.author")->leftJoin("#__users AS author on author.id=u.id"); $results = $db->setQuery($query)->loadAssocList(); //clean results if (count($results) > 0) { foreach ($results as $key => $convo) { $results[$key]['created_formatted'] = DateHelper::formatDate($convo['created']); $results[$key]['owner_avatar'] = CobaltHelper::getGravatar($convo['email']); } } return $results; }
public function getNotes($object_id = NULL, $type = NULL, $display = true) { $app = \Cobalt\Container::fetch('app'); //grab db $db = JFactory::getDBO(); //initialize query $query = $db->getQuery(true); //gen query string $query->select("n.*,cat.name as category_name,comp.name as company_name,\n comp.id as company_id,deal.name as deal_name,deal.id as deal_id,\n person.id as person_id,person.first_name as person_first_name,\n person.last_name as person_last_name, owner.first_name as owner_first_name,\n event.name as event_name, event.id as event_id,\n owner.last_name as owner_last_name, author.email"); $query->from("#__notes as n"); $query->leftJoin("#__notes_categories AS cat ON cat.id = n.category_id"); $query->leftJoin("#__companies AS comp ON comp.id = n.company_id AND comp.published>0"); $query->leftJoin("#__events AS event ON event.id = n.event_id AND event.published>0"); $query->leftJoin("#__deals AS deal ON deal.id = n.deal_id AND deal.published>0"); $query->leftJoin("#__people AS person on n.person_id = person.id AND person.published>0"); $query->leftJoin("#__users AS owner ON n.owner_id = owner.id"); $query->leftJoin("#__users AS author ON author.id = owner.id"); $company_filter = $this->getState('Note.company_name'); if ($company_filter != null) { $query->where("comp.name LIKE '%" . $company_filter . "%'"); } //deal $deal_filter = $this->getState('Note.deal_name'); if ($deal_filter != null) { $query->where("deal.name LIKE '%" . $deal_filter . "%'"); } //person $person_filter = $this->getState('Note.person_name'); if ($person_filter != null) { } if ($object_id) { switch ($type) { case 'person': case 'people': $query->where('n.person_id =' . $object_id); break; case 'company': $query->where('(n.company_id =' . $object_id . ' OR deal.company_id = ' . $object_id . ' OR person.company_id = ' . $object_id . ")"); break; case 'deal': $query->where('n.deal_id=' . $object_id); break; case "event": $query->where("n.event_id={$object_id}"); break; } } //owner $owner_filter = $this->getState('Note.owner_id'); if ($owner_filter != null && $owner_filter != "all") { $owner_type = $this->getState('Note.owner_type'); switch ($owner_type) { case "team": $team_member_ids = UsersHelper::getTeamUsers($owner_filter, TRUE); $query->where("n.owner_id IN (" . implode(',', $team_member_ids) . ")"); break; case "member": $query->where("n.owner_id=" . $owner_filter); break; } } //created $created_filter = $this->getState('Note.created'); if ($company_filter != null) { } //category $category_filter = $this->getState('Note.category_id'); if ($category_filter != null) { $query->where("n.category_id=" . $category_filter); } if ($this->_id) { if (is_array($this->_id)) { $query->where("n.id IN (" . implode(',', $this->_id) . ")"); } else { $query->where("n.id={$this->_id}"); } } /** --------------------------------------------------------------- * Filter data using member role permissions */ $member_id = UsersHelper::getUserId(); $member_role = UsersHelper::getRole(); $team_id = UsersHelper::getTeamId(); if ($this->public_notes != true) { if ($member_role != 'exec') { //manager filter if ($member_role == 'manager') { $query->where('owner.team_id = ' . $team_id); } else { //basic user filter $query->where(array('n.owner_id = ' . $member_id)); } } } $query->where("n.published=" . $this->published); $query->order("n.modified DESC"); //load results $db->setQuery($query); $results = $db->loadAssocList(); //clean results if (count($results) > 0) { foreach ($results as $key => $note) { $results[$key]['created_formatted'] = DateHelper::formatDate($note['created']); $results[$key]['owner_avatar'] = CobaltHelper::getGravatar($note['email']); } } //$app->triggerEvent('onNoteLoad', array(&$results)); if (!$display) { //return results return $results; } else { $notesView = ViewHelper::getView('note', 'default', 'phtml', array('notes' => $results)); return $notesView; } }
/** * Prepare HTML field templates for each dataTable column. * * @param string column name * @param object of item * @return string HTML template for propper field */ public function getDataTableFieldTemplate($column, $item) { switch ($column) { case 'id': $template = '<input type="checkbox" class="export" name="ids[]" value="' . $item->id . '" />'; break; case 'name': $template = '<div class="title_holder">'; $template .= '<a href="' . RouteHelper::_('index.php?view=companies&layout=company&company_id=' . $item->id) . '">' . $item->name . '</a>'; $template .= '</div>'; if ($item->address_formatted != '') { $template .= '<address>' . $item->address_formatted . '</address>'; } $template .= '<div class="hidden"><small>' . $item->description . '</small></div>'; break; case 'contact_info': $template = $item->phone . '<br>' . $item->email; break; case 'modified': $template = DateHelper::formatDate($item->modified); break; case 'created': $template = DateHelper::formatDate($item->created); break; case 'action': $template = '<div class="btn-group">'; // @TODO: make these 2 buttons work // $template .= ' <a rel="tooltip" title="'.TextHelper::_('COBALT_VIEW_CONTACTS').'" data-placement="bottom" class="btn" href="#" onclick="showCompanyContactsDialogModal('.$item->id.')"><i class="glyphicon glyphicon-user"></i></a>'; // $template .= ' <a rel="tooltip" title="'.TextHelper::_('COBALT_VIEW_NOTES').'" data-placement="bottom" class="btn" href="#" onclick="openNoteModal('.$item->id.',\'company\');"><i class="glyphicon glyphicon-file"></i></a>'; $template .= '</div>'; break; default: if (isset($column) && isset($item->{$column})) { $template = $item->{$column}; } else { $template = ''; } break; } return $template; }
/** * Prepare HTML field templates for each dataTable column. * * @param string column name * @param object of item * @return string HTML template for propper field */ public function getDataTableFieldTemplate($column, $item) { switch ($column) { case 'id': $template = '<input type="checkbox" class="export" name="ids[]" value="' . $item->id . '" />'; break; case 'type': $file_path = sprintf('%s/media/images/%s.png', JPATH_COBALT, $item->filetype); if (file_exists($file_path)) { $file_src = sprintf('%s/src/Cobalt/media/images/%s.png', JUri::base(), $item->filetype); $template = '<img src="' . $file_src . '" >'; } else { $file_src = sprintf('%s/src/Cobalt/media/images/file.png', JUri::base()); $template = '<img src="' . $file_src . '" >'; } break; case 'name': $template = '<div class="dropdown"><span class="caret"></span><a id="' . $item->id . '" class="document_edit dropdown-toggle" data-toggle="dropdown" role="button" href="javascript:void(0);"> ' . $item->name . '</a>'; $template .= '<ul class="dropdown-menu" role="menu">'; $template .= '<li><a href="' . RouteHelper::_('index.php?task=PreviewDocument&format=raw&tmpl=component&document=' . $item->filename) . '" target="_blank" class="document_preview" id="preview_' . $item->id . '"><i class="glyphicon glyphicon-eye-open"></i> ' . TextHelper::_('COBALT_PREVIEW') . '</a></li>'; $template .= '<li><a href="' . RouteHelper::_('index.php?task=DownloadDocument&format=raw&tmpl=component&document=' . $item->filename) . '" target="_blank" class="document_download" id="download_' . $item->id . '"><i class="glyphicon glyphicon-download"></i> ' . TextHelper::_('COBALT_DOWNLOAD') . '</a></li>'; if ($item->owner_id == UsersHelper::getLoggedInUser()->id) { $template .= '<li><a href="javascript:void(0);" class="document_delete" id="delete_' . $item->id . '"><i class="glyphicon glyphicon-remove"></i> ' . TextHelper::_('COBALT_DELETE') . '</a></li>'; } $template .= '</ul></div>'; break; case 'association': $association_type = $item->association_type; //assign association link switch ($association_type) { case "deal": $view = 'deals'; $association_type = "deal"; $item->association_name = $item->deal_name; break; case "person": $view = "people"; $association_type = "person"; $item->association_name = $item->owner_first_name . " " . $item->owner_last_name; break; case "company": $view = "companies"; $association_type = "company"; $item->association_name = $item->company_name; break; } if (isset($item->association_name)) { $template = '<a href="' . RouteHelper::_('index.php?view=' . $view . '&layout=' . $association_type . '&id=' . $item->association_id) . '" >' . $item->association_name; } else { $template = ""; } break; case 'owner': $template = $item->owner_name; break; case 'size': $template = FileHelper::sizeFormat($item->size); break; case 'created': $template = DateHelper::formatDate($item->created); break; case 'modified': $template = DateHelper::formatDate($item->modified); break; default: if (isset($column) && isset($item->{$column})) { $template = $item->{$column}; } else { $template = ''; } break; } return $template; }
/** * Get Yearly Revenue * @param $access_type we wish to filter by 'member','team','company' * @param $access_id the id of the $access_type we wish to filter by * @return mixed $results */ public function getYearlyRevenue($access_type = null, $access_id = null) { //get db $db = JFactory::getDBO(); $query = $db->getQuery(true); //get current year and months to loop through $current_year = DateHelper::formatDBDate(date('Y-01-01 00:00:00')); $month_names = DateHelper::getMonthNames(); $months = DateHelper::getMonthDates(); //get stage id to filter deals by $won_stage_ids = DealHelper::getWonStages(); //gen query $results = array(); foreach ($months as $month) { $start_date = $month['date']; $end_date = DateHelper::formatDBDate(date('Y-m-d 00:00:00', strtotime("{$start_date} + 1 months"))); //flush the query $query = $db->getQuery(true); //generate query string $query->select("d.modified,SUM(d.amount) AS y"); $query->from("#__deals AS d"); $query->where("d.stage_id IN (" . implode(',', $won_stage_ids) . ")"); $query->where("d.modified >= '{$start_date}'"); $query->where("d.modified < '{$end_date}'"); $query->where("d.modified IS NOT NULL"); //sort by published deals $query->where("d.published>0"); //filter by access type if ($access_type != 'company') { //team sorting if ($access_type == 'team') { //get team members $team_members = UsersHelper::getTeamUsers($access_id); $query .= " AND d.owner_id IN ("; //loop to make string foreach ($team_members as $key => $member) { $query .= "'" . $member['id'] . "',"; } $query = substr($query, 0, -1); $query .= ") "; } //member filter if ($access_type == 'member') { $query->where("d.owner_id={$access_id}"); } } //get results and assign to month $db->setQuery($query); $totals = $db->loadAssoc(); if (!$totals) { $totals = array('y' => 0); } $totals['y'] = (int) $totals['y']; $results[] = $totals; } //return return $results; }
/** * Get yearly commission data for user * @param int $id to search for * @return mixed $results */ public function getYearlyCommissionData($id) { //get current year and months to loop through $current_year = DateHelper::formatDBDate(date('Y-01-01 00:00:00')); $month_names = DateHelper::getMonthNames(); $months = DateHelper::getMonthDates(); //get stage id to filter deals by $won_stage_ids = DealHelper::getWonStages(); //gen query $results = array(); foreach ($months as $month) { $start_date = $month['date']; $end_date = DateHelper::formatDBDate(date('Y-m-d 00:00:00', strtotime("{$start_date} + 1 months"))); //flush the query $query = $this->db->getQuery(true)->select("d.owner_id,d.modified,SUM(d.amount) AS y")->from("#__deals AS d")->where("d.stage_id IN (" . implode(',', $won_stage_ids) . ")")->where("d.modified >= '{$start_date}'")->where("d.modified < '{$end_date}'")->where("d.modified IS NOT NULL")->where("d.owner_id={$id}")->group("d.owner_id")->where("d.published>0"); $results[] = $this->db->setQuery($query)->loadAssoc(); } //clean data for commission rate foreach ($results as $key => $result) { $commission_rate = UsersHelper::getCommissionRate($result['owner_id']); $results[$key]['y'] = (int) $result['y'] * ($commission_rate / 100); } return $results; }
/** * Prepare HTML field templates for each dataTable column. * * @param string column name * @param object of item * @return string HTML template for propper field */ public function getDataTableFieldTemplate($column, $item) { switch ($column) { case 'id': $template = '<input type="checkbox" class="export" name="ids[]" value="' . $item->id . '" />'; break; case 'avatar': if (isset($item->avatar) && $item->avatar) { $template = '<img id="avatar_img_' . $item->id . '" data-item-type="people" data-item-id="' . $item->id . '" class="avatar" src="' . JURI::base() . 'src/Cobalt/media/avatars/' . $item->avatar . '"/>'; } else { $template = '<img id="avatar_img_' . $item->id . '" data-item-type="people" data-item-id="' . $item->id . '" class="avatar" src="' . JURI::base() . 'src/Cobalt/media/images/person.png' . '"/>'; } break; case 'name': $template = '<a href="' . RouteHelper::_('index.php?view=people&layout=person&id=' . $item->id) . '">' . $item->first_name . ' ' . $item->last_name . '</a>'; break; case 'company_name': $template = '<a href="' . RouteHelper::_('index.php?view=companies&layout=company&id=' . $item->company_id) . '">' . $item->company_name . '</a>'; break; case 'owner': if (!isset($item->owner_last_name) || !$item->owner_last_name) { $item->status_name = TextHelper::_('COBALT_CLICK_TO_EDIT'); } $me = array(array('label' => TextHelper::_('COBALT_ME'), 'value' => UsersHelper::getLoggedInUser()->id)); $users = UsersHelper::getUsers(null, true); $users = array_merge($me, $users); $template = '<div class="dropdown">'; $template .= ' <a href="#" class="dropdown-toggle update-toggle-html" role="button" data-toggle="dropdown" id="oerson_owner_' . $item->id . '_link">'; $template .= $item->owner_first_name . ' ' . $item->owner_last_name; $template .= ' </a>'; $template .= ' <ul class="dropdown-menu" aria-labelledby="deal_status_' . $item->id . '" role="menu">'; if (isset($users) && count($users)) { foreach ($users as $id => $user) { $template .= ' <li>'; $template .= ' <a href="#" class="owner_select dropdown_item" data-field="owner_id" data-item="person" data-item-id="' . $item->id . '" data-value="' . $user['value'] . '">'; $template .= ' <span class="person-owner-' . OutputFilter::stringURLUnicodeSlug($user['value']) . '">' . $user['label'] . '</span>'; $template .= ' </a>'; $template .= ' </li>'; } } $template .= ' </ul>'; $template .= ' </div>'; break; case 'status_name': if (!isset($item->status_id) || !$item->status_id) { $item->status_name = TextHelper::_('COBALT_CLICK_TO_EDIT'); } $statuses = PeopleHelper::getStatusList(); $template = '<div class="dropdown">'; $template .= ' <a href="#" class="dropdown-toggle update-toggle-html" role="button" data-toggle="dropdown" id="deal_stage_' . $item->id . '_link">'; $template .= ' <span class="person-status-' . $item->status_name . '">' . $item->status_name . '</span>'; $template .= ' </a>'; $template .= ' <ul class="dropdown-menu" aria-labelledby="deal_stage_' . $item->id . '" role="menu">'; if (isset($statuses) && count($statuses)) { foreach ($statuses as $id => $status) { $template .= ' <li>'; $template .= ' <a href="#" class="status_select dropdown_item" data-field="status_id" data-item="people" data-item-id="' . $item->id . '" data-value="' . $status['id'] . '">'; $template .= ' <span class="person-status-' . OutputFilter::stringURLUnicodeSlug($status['id']) . '">' . $status['name'] . '</span>'; $template .= ' </a>'; $template .= ' </li>'; } } $template .= ' </ul>'; $template .= ' </div>'; break; case 'source_name': if (!isset($item->source_id) || !$item->source_id) { $item->source_name = TextHelper::_('COBALT_CLICK_TO_EDIT'); } $sources = DealHelper::getSources(null, true); $template = '<div class="dropdown">'; $template .= ' <a href="#" class="dropdown-toggle update-toggle-html" role="button" data-toggle="dropdown" id="person_source_' . $item->id . '_link">'; $template .= ' <span class="person-source-' . $item->source_name . '">' . $item->source_name . '</span>'; $template .= ' </a>'; $template .= ' <ul class="dropdown-menu" aria-labelledby="person_source_' . $item->id . '" role="menu">'; if (isset($sources) && count($sources)) { foreach ($sources as $id => $name) { $template .= ' <li>'; $template .= ' <a href="#" class="source_select dropdown_item" data-field="source_id" data-item="people" data-item-id="' . $item->id . '" data-value="' . $id . '">'; $template .= ' <span class="person-source-' . OutputFilter::stringURLUnicodeSlug($name) . '">' . $name . '</span>'; $template .= ' </a>'; $template .= ' </li>'; } } $template .= ' </ul>'; $template .= ' </div>'; break; case 'type': if (!isset($item->type) || !$item->type) { $item->type = TextHelper::_('COBALT_CLICK_TO_EDIT'); } $types = PeopleHelper::getPeopleTypes(false); $template = '<div class="dropdown">'; $template .= ' <a href="#" class="dropdown-toggle update-toggle-html" role="button" data-toggle="dropdown" id="person_type_' . $item->id . '_link">'; $template .= $item->type; $template .= ' </a>'; $template .= ' <ul class="dropdown-menu" aria-labelledby="person_type_' . $item->id . '" role="menu">'; if (isset($types) && count($types)) { foreach ($types as $id => $name) { $template .= ' <li>'; $template .= ' <a href="#" class="type_select dropdown_item" data-field="type" data-item="people" data-item-id="' . $item->id . '" data-value="' . $id . '">'; $template .= ' <span class="person-type-' . OutputFilter::stringURLUnicodeSlug($name) . '">' . $name . '</span>'; $template .= ' </a>'; $template .= ' </li>'; } } $template .= ' </ul>'; $template .= ' </div>'; break; case 'notes': // $template = '<a rel="tooltip" title="'.TextHelper::_('COBALT_VIEW_NOTES').'" data-placement="bottom" class="btn" href="#" onclick="Cobalt.openNoteModal('.$item->id.', \'people\');"><i class="glyphicon glyphicon-file"></i></a>'; $template = ''; // @TODO: Implement notes modal break; case 'address': $template = $item->work_city . '<br>' . $item->work_state . '<br>' . $item->work_zip . '<br>' . $item->work_country; break; case 'created': $template = DateHelper::formatDate($item->created); break; case 'modified': $template = DateHelper::formatDate($item->modified); break; default: if (isset($column) && isset($item->{$column})) { $template = $item->{$column}; } else { $template = ''; } break; } return $template; }
/** * Save user avatars * @return [type] [description] */ public function saveAvatar() { //this is the name of the field in the html form, filedata is the default name for swfupload //so we will leave it as that $fieldName = 'avatar'; //any errors the server registered on uploading $fileError = $_FILES[$fieldName]['error']; if ($fileError > 0) { switch ($fileError) { case 1: echo TextHelper::_('FILE TO LARGE THAN PHP INI ALLOWS'); return false; case 2: echo TextHelper::_('FILE TO LARGE THAN HTML FORM ALLOWS'); return false; case 3: echo TextHelper::_('ERROR PARTIAL UPLOAD'); return false; case 4: echo TextHelper::_('ERROR NO FILE'); return false; } } //check the file extension is ok $fileName = $_FILES[$fieldName]['name']; $fileTemp = $_FILES[$fieldName]['tmp_name']; $uploadedFileNameParts = explode('.', $fileName); $uploadedFileExtension = array_pop($uploadedFileNameParts); $validFileExts = explode(',', 'jpeg,jpg,png,gif,bmp'); //assume the extension is false until we know its ok $extOk = false; //go through every ok extension, if the ok extension matches the file extension (case insensitive) //then the file extension is ok foreach ($validFileExts as $key => $value) { if (preg_match("/{$value}/i", $uploadedFileExtension)) { $extOk = true; } } if ($extOk == false) { echo TextHelper::_('INVALID EXTENSION'); return false; } //data generation $date = DateHelper::formatDBDate(date('Y-m-d H:i:s')); $hashFilename = md5($fileName . $date) . "." . $uploadedFileExtension; //lose any special characters in the filename //$fileName = preg_replace("[^A-Za-z0-9.]", "-", $fileName); //always use constants when making file paths, to avoid the possibilty of remote file inclusion $uploadPath = JPATH_SITE . '/src/Cobalt/media/avatars/' . $hashFilename; if (!File::upload($fileTemp, $uploadPath)) { echo TextHelper::_('ERROR MOVING FILE'); return false; } $image = new Image(); $image->loadFile($uploadPath); $image->resize(50, 50, false); $image->toFile($uploadPath); $data = array('id' => $this->state->get('item_id'), 'avatar' => $hashFilename); $item_type = $this->state->get('item_type'); $this->deleteOldAvatar($data['id'], $item_type); switch ($item_type) { case "people": $model_name = "people"; break; case "companies": $model_name = "company"; break; } $modelClass = "Cobalt\\Model\\" . ucwords($model_name); $model = new $modelClass($this->db); $model->store($data); return JUri::base() . 'src/Cobalt/media/avatars/' . $hashFilename; }
/** * Method to run the application routines. * * @return void * * @since 1.0 */ public function doExecute() { // Register the template to the config $template = $this->getTemplate(true); $this->set('theme', $template->template); $this->set('themeFile', $this->input->get('tmpl', 'index') . '.php'); // Set metadata $this->document->setTitle('Cobalt'); // Start the output buffer ob_start(); // Install check if (!file_exists(JPATH_CONFIGURATION . '/configuration.php') || filesize(JPATH_CONFIGURATION . '/configuration.php') < 10) { // Redirect to the installer if we aren't there if (strpos($this->get('uri.route'), 'install') === false && $this->input->getString('task') != 'install') { ob_end_flush(); $this->redirect(RouteHelper::_('index.php?view=install')); } // Build a session object to push into the DI container $session = new Session(new MockFileSessionStorage()); $this->getContainer()->set('session', $session); // Fetch the controller $controllerObj = $this->getRouter()->getController($this->get('uri.route')); // Perform the Request task $controllerObj->execute(); } elseif (file_exists(JPATH_CONFIGURATION . '/configuration.php') && filesize(JPATH_CONFIGURATION . '/configuration.php') > 10 && strpos($this->get('uri.route'), 'install') !== false) { $this->redirect(RouteHelper::_('index.php')); } else { // Finish bootstrapping the application now $this->getContainer()->registerServiceProvider(new Provider\ConfigServiceProvider())->registerServiceProvider(new Provider\DatabaseServiceProvider())->registerServiceProvider(new Provider\SessionServiceProvider()); $this->loadConfiguration(); // Load Language UsersHelper::loadLanguage(); // Set site timezone $tz = DateHelper::getSiteTimezone(); // Get user object $user = $this->getUser(); // Fetch the controller $controllerObj = $this->getRouter()->getController($this->get('uri.route')); // Require specific controller if requested $controller = $this->input->get('controller', 'default'); // Load user toolbar $format = $this->input->get('format'); $overrides = array('ajax', 'mail', 'login'); $loggedIn = $user->isAuthenticated(); if ($loggedIn && $format !== 'raw' && !in_array($controller, $overrides)) { ActivityHelper::saveUserLoginHistory(); // Set a default view if none exists $this->input->def('view', 'dashboard'); // Grab document instance $document = $this->getDocument(); // Start component div wrapper if (!in_array($this->input->get('view'), array('print'))) { TemplateHelper::loadToolbar(); } TemplateHelper::startCompWrap(); // Load javascript language TemplateHelper::loadJavascriptLanguage(); TemplateHelper::showMessages(); } if (!$loggedIn && !$controllerObj instanceof \Cobalt\Controller\Login) { $this->redirect(RouteHelper::_('index.php?view=login')); } // Fullscreen detection if (UsersHelper::isFullscreen()) { $this->input->set('tmpl', 'component'); } // Perform the Request task $controllerObj->execute(); // End componenet wrapper if ($user !== false && $format !== 'raw') { TemplateHelper::endCompWrap(); } } $contents = ob_get_clean(); if ($this->input->get('format', 'html') === 'raw') { $this->setBody($contents); } else { $this->document->setBuffer($contents, 'cobalt'); $this->setBody($this->document->render(false, (array) $template)); } }
/** * Get custom field values from picklists // forecasts // otherwise return the value as it was an input field */ public static function getCustomValue($customType, $customNameOrId, $customValue, $itemId) { $db = \Cobalt\Container::fetch('db'); $query = $db->getQuery(true); $id = str_replace("custom_", "", $customNameOrId); $query->select("c.type,c.values")->from("#__" . $customType . "_custom AS c")->where("c.id=" . $id); $db->setQuery($query); $custom = $db->loadObject(); switch ($custom->type) { case "forecast": $query->clear(); $query->select("(d.amount * ( d.probability / 100 )) AS amount")->from("#__deals AS d")->where("d.id=" . $itemId); $db->setQuery($query); $result = $db->loadResult(); return ConfigHelper::getCurrency() . $result; break; case "currency": return ConfigHelper::getCurrency() . $customValue; break; case "picklist": $values = json_decode($custom->values); return array_key_exists($customValue, $values) ? $values[$customValue] : TextHelper::_('COBALT_NONE'); break; case "date": return DateHelper::formatDate($customValue); break; default: return $customValue; break; } return $customValue; }
/** * Method to store a record * * @return boolean True on success */ public function store($data = null) { if (!$data) { $data = $this->app->input->post->getArray(); } //Load Table $row = new UserTable(); if (isset($data['id']) && $data['id']) { $row->load($data['id']); } if (isset($data['fullscreen'])) { $data['fullscreen'] = !$row->fullscreen; } if (isset($data['password']) && $data['password']) { $data['password'] = UsersHelper::hashPassword($data['password']); } //date generation $date = DateHelper::formatDBDate(date('Y-m-d H:i:s')); $data['modified'] = $date; // Bind the form fields to the table if (!$row->bind($data)) { $this->setError($this->db->getErrorMsg()); return false; } // Make sure the record is valid if (!$row->check()) { $this->setError($this->db->getErrorMsg()); return false; } // Store the web link table to the database if (!$row->store()) { $this->setError($this->db->getErrorMsg()); return false; } //update users email address if (array_key_exists('email', $data)) { $this->updateEmail($row->id, $data['email']); } if (isset($data['team_name']) && $data['team_name']) { $teamModel = new Teams(); $teamModel->createTeam($row->id, $data['team_name']); } $this->app->refreshUser(); return $row->id; }
/** * Get data for custom reports * @param int $id custom id data to retrieve * @return mixed $results */ public function getCustomReportData($id = null) { //get db $db = JFactory::getDBO(); $query = $db->getQuery(true); $app = \Cobalt\Container::fetch('app'); //get the custom report so we know what data to filter and select $custom_report = $this->getCustomReports($id); $custom_report = $custom_report[0]; $custom_report_fields = unserialize($custom_report['fields']); //gen query //construct query string $queryString = 'd.*,SUM(d.amount) AS filtered_total,'; $queryString .= 'c.name as company_name,'; $queryString .= 'stat.name as status_name,'; $queryString .= 'source.name as source_name,'; $queryString .= 'stage.name as stage_name,stage.percent,'; $queryString .= 'user.first_name, user.last_name,'; $queryString .= 'p.first_name as primary_contact_first_name,p.last_name as primary_contact_last_name,'; $queryString .= "p.email as primary_contact_email,p.phone as primary_contact_phone,"; $queryString .= "pc.name as primary_contact_company_name"; //select $query->select($queryString); $query->from("#__deals AS d"); //left join $query->leftJoin('#__companies AS c ON c.id = d.company_id AND c.published>0'); $query->leftJoin('#__deal_status AS stat ON stat.id = d.status_id'); $query->leftJoin('#__sources AS source ON source.id = d.source_id'); $query->leftJoin('#__stages AS stage on stage.id = d.stage_id'); $query->leftJoin('#__users AS user ON user.id = d.owner_id'); $query->leftJoin("#__people AS p ON p.id = d.primary_contact_id AND p.published>0"); $query->leftJoin("#__companies AS pc ON pc.id = p.company_id AND pc.published>0"); //group results $query->group("d.id"); //filter data with user state requests $layout = str_replace("_filter", "", $app->input->get('layout')); $view = $app->input->get('view'); if ($view == "print") { $layout = "custom_report"; $id = $app->input->get('custom_report'); } $filter_order = $this->getState('Report.' . $id . '_' . $layout . '_filter_order'); $filter_order_Dir = $this->getState('Report.' . $id . '_' . $layout . '_filter_order_Dir'); $filter_order = strstr($filter_order, "custom_") ? str_replace("d.", "", $filter_order) : $filter_order; $query->order($filter_order . ' ' . $filter_order_Dir); //assign defaults $close = null; $modified = null; $created = null; $status = null; $source = null; $stage = null; //filter by deal names $deal_filter = $this->getState('Report.' . $id . '_' . $layout . '_name'); if ($deal_filter != null) { $query->where("d.name LIKE '%" . $deal_filter . "%'"); } //owner $owner_filter = $this->getState('Report.' . $id . '_' . $layout . '_owner_id'); if ($owner_filter != null and $owner_filter != 'all') { $owner_type = $this->getState('Report.' . $id . '_' . $layout . '_owner_type'); if ($owner_type == 'member') { $query->where("d.owner_id=" . $owner_filter); } if ($owner_type == 'team') { //get team members $team_members = UsersHelper::getTeamUsers($owner_filter); //filter by results having team ids $ids = ""; for ($i = 0; $i < count($team_members); $i++) { $member = $team_members[$i]; $ids .= $member['id'] . ","; } $ids = substr($ids, 0, -1); $query->where("d.owner_id IN(" . $ids . ")"); } } //amount $amount_filter = $this->getState('Report.' . $id . '_' . $layout . '_amount'); if ($amount_filter != null and $amount_filter != 'all') { if ($amount_filter == 'small') { $query->where("d.amount <= 50"); } if ($amount_filter == 'medium') { $query->where("d.amount > 50 AND d.amount <= 400"); } if ($amount_filter == 'large') { $query->where("d.amount > 400"); } } //source $source_filter = $this->getState('Report.' . $id . '_' . $layout . '_source_id'); if ($source_filter != null and $source_filter != 'all') { $source = $source_filter; } //stage $stage_filter = $this->getState('Report.' . $id . '_' . $layout . '_stage_id'); if ($stage_filter != null and $stage_filter != 'all') { $stage = $stage_filter; } //status $status_filter = $this->getState('Report.' . $id . '_' . $layout . '_status_id'); if ($status_filter != null and $status_filter != 'all') { $status = $status_filter; } //expected close $expected_close_filter = $this->getState('Report.' . $id . '_' . $layout . '_expected_close'); if ($expected_close_filter != null and $expected_close_filter != 'all') { $close = $expected_close_filter; } //modified $modified_filter = $this->getState('Report.' . $id . '_' . $layout . '_modified'); if ($modified_filter != null and $modified_filter != 'all') { $modified = $modified_filter; } //created $created_filter = $this->getState('Report.' . $id . '_' . $layout . '_created'); if ($created_filter != null and $created_filter != 'all') { $created = $created_filter; } //filter by primary contact name $primary_contact_name = $this->getState('Report.' . $id . '_' . $layout . '_primary_contact_name'); if ($primary_contact_name != null) { $query->where("(p.first_name LIKE '%" . $primary_contact_name . "%' OR p.last_name LIKE '%" . $primary_contact_name . "%')"); } //filter by primary contact email $primary_contact_email = $this->getState('Report.' . $id . '_' . $layout . '_primary_contact_email'); if ($primary_contact_email != null) { $query->where("p.email LIKE '%" . $primary_contact_email . "%'"); } //filter by primary contact phone $primary_contact_phone = $this->getState('Report.' . $id . '_' . $layout . '_primary_contact_phone'); if ($primary_contact_phone != null) { $query->where("p.phone LIKE '%" . $primary_contact_phone . "%'"); } //get current date to use for all date filtering $date = DateHelper::formatDBDate(date('Y-m-d 00:00:00')); /** -------------------------------------------- * Search for closing deal filters */ if ($close != null && $close != "any") { if ($close == "this_week") { $this_week = DateHelper::formatDBDate(date('Y-m-d 00:00:00')); $next_week = date('Y-m-d 00:00:00', strtotime(date("Y-m-d", strtotime($date)) . "+7 days")); $query->where("d.expected_close >= '{$this_week}'"); $query->where("d.expected_close < '{$next_week}'"); } if ($close == "next_week") { $next_week = date('Y-m-d 00:00:00', strtotime(DateHelper::formatDBDate(date("Y-m-d", strtotime($date))) . "+7 days")); $week_after_next = date('Y-m-d 00:00:00', strtotime(date("Y-m-d", strtotime($date)) . "+14 days")); $query->where("d.expected_close >= '{$next_week}'"); $query->where("d.expected_close < '{$week_after_next}'"); } if ($close == "this_month") { $this_month = DateHelper::formatDBDate(date('Y-m-0 00:00:00')); $next_month = date('Y-m-0 00:00:00', strtotime(date("Y-m-d", strtotime($date)) . "+1 month")); $query->where("d.expected_close >= '{$this_month}'"); $query->where("d.expected_close < '{$next_month}'"); } if ($close == "next_month") { $next_month = date("Y-m-0 00:00:00", strtotime(date("Y-m-d 00:00:00", strtotime($date)) . "+1 month")); $next_next_month = date("Y-m-0 00:00:00", strtotime(date("Y-m-d 00:00:00", strtotime($date)) . "+2 months")); $query->where("d.expected_close >= '{$next_month}'"); $query->where("d.expected_close < '{$next_next_month}'"); } } /** -------------------------------------------- * Search for modified deal filters */ if ($modified != null && $modified != "any") { if ($modified == "this_week") { $this_week = DateHelper::formatDBDate(date('Y-m-d 00:00:00')); $last_week = date('Y-m-d 00:00:00', strtotime(date("Y-m-d", strtotime($date)) . "-7 days")); $query->where("d.modified >= '{$last_week}'"); $query->where("d.modified < '{$this_week}'"); } if ($modified == "last_week") { $last_week = DateHelper::formatDBDate(date("Y-m-d", strtotime("-7 days"))); $week_before_last = DateHelper::formatDBDate(date("Y-m-d", strtotime("-14 days"))); $query->where("d.modified >= '{$week_before_last}'"); $query->where("d.modified < '{$last_week}'"); } if ($modified == "this_month") { $this_month = DateHelper::formatDBDate(date('Y-m-1 00:00:00')); $next_month = date('Y-m-1 00:00:00', strtotime(date("Y-m-d", strtotime($date)) . "+1 month")); $query->where("d.modified >= '{$this_month}'"); $query->where("d.modified < '{$next_month}'"); } if ($modified == "last_month") { $this_month = DateHelper::formatDBDate(date('Y-m-1 00:00:00')); $last_month = date('Y-m-1 00:00:00', strtotime(date("Y-m-d", strtotime($date)) . "-1 month")); $query->where("d.modified >= '{$last_month}'"); $query->where("d.modified < '{$this_month}'"); } } /** -------------------------------------------- * Search for created deal filters */ if ($created != null && $created != "any") { if ($created == "this_week") { $this_week = DateHelper::formatDBDate(date('Y-m-d 00:00:00')); $last_week = date('Y-m-d 00:00:00', strtotime(date("Y-m-d", strtotime($date) . "-7 days"))); $query->where("d.created >= '{$last_week}'"); $query->where("d.created < '{$this_week}'"); } if ($created == "last_week") { $last_week = DateHelper::formatDBDate(date("Y-m-d", strtotime("-7 days"))); $week_before_last = DateHelper::formatDBDate(date("Y-m-d", strtotime("-14 days"))); $query->where("d.created >= '{$week_before_last}'"); $query->where("d.created < '{$last_week}'"); } if ($created == "this_month") { $this_month = DateHelper::formatDBDate(date('Y-m-1 00:00:00')); $next_month = date('Y-m-1 00:00:00', strtotime(date("Y-m-d", strtotime($date)) . "+1 month")); $query->where("d.created >= '{$this_month}'"); $query->where("d.created < '{$next_month}'"); } if ($created == "last_month") { $this_month = DateHelper::formatDBDate(date('Y-m-1 00:00:00')); $last_month = date('Y-m-1 00:00:00', strtotime(date("Y-m-d", strtotime($date) . "-1 month"))); $query->where("d.created >= '{$last_month}'"); $query->where("d.created < '{$this_month}'"); } if ($created == "today") { $today = DateHelper::formatDBDate(date("Y-m-d 00:00:00")); $tomorrow = date('Y-m-d 00:00:00', strtotime(date("Y-m-d", strtotime($date)) . "+1 day")); $query->where("d.created >= '{$today}'"); $query->where("d.created < '{$tomorrow}'"); } if ($created == "yesterday") { $today = DateHelper::formatDBDate(date("Y-m-d 00:00:00")); $yesterday = date('Y-m-d 00:00:00', strtotime(date("Y-m-d", strtotime($date)) . "-1 day")); $query->where("d.created >= '{$yesterday}'"); $query->where("d.created < '{$today}'"); } } /** ------------------------------------------ * Search for status */ if ($status != null and $status != 'all') { $query->where("d.status_id=" . $status); } /** ------------------------- * Search for sources */ if ($source != null and $source != 'all') { $query->where('d.source_id=' . $source); } /** ---------------------------------------------------------------- * Filter for stage id associations */ if ($stage != null && $stage != 'all') { //if we want active deals we must retrieve the active stage ids to filter by if ($stage == 'active') { //get stage ids $stage_ids = DealHelper::getActiveStages(); //filter by results having team ids $stages = ""; for ($i = 0; $i < count($stage_ids); $i++) { $stage = $stage_ids[$i]; $stages .= $stage['id'] . ","; } $stages = substr($stages, 0, -1); $query->where("d.stage_id IN(" . $stages . ")"); } else { // else filter by the stage id $query->where("d.stage_id='" . $stage . "'"); } } /** --------------------------------------------------------------------------------------------------------------- * Field for custom field user states */ //Get custom filters $custom_fields = DealHelper::getUserCustomFields(); //If the user has defined any custom fields we will left join the associated data here if (count($custom_fields) > 0) { foreach ($custom_fields as $row) { //Join different data based on type switch ($row['type']) { //If the type is forecast we want to calculate the amount case "forecast": $query->select("( d.amount * ( d.probability / 100 )) as custom_" . $row['id']); break; //Else join the associated value from the database //Else join the associated value from the database default: $query->select("custom_" . $row['id'] . ".value as custom_" . $row['id']); $query->leftJoin("#__deal_custom_cf as custom_" . $row['id'] . " on " . "custom_" . $row['id'] . ".deal_id = d.id AND " . "custom_" . $row['id'] . ".custom_field_id = " . $row['id']); break; } //If the user has any associated user state requests set in the model we set the filters here $custom_field_filter = $this->getState('Report.' . $id . '_' . $layout . '_' . $row['id']); if ($custom_field_filter != null and $custom_field_filter != 'all') { switch ($row['type']) { case "forecast": $query->where("( d.amount * ( d.probability / 100 )) LIKE '%" . $custom_field_filter . "%'"); break; case "date": if ($custom_field_filter == "this_week") { $this_week = DateHelper::formatDBDate(date('Y-m-d 00:00:00')); $next_week = date('Y-m-d 00:00:00', strtotime(date("Y-m-d", strtotime($date)) . "+7 days")); $query->where("custom_" . $row['id'] . ".value >= '{$this_week}'"); $query->where("custom_" . $row['id'] . ".value < '{$next_week}'"); } if ($custom_field_filter == "next_week") { $next_week = date('Y-m-d 00:00:00', strtotime(date("Y-m-d", strtotime($date)) . "+7 days")); $week_after_next = date('Y-m-d 00:00:00', strtotime(date("Y-m-d", strtotime($date)) . "+14 days")); $query->where("custom_" . $row['id'] . ".value >= '{$next_week}'"); $query->where("custom_" . $row['id'] . ".value < '{$week_after_next}'"); } if ($custom_field_filter == "this_month") { $this_month = DateHelper::formatDBDate(date('Y-m-0 00:00:00')); $next_month = date('Y-m-0 00:00:00', strtotime(date("Y-m-d", strtotime($date)) . "+1 month")); $query->where("custom_" . $row['id'] . ".value >= '{$this_month}'"); $query->where("custom_" . $row['id'] . ".value < '{$next_month}'"); } if ($custom_field_filter == "next_month") { $next_month = date("Y-m-0 00:00:00", strtotime(date("Y-m-d 00:00:00", strtotime($date)) . "+1 month")); $next_next_month = date("Y-m-0 00:00:00", strtotime(date("Y-m-d 00:00:00", strtotime($date)) . "+2 months")); $query->where("custom_" . $row['id'] . ".value >= '{$next_month}'"); $query->where("custom_" . $row['id'] . ".value < '{$next_next_month}'"); } break; default: $query->where("custom_" . $row['id'] . ".value LIKE '%" . $custom_field_filter . "%'"); break; } } } } //filter based on member access roles $user_id = UsersHelper::getUserId(); $member_role = UsersHelper::getRole(); $team_id = UsersHelper::getTeamId(); if ($member_role != 'exec') { if ($member_role == 'manager') { $query->where("user.team_id={$team_id}"); } else { $query->where("(d.owner_id={$user_id})"); } } $query->where("d.published=" . $this->published); $query->where("d.archived=0"); //return results $db->setQuery($query); $results = $db->loadAssocList(); return $results; }
public function _display_sales_pipeline() { //get deals for reports $dealModel = new DealModel(); $dealModel->set('archived', 0); $dealModel->set('limit', 0); $reports = $dealModel->getReportDeals(); // Initialise state variables. $state = $dealModel->getState(); //info for dropdowns $deal_amounts = DealHelper::getAmounts(); $deal_stages = DealHelper::getActiveStages(TRUE); $deal_statuses = DealHelper::getStatuses(); $deal_close_dates = DealHelper::getClosing(); $modified_dates = DealHelper::getModified(); //list view $sales_pipeline_header = ViewHelper::getView('reports', 'sales_pipeline_header', 'phtml', array('state' => $state, 'reports' => $reports)); $sales_pipeline_list = ViewHelper::getView('reports', 'sales_pipeline_filter', 'phtml', array('reports' => $reports)); $sales_pipeline_footer = ViewHelper::getView('reports', 'sales_pipeline_footer', 'phtml'); $sales_pipeline_header->deal_amounts = $deal_amounts; $sales_pipeline_header->deal_stages = $deal_stages; $sales_pipeline_header->deal_statuses = $deal_statuses; $sales_pipeline_header->deal_close_dates = $deal_close_dates; $sales_pipeline_header->modified_dates = $modified_dates; $sales_pipeline_header->created_dates = DateHelper::getCreatedDates(); $sales_pipeline_header->team_names = DropdownHelper::getTeamNames(); $sales_pipeline_header->user_names = DropdownHelper::getUserNames(); $sales_pipeline_header->state = $state; //assign refs to view $this->sales_pipeline_header = $sales_pipeline_header; $this->sales_pipeline_list = $sales_pipeline_list; $this->sales_pipeline_footer = $sales_pipeline_footer; $this->state = $state; $this->reports = $reports; }
public function _buildQuery() { $app = \Cobalt\Container::fetch('app'); $loc = $app->input->getCmd('loc', $this->loc); $association = null; $user = null; if ($this->db->name == 'mysqli') { $this->db->setQuery("SET SQL_BIG_SELECTS=1")->execute(); } $query = $this->db->getQuery(true); $db = $this->db; $query->select("e.*," . "a.*," . "ci.name AS category_name," . "c.name as company_name, c.id as company_id," . "d.name as deal_name,d.id as deal_id," . "p.first_name as person_first_name, p.last_name as person_last_name,p.id as person_id," . "assignee.color AS assignee_color," . 'assignee.first_name AS assignee_first_name,assignee.last_name AS assignee_last_name,' . "owner.first_name as owner_first_name, owner.last_name as owner_last_name " . "FROM #__events AS e"); $query->leftJoin("#__events_categories AS ci ON ci.id = e.category_id"); $query->leftJoin("#__events_cf AS a ON e.id = a.event_id"); $query->leftJoin("#__companies AS c ON a.association_type = 'company' AND a.association_id = c.id AND c.published>0"); $query->leftJoin("#__deals AS d ON a.association_type = 'deal' AND a.association_id = d.id AND d.published>0"); $query->leftJoin("#__people AS p ON a.association_type = 'person' AND a.association_id = p.id AND p.published>0"); $query->leftJoin('#__users AS assignee ON assignee.id = e.assignee_id'); $query->leftJoin('#__users AS owner ON owner.id = e.owner_id'); //gather info $user_role = UsersHelper::getRole(); $user_id = UsersHelper::getUserId(); $team_id = UsersHelper::getTeamId(); //filter based on user role if ($user_role != 'exec' && $this->view != "print") { //manager filter if ($user_role == 'manager') { $query->where('(assignee.team_id = ' . $team_id . ' OR owner.team_id = ' . $team_id . ")"); } else { //basic user filter $query->where("(e.assignee_id = " . $user_id . " OR e.owner_id =" . $user_id . ")"); } } //search for certain user events if ($user && $this->view != "print") { if ($user == $user_id) { $query->where("(e.assignee_id=" . $user_id . ' OR e.owner_id=' . $user_id . ')'); } elseif ($user != 'all') { $query->where(array("e.assignee_id=" . $user)); } } if (!$association) { $association = $app->input->get('association_id') ? $app->input->get('association_id') : $app->input->get('id'); } $association_type = $app->input->get('association_type') ? $app->input->get('association_type') : $app->input->get('layout'); $association_types = array("company", "deal", "person"); if ($association) { $association_type = $association_type ? $association_type : $loc; if ($association_type == "company") { if (is_array($association)) { $query->where("(p.company_id=" . $association . " OR d.company_id=" . $association . " OR ( a.association_type=" . $db->quote("company") . " AND a.association_id IN(" . implode(",", $association) . ") ))"); } else { $query->where("(p.company_id=" . $association . " OR d.company_id=" . $association . " OR ( a.association_type=" . $db->quote("company") . " AND a.association_id=" . $association . " ))"); } } else { if (is_array($association)) { $query->where("a.association_id IN(" . implode(",", $association) . ")"); } else { $query->where("a.association_id=" . $association); } $query->where("a.association_type=" . $db->quote($association_type)); } } elseif ($association_type && in_array($association_type, $association_types)) { $query->where("a.association_type=" . $db->Quote($association_type)); } else { /** hide events associated with archived deals **/ $query->where("(d.archived=0 OR d.archived IS NULL)"); } if ($this->_id != null) { if (is_array($this->_id)) { $query->where("e.id IN (" . implode(',', $this->_id) . ")"); } else { $query->where("e.id={$this->_id}"); } } if ($this->current_events) { $now = DateHelper::formatDBDate(date('Y-m-d')); $query->where('e.due_date != "0000-00-00 00:00:00" AND e.due_date >="' . $now . '"'); } /** Filter by status **/ $status_filter = $this->getState('Event.' . $this->view . '_' . $this->layout . '_status'); if ($status_filter != null && $this->view != "print") { $query->where("e.completed={$status_filter}"); } else { if ($this->completed != null) { if ($this->completed == 'true') { $query->where("e.completed=1"); } elseif ($this->completed != 'false') { $query->where("e.completed=" . $this->completed); } } else { $query->where("e.completed=0"); } } /** Filter by type **/ $type_filter = $this->getState('Event.' . $this->view . '_' . $this->layout . '_type'); if ($type_filter != null && $type_filter != "all" && $this->view != "print") { $query->where("e.type='{$type_filter}'"); } /** Filter by category **/ $category_filter = $this->getState('Event.' . $this->view . '_' . $this->layout . '_category'); if ($category_filter != null && $category_filter != "any" && $this->view != "print") { $query->where("e.category_id={$category_filter}"); } /** Filter by due date **/ $due_date_filter = $this->getState('Event.' . $this->view . '_' . $this->layout . '_due_date'); if ($due_date_filter != null && $due_date_filter != "any" && $this->view != "print") { $date = DateHelper::formatDBDate(date('Y-m-d 00:00:00')); switch ($due_date_filter) { case "today": $tomorrow = DateHelper::formatDBDate(date('Y-m-d 00:00:00', time() + 1 * 24 * 60 * 60)); $query->where("((e.due_date >= '{$date}' AND e.due_date < '{$tomorrow}') OR (e.start_time >= '{$date}' AND e.start_time < '{$tomorrow}'))"); break; case "tomorrow": $tomorrow = DateHelper::formatDBDate(date('Y-m-d 00:00:00', time() + 1 * 24 * 60 * 60)); $day_after_tomorrow = DateHelper::formatDBDate(date('Y-m-d 00:00:00', time() + 2 * 24 * 60 * 60)); $query->where("((e.due_date >= '{$tomorrow}' AND e.due_date < '{$day_after_tomorrow}') OR (e.start_time >= '{$tomorrow}' AND e.start_time < '{$day_after_tomorrow}'))"); break; case "this_week": $date_info = getDate(strtotime($date)); $today = $date_info['wday']; $days_to_remove = -1 + $today; $days_to_add = 5 - $today; $beginning_of_week = DateHelper::formatDBDate(date('Y-m-d 00:00:00', strtotime($date . " - {$days_to_remove} days"))); $end_of_week = DateHelper::formatDBDate(date('Y-m-d 00:00:00', strtotime($date . " + {$days_to_add} days"))); $query->where("((e.due_date >= '{$beginning_of_week}' AND e.due_date < '{$end_of_week}') OR (e.start_time >= '{$beginning_of_week}' AND e.start_time < '{$end_of_week}'))"); break; case "past_due": $query->where("((e.due_date < '{$date}' AND e.due_date != '0000-00-00 00:00:00') OR (e.start_time < '{$date}' AND e.start_time != '0000-00-00 00:00:00'))"); break; case "not_past_due": $query->where("((e.due_date >= '{$date}' AND e.due_date != '0000-00-00 00:00:00') OR (e.start_time >= '{$date}' AND e.start_time != '0000-00-00 00:00:00'))"); break; } } /** Filter by assignee id **/ $assignee_id_filter = $this->getState('Event.' . $this->view . '_' . $this->layout . '_assignee_id'); $assignee_filter_type = $this->getState('Event.' . $this->view . '_' . $this->layout . '_assignee_filter_type'); if ($loc != "calendar" && $assignee_id_filter != null && $assignee_id_filter != 'all' && $this->view != "print") { if ($assignee_filter_type == "team") { $team_members = UsersHelper::getTeamUsers($assignee_id_filter, TRUE); $query->where("e.assignee_id IN(" . implode(',', $team_members) . ")"); } else { $query->where("e.assignee_id={$assignee_id_filter}"); } } /** Filter by association type **/ $association_type_filter = $this->getState('Event.' . $this->view . '_' . $this->layout . '_association_type'); if ($association_type_filter != null && $association_type_filter != "any" && !$association && $assignee_id_filter != 'all' && $this->view != "print") { $query->where("a.association_type='" . $association_type_filter . "'"); } $query->where("e.published=" . $this->published); if ($this->start_date) { $query->where("(e.due_date >= '" . $this->start_date . "' OR e.start_time >= '" . $this->start_date . "' OR e.repeats != 'none' )"); } if ($this->end_date) { $query->where("(e.due_date < '" . $this->end_date . "' OR e.end_time < '" . $this->end_date . "' OR e.repeats != 'none' )"); } if ($this->deal_id > 0) { $query->where("(a.association_id=" . $this->deal_id . " AND a.association_type='deal')"); } $this->filter_order = $this->getState('Event.' . $this->view . '_' . $this->layout . '_filter_order'); $this->filter_order_Dir = $this->getState('Event.' . $this->view . '_' . $this->layout . '_filter_order_Dir'); $query->order($this->filter_order . ' ' . $this->filter_order_Dir); /** ------------------------------------------ * Set query limits and load results */ if ($this->getState("Event." . $this->view . '_' . $this->layout . '_limit') != 0) { $query .= " LIMIT " . $this->getState("Event." . $this->view . '_' . $this->layout . '_limit') . " OFFSET " . $this->getState("Event." . $this->view . '_' . $this->layout . '_limitstart'); } return $query; }
public function execute() { //get post data $data = $this->getInput()->getArray(array('association_id' => 'int', 'association_type' => 'string', 'person_id' => 'int')); //get db Object $db = $this->container->fetch('db'); $query = $db->getQuery(true); $table = $this->getInput()->getCmd('table'); $loc = $this->getInput()->getCmd('loc'); unset($data['table']); unset($data['loc']); if (empty($data['person_id'])) { unset($data['person_id']); } //write to tables if there is no association already in cf tables $query->select('* FROM #__' . $table . '_cf'); //loop to see if we have matches in database $overrides = array('tmpl'); foreach ($data as $key => $value) { if (!in_array($key, $overrides)) { $query->where($key . " = '" . $value . "'"); } } $db->setQuery($query); $results = $db->loadAssocList(); $response = new \stdClass(); //determine if we found any results if (count($results) == 0) { $query->insert('#__' . $table . '_cf'); //timestamp $data['created'] = date('Y-m-d H:i:s'); $date = DateHelper::formatDBDate(date('Y-m-d H:i:s')); //loop through data to get query string foreach ($data as $key => $value) { if (!in_array($key, $overrides)) { // determine key and key values $query->set($key . " = '" . $value . "'"); } } $db->setQuery($query)->execute(); //if return data requested if ($table == 'people') { //determine which page we want are wanting to send information back to if ($loc == 'deal') { $model = new PeopleModel(); $return = $model->getPerson($data['person_id']); $response->alert = new \stdClass(); $response->alert->message = \JText::_('DEAL_CONTACT_ADDED_SUCCESS'); $response->alert->type = 'success'; $response->item = $return; $response->reload = 2000; } if ($loc == 'person') { $model = new DealModel(); $return = $model->getDeals(array_key_exists('deal_id', $data) ? $data['deal_id'] : ""); $return = $return[0]; $response->alert = new \stdClass(); $response->alert->message = $return; $response->alert->type = 'success'; } } } else { $response->alert = new \stdClass(); $response->alert->message = \JText::_('DEAL_CONTACT_ERROR_FAILURE_ADD_PERSON'); $response->alert->type = 'error'; } //return json data echo json_encode($response); }