function setUserDate($user_id, $date)
 {
     $user_date_id = UserDateFactory::findOrInsertUserDate($user_id, $date);
     Debug::text(' User Date ID: ' . $user_date_id, __FILE__, __LINE__, __METHOD__, 10);
     if ($user_date_id != '') {
         $this->setUserDateID($user_date_id);
         return TRUE;
     }
     Debug::text(' No User Date ID found', __FILE__, __LINE__, __METHOD__, 10);
     return FALSE;
 }
    function getAPISearchByCompanyIdAndArrayCriteria($company_id, $filter_data, $limit = NULL, $page = NULL, $where = NULL, $order = NULL)
    {
        if ($company_id == '') {
            return FALSE;
        }
        if (!is_array($order)) {
            //Use Filter Data ordering if its set.
            if (isset($filter_data['sort_column']) and $filter_data['sort_order']) {
                $order = array(Misc::trimSortPrefix($filter_data['sort_column']) => $filter_data['sort_order']);
            }
        }
        //$additional_order_fields = array('b.name', 'c.name', 'd.name', 'e.name');
        $additional_order_fields = array('first_name', 'last_name', 'date_stamp', 'time_stamp', 'type_id', 'status_id', 'branch', 'department', 'default_branch', 'default_department', 'group', 'title');
        if ($order == NULL) {
            $order = array('c.pay_period_id' => 'asc', 'c.user_id' => 'asc');
            $strict = FALSE;
        } else {
            $strict = FALSE;
        }
        //Debug::Arr($order,'Order Data:', __FILE__, __LINE__, __METHOD__,10);
        //Debug::Arr($filter_data,'Filter Data:', __FILE__, __LINE__, __METHOD__,10);
        if (isset($filter_data['exclude_user_ids'])) {
            $filter_data['exclude_id'] = $filter_data['exclude_user_ids'];
        }
        if (isset($filter_data['user_id'])) {
            $filter_data['id'] = $filter_data['user_id'];
        }
        if (isset($filter_data['include_user_ids'])) {
            $filter_data['id'] = $filter_data['include_user_ids'];
        }
        if (isset($filter_data['user_status_ids'])) {
            $filter_data['status_id'] = $filter_data['user_status_ids'];
        }
        if (isset($filter_data['user_title_ids'])) {
            $filter_data['title_id'] = $filter_data['user_title_ids'];
        }
        if (isset($filter_data['group_ids'])) {
            $filter_data['group_id'] = $filter_data['group_ids'];
        }
        if (isset($filter_data['branch_ids'])) {
            $filter_data['default_branch_id'] = $filter_data['branch_ids'];
        }
        if (isset($filter_data['department_ids'])) {
            $filter_data['default_department_id'] = $filter_data['department_ids'];
        }
        if (isset($filter_data['punch_branch_ids'])) {
            $filter_data['punch_branch_id'] = $filter_data['punch_branch_ids'];
        }
        if (isset($filter_data['punch_department_ids'])) {
            $filter_data['punch_department_id'] = $filter_data['punch_department_ids'];
        }
        if (isset($filter_data['exclude_job_ids'])) {
            $filter_data['exclude_id'] = $filter_data['exclude_job_ids'];
        }
        if (isset($filter_data['include_job_ids'])) {
            $filter_data['include_job_id'] = $filter_data['include_job_ids'];
        }
        if (isset($filter_data['job_group_ids'])) {
            $filter_data['job_group_id'] = $filter_data['job_group_ids'];
        }
        if (isset($filter_data['job_item_ids'])) {
            $filter_data['job_item_id'] = $filter_data['job_item_ids'];
        }
        $uf = new UserFactory();
        $udf = new UserDateFactory();
        $pcf = new PunchControlFactory();
        $uwf = new UserWageFactory();
        $bf = new BranchFactory();
        $df = new DepartmentFactory();
        $ugf = new UserGroupFactory();
        $utf = new UserTitleFactory();
        if (getTTProductEdition() >= TT_PRODUCT_CORPORATE) {
            $jf = new JobFactory();
            $jif = new JobItemFactory();
        }
        $ph = array('company_id' => $company_id);
        $query = '
					select
							b.id as id,
							b.user_date_id as user_date_id,
							b.branch_id as branch_id,
							j.name as branch,
							b.department_id as department_id,
							k.name as department,
							b.job_id as job_id,
							x.name as job,
							b.job_item_id as job_item_id,
							y.name as job_item,
							b.quantity as quantity,
							b.bad_quantity as bad_quantity,
							b.total_time as total_time,
							b.actual_total_time as actual_total_time,
							b.meal_policy_id as meal_policy_id,
							b.other_id1 as other_id1,
							b.other_id2 as other_id2,
							b.other_id3 as other_id3,
							b.other_id4 as other_id4,
							b.other_id5 as other_id5,
							b.note as note,

							c.user_id as user_id,
							c.date_stamp as date_stamp,
							c.pay_period_id as pay_period_id,

							d.first_name as first_name,
							d.last_name as last_name,
							d.status_id as user_status_id,
							d.group_id as group_id,
							g.name as "group",
							d.title_id as title_id,
							h.name as title,
							d.default_branch_id as default_branch_id,
							e.name as default_branch,
							d.default_department_id as default_department_id,
							f.name as default_department,
							d.created_by as user_created_by,

							z.id as user_wage_id,
							z.effective_date as user_wage_effective_date ';
        if (getTTProductEdition() >= TT_PRODUCT_CORPORATE) {
            $query .= ',
						x.name as job_name,
						x.status_id as job_status_id,
						x.manual_id as job_manual_id,
						x.branch_id as job_branch_id,
						x.department_id as job_department_id,
						x.group_id as job_group_id';
        }
        $query .= '
					from 	' . $this->getTable() . ' as b
							LEFT JOIN ' . $udf->getTable() . ' as c ON b.user_date_id = c.id
							LEFT JOIN ' . $uf->getTable() . ' as d ON c.user_id = d.id

							LEFT JOIN ' . $bf->getTable() . ' as e ON ( d.default_branch_id = e.id AND e.deleted = 0)
							LEFT JOIN ' . $df->getTable() . ' as f ON ( d.default_department_id = f.id AND f.deleted = 0)
							LEFT JOIN ' . $ugf->getTable() . ' as g ON ( d.group_id = g.id AND g.deleted = 0 )
							LEFT JOIN ' . $utf->getTable() . ' as h ON ( d.title_id = h.id AND h.deleted = 0 )

							LEFT JOIN ' . $bf->getTable() . ' as j ON ( b.branch_id = j.id AND j.deleted = 0)
							LEFT JOIN ' . $df->getTable() . ' as k ON ( b.department_id = k.id AND k.deleted = 0)

							LEFT JOIN ' . $uwf->getTable() . ' as z ON z.id = (select z.id
																		from ' . $uwf->getTable() . ' as z
																		where z.user_id = c.user_id
																			and z.effective_date <= c.date_stamp
																			and z.deleted = 0
																			order by z.effective_date desc LiMiT 1)
					';
        if (getTTProductEdition() >= TT_PRODUCT_CORPORATE) {
            $query .= '	LEFT JOIN ' . $jf->getTable() . ' as x ON b.job_id = x.id';
            $query .= '	LEFT JOIN ' . $jif->getTable() . ' as y ON b.job_item_id = y.id';
        }
        $query .= '	WHERE d.company_id = ?';
        if (isset($filter_data['permission_children_ids']) and isset($filter_data['permission_children_ids'][0]) and !in_array(-1, (array) $filter_data['permission_children_ids'])) {
            $query .= ' AND d.id in (' . $this->getListSQL($filter_data['permission_children_ids'], $ph) . ') ';
        }
        if (isset($filter_data['id']) and isset($filter_data['id'][0]) and !in_array(-1, (array) $filter_data['id'])) {
            $query .= ' AND b.id in (' . $this->getListSQL($filter_data['id'], $ph) . ') ';
        }
        if (isset($filter_data['exclude_id']) and isset($filter_data['exclude_id'][0]) and !in_array(-1, (array) $filter_data['exclude_id'])) {
            $query .= ' AND d.id not in (' . $this->getListSQL($filter_data['exclude_id'], $ph) . ') ';
        }
        if (isset($filter_data['user_id']) and isset($filter_data['user_id'][0]) and !in_array(-1, (array) $filter_data['user_id'])) {
            $query .= ' AND c.user_id in (' . $this->getListSQL($filter_data['user_id'], $ph) . ') ';
        }
        if (isset($filter_data['status_id']) and isset($filter_data['status_id'][0]) and !in_array(-1, (array) $filter_data['status_id'])) {
            $query .= ' AND d.status_id in (' . $this->getListSQL($filter_data['status_id'], $ph) . ') ';
        }
        if (isset($filter_data['group_id']) and isset($filter_data['group_id'][0]) and !in_array(-1, (array) $filter_data['group_id'])) {
            if (isset($filter_data['include_subgroups']) and (bool) $filter_data['include_subgroups'] == TRUE) {
                $uglf = new UserGroupListFactory();
                $filter_data['group_id'] = $uglf->getByCompanyIdAndGroupIdAndSubGroupsArray($company_id, $filter_data['group_id'], TRUE);
            }
            $query .= ' AND d.group_id in (' . $this->getListSQL($filter_data['group_id'], $ph) . ') ';
        }
        if (isset($filter_data['default_branch_id']) and isset($filter_data['default_branch_id'][0]) and !in_array(-1, (array) $filter_data['default_branch_id'])) {
            $query .= ' AND d.default_branch_id in (' . $this->getListSQL($filter_data['default_branch_id'], $ph) . ') ';
        }
        if (isset($filter_data['default_department_id']) and isset($filter_data['default_department_id'][0]) and !in_array(-1, (array) $filter_data['default_department_id'])) {
            $query .= ' AND d.default_department_id in (' . $this->getListSQL($filter_data['default_department_id'], $ph) . ') ';
        }
        if (isset($filter_data['title_id']) and isset($filter_data['title_id'][0]) and !in_array(-1, (array) $filter_data['title_id'])) {
            $query .= ' AND d.title_id in (' . $this->getListSQL($filter_data['title_id'], $ph) . ') ';
        }
        if (isset($filter_data['punch_branch_id']) and isset($filter_data['punch_branch_id'][0]) and !in_array(-1, (array) $filter_data['punch_branch_id'])) {
            $query .= ' AND b.branch_id in (' . $this->getListSQL($filter_data['punch_branch_id'], $ph) . ') ';
        }
        if (isset($filter_data['punch_department_id']) and isset($filter_data['punch_department_id'][0]) and !in_array(-1, (array) $filter_data['punch_department_id'])) {
            $query .= ' AND b.department_id in (' . $this->getListSQL($filter_data['punch_department_id'], $ph) . ') ';
        }
        if (isset($filter_data['pay_period_ids']) and isset($filter_data['pay_period_ids'][0]) and !in_array(-1, (array) $filter_data['pay_period_ids'])) {
            $query .= ' AND c.pay_period_id in (' . $this->getListSQL($filter_data['pay_period_ids'], $ph) . ') ';
        }
        //Use the job_id in the punch_control table so we can filter by '0' or No Job
        if (isset($filter_data['include_job_id']) and isset($filter_data['include_job_id'][0]) and !in_array(-1, (array) $filter_data['include_job_id'])) {
            $query .= ' AND b.job_id in (' . $this->getListSQL($filter_data['include_job_id'], $ph) . ') ';
        }
        if (isset($filter_data['exclude_job_id']) and isset($filter_data['exclude_job_id'][0]) and !in_array(-1, (array) $filter_data['exclude_job_id'])) {
            $query .= ' AND b.job_id not in (' . $this->getListSQL($filter_data['exclude_job_id'], $ph) . ') ';
        }
        if (isset($filter_data['job_group_id']) and isset($filter_data['job_group_id'][0]) and !in_array(-1, (array) $filter_data['job_group_id'])) {
            if (isset($filter_data['include_job_subgroups']) and (bool) $filter_data['include_job_subgroups'] == TRUE) {
                $uglf = new UserGroupListFactory();
                $filter_data['job_group_id'] = $uglf->getByCompanyIdAndGroupIdAndjob_subgroupsArray($company_id, $filter_data['job_group_id'], TRUE);
            }
            $query .= ' AND x.group_id in (' . $this->getListSQL($filter_data['job_group_id'], $ph) . ') ';
        }
        if (isset($filter_data['job_item_id']) and isset($filter_data['job_item_id'][0]) and !in_array(-1, (array) $filter_data['job_item_id'])) {
            $query .= ' AND b.job_item_id in (' . $this->getListSQL($filter_data['job_item_id'], $ph) . ') ';
        }
        if (isset($filter_data['start_date']) and trim($filter_data['start_date']) != '') {
            $ph[] = $this->db->BindDate($filter_data['start_date']);
            $query .= ' AND c.date_stamp >= ?';
        }
        if (isset($filter_data['end_date']) and trim($filter_data['end_date']) != '') {
            $ph[] = $this->db->BindDate($filter_data['end_date']);
            $query .= ' AND c.date_stamp <= ?';
        }
        $query .= '
						AND ( b.deleted = 0 AND c.deleted = 0 AND d.deleted = 0 )
					';
        $query .= $this->getWhereSQL($where);
        $query .= $this->getSortSQL($order, $strict, $additional_order_fields);
        $this->ExecuteSQL($query, $ph, $limit, $page);
        return $this;
    }
    function getAPISearchByCompanyIdAndArrayCriteria($company_id, $filter_data, $limit = NULL, $page = NULL, $where = NULL, $order = NULL)
    {
        if ($company_id == '') {
            return FALSE;
        }
        if (!is_array($order)) {
            //Use Filter Data ordering if its set.
            if (isset($filter_data['sort_column']) and $filter_data['sort_order']) {
                $order = array(Misc::trimSortPrefix($filter_data['sort_column']) => $filter_data['sort_order']);
            }
        }
        $additional_order_fields = array('date_stamp', 'user_status_id', 'last_name', 'first_name', 'default_branch', 'default_department', 'user_group', 'title');
        $sort_column_aliases = array('status' => 'status_id', 'type' => 'type_id');
        $order = $this->getColumnsFromAliases($order, $sort_column_aliases);
        if ($order == NULL) {
            $order = array('status_id' => 'asc', 'type_id' => 'asc', 'date_stamp' => 'desc');
            $strict = FALSE;
        } else {
            //Always sort by last name,first name after other columns
            /*
            if ( !isset($order['effective_date']) ) {
            	$order['effective_date'] = 'desc';
            }
            */
            $strict = TRUE;
        }
        //Debug::Arr($order,'Order Data:', __FILE__, __LINE__, __METHOD__,10);
        //Debug::Arr($filter_data,'Filter Data:', __FILE__, __LINE__, __METHOD__,10);
        $uf = new UserFactory();
        $bf = new BranchFactory();
        $df = new DepartmentFactory();
        $ugf = new UserGroupFactory();
        $utf = new UserTitleFactory();
        $udf = new UserDateFactory();
        $huf = new HierarchyUserFactory();
        $ph = array('company_id' => $company_id);
        //Need to make this return DISTINCT records only, because if the same child is assigned to multiple hierarchies,
        //the join to table HUF will force it to return one row for each hierarchy they are a child of. This prevents that.
        $query = '
					select 	DISTINCT
							a.*,
							b.first_name as first_name,
							b.last_name as last_name,
							b.country as country,
							b.province as province,

							udf.date_stamp as date_stamp,
							udf.user_id as user_id,

							c.id as default_branch_id,
							c.name as default_branch,
							d.id as default_department_id,
							d.name as default_department,
							e.id as user_group_id,
							e.name as user_group,
							f.id as title_id,
							f.name as title
					from 	' . $this->getTable() . ' as a
						LEFT JOIN ' . $udf->getTable() . ' as udf ON ( a.user_date_id = udf.id AND udf.deleted = 0 )
						LEFT JOIN ' . $uf->getTable() . ' as b ON ( udf.user_id = b.id AND b.deleted = 0 )

						LEFT JOIN ' . $huf->getTable() . ' as huf ON ( udf.user_id = huf.user_id )

						LEFT JOIN ' . $bf->getTable() . ' as c ON ( b.default_branch_id = c.id AND c.deleted = 0)
						LEFT JOIN ' . $df->getTable() . ' as d ON ( b.default_department_id = d.id AND d.deleted = 0)
						LEFT JOIN ' . $ugf->getTable() . ' as e ON ( b.group_id = e.id AND e.deleted = 0 )
						LEFT JOIN ' . $utf->getTable() . ' as f ON ( b.title_id = f.id AND f.deleted = 0 )

					where	b.company_id = ?
					';
        if (isset($filter_data['permission_children_ids']) and isset($filter_data['permission_children_ids'][0]) and !in_array(-1, (array) $filter_data['permission_children_ids'])) {
            $query .= ' AND udf.user_id in (' . $this->getListSQL($filter_data['permission_children_ids'], $ph) . ') ';
        }
        if (isset($filter_data['user_id']) and isset($filter_data['user_id'][0]) and !in_array(-1, (array) $filter_data['user_id'])) {
            $query .= ' AND udf.user_id in (' . $this->getListSQL($filter_data['user_id'], $ph) . ') ';
        }
        if (isset($filter_data['id']) and isset($filter_data['id'][0]) and !in_array(-1, (array) $filter_data['id'])) {
            $query .= ' AND a.id in (' . $this->getListSQL($filter_data['id'], $ph) . ') ';
        }
        if (isset($filter_data['exclude_id']) and isset($filter_data['exclude_id'][0]) and !in_array(-1, (array) $filter_data['exclude_id'])) {
            $query .= ' AND udf.user_id not in (' . $this->getListSQL($filter_data['exclude_id'], $ph) . ') ';
        }
        if (isset($filter_data['type_id']) and isset($filter_data['type_id'][0]) and !in_array(-1, (array) $filter_data['type_id'])) {
            $query .= ' AND a.type_id in (' . $this->getListSQL($filter_data['type_id'], $ph) . ') ';
        }
        if (isset($filter_data['status_id']) and isset($filter_data['status_id'][0]) and !in_array(-1, (array) $filter_data['status_id'])) {
            $query .= ' AND a.status_id in (' . $this->getListSQL($filter_data['status_id'], $ph) . ') ';
        }
        if (isset($filter_data['group_id']) and isset($filter_data['group_id'][0]) and !in_array(-1, (array) $filter_data['group_id'])) {
            if (isset($filter_data['include_subgroups']) and (bool) $filter_data['include_subgroups'] == TRUE) {
                $uglf = new UserGroupListFactory();
                $filter_data['group_id'] = $uglf->getByCompanyIdAndGroupIdAndSubGroupsArray($company_id, $filter_data['group_id'], TRUE);
            }
            $query .= ' AND b.group_id in (' . $this->getListSQL($filter_data['group_id'], $ph) . ') ';
        }
        if (isset($filter_data['default_branch_id']) and isset($filter_data['default_branch_id'][0]) and !in_array(-1, (array) $filter_data['default_branch_id'])) {
            $query .= ' AND b.default_branch_id in (' . $this->getListSQL($filter_data['default_branch_id'], $ph) . ') ';
        }
        if (isset($filter_data['default_department_id']) and isset($filter_data['default_department_id'][0]) and !in_array(-1, (array) $filter_data['default_department_id'])) {
            $query .= ' AND b.default_department_id in (' . $this->getListSQL($filter_data['default_department_id'], $ph) . ') ';
        }
        if (isset($filter_data['title_id']) and isset($filter_data['title_id'][0]) and !in_array(-1, (array) $filter_data['title_id'])) {
            $query .= ' AND b.title_id in (' . $this->getListSQL($filter_data['title_id'], $ph) . ') ';
        }
        if (isset($filter_data['country']) and isset($filter_data['country'][0]) and !in_array(-1, (array) $filter_data['country'])) {
            $query .= ' AND b.country in (' . $this->getListSQL($filter_data['country'], $ph) . ') ';
        }
        if (isset($filter_data['province']) and isset($filter_data['province'][0]) and !in_array(-1, (array) $filter_data['province']) and !in_array('00', (array) $filter_data['province'])) {
            $query .= ' AND b.province in (' . $this->getListSQL($filter_data['province'], $ph) . ') ';
        }
        //Handle authorize list criteria here.
        if (isset($filter_data['authorized']) and isset($filter_data['authorized'][0]) and !in_array(-1, (array) $filter_data['authorized'])) {
            $query .= ' AND a.authorized in (' . $this->getListSQL($filter_data['authorized'], $ph) . ') ';
        }
        if (isset($filter_data['hierarchy_level_map']) and is_array($filter_data['hierarchy_level_map'])) {
            $query .= ' AND  huf.id IS NOT NULL ';
            //Make sure the user maps to a hierarchy.
            $query .= ' AND ( ' . HierarchyLevelFactory::convertHierarchyLevelMapToSQL($filter_data['hierarchy_level_map'], 'a.', 'huf.', 'a.type_id') . ' )';
        } elseif (isset($filter_data['hierarchy_level_map']) and $filter_data['hierarchy_level_map'] == FALSE) {
            //If hierarchy_level_map is not an array, don't return any requests.
            $query .= ' AND  huf.id = -1 ';
            //Make sure the user maps to a hierarchy.
        }
        if (isset($filter_data['start_date']) and trim($filter_data['start_date']) != '') {
            $ph[] = $this->db->BindDate(TTDate::parseDateTime($filter_data['start_date']));
            $query .= ' AND udf.date_stamp >= ?';
        }
        if (isset($filter_data['end_date']) and trim($filter_data['end_date']) != '') {
            $ph[] = $this->db->BindDate(TTDate::parseDateTime($filter_data['end_date']));
            $query .= ' AND udf.date_stamp <= ?';
        }
        $query .= isset($filter_data['created_by']) ? $this->getWhereClauseSQL(array('a.created_by', 'y.first_name', 'y.last_name'), $filter_data['created_by'], 'user_id_or_name', $ph) : NULL;
        $query .= isset($filter_data['updated_by']) ? $this->getWhereClauseSQL(array('a.updated_by', 'z.first_name', 'z.last_name'), $filter_data['updated_by'], 'user_id_or_name', $ph) : NULL;
        $query .= '
						AND a.deleted = 0
					';
        $query .= $this->getWhereSQL($where);
        $query .= $this->getSortSQL($order, $strict, $additional_order_fields);
        //Debug::Arr($ph,'Query: '. $query, __FILE__, __LINE__, __METHOD__,10);
        $this->ExecuteSQL($query, $ph, $limit, $page);
        return $this;
    }
 function postSave()
 {
     $this->removeCache($this->getId());
     if ($this->getDeleted() == TRUE) {
         Debug::text('Delete TRUE: ', __FILE__, __LINE__, __METHOD__, 10);
         //Unassign user_date rows from this pay period, no need to delete this data anymore as it can be easily done otherways and users don't realize
         //how much data will actually be deleted.
         $udf = new UserDateFactory();
         $query = 'update ' . $udf->getTable() . ' set pay_period_id = 0 where pay_period_id = ' . $this->getId();
         $this->db->Execute($query);
     } else {
         if ($this->getStatus() == 20) {
             //Closed
             //Mark pay stubs as PAID once the pay period is closed?
             TTLog::addEntry($this->getId(), 'Edit', TTi18n::getText('Setting Pay Period to Closed'), NULL, $this->getTable());
             $this->setPayStubStatus(40);
         } elseif ($this->getStatus() == 30) {
             TTLog::addEntry($this->getId(), 'Edit', TTi18n::getText('Setting Pay Period to Post-Adjustment'), NULL, $this->getTable());
         }
         if ($this->getEnableImportData() == TRUE) {
             $this->importData();
         }
     }
     $this->CommitTransaction();
     return TRUE;
 }
 function postSave()
 {
     if ($this->getEnableTimeSheetVerificationCheck()) {
         //Check to see if schedule is verified, if so unverify it on modified punch.
         //Make sure exceptions are calculated *after* this so TimeSheet Not Verified exceptions can be triggered again.
         if (is_object($this->getUserDateObject()) and is_object($this->getUserDateObject()->getPayPeriodObject()) and is_object($this->getUserDateObject()->getPayPeriodObject()->getPayPeriodScheduleObject()) and $this->getUserDateObject()->getPayPeriodObject()->getPayPeriodScheduleObject()->getTimeSheetVerifyType() != 10) {
             //Find out if timesheet is verified or not.
             $pptsvlf = TTnew('PayPeriodTimeSheetVerifyListFactory');
             $pptsvlf->getByPayPeriodIdAndUserId($this->getUserDateObject()->getPayPeriod(), $this->getUserDateObject()->getUser());
             if ($pptsvlf->getRecordCount() > 0) {
                 //Pay period is verified, delete all records and make log entry.
                 //These can be added during the maintenance jobs, so the audit records are recorded as user_id=0, check those first.
                 Debug::text('Pay Period is verified, deleting verification records: ' . $pptsvlf->getRecordCount() . ' User ID: ' . $this->getUserDateObject()->getUser() . ' Pay Period ID: ' . $this->getUserDateObject()->getPayPeriod(), __FILE__, __LINE__, __METHOD__, 10);
                 foreach ($pptsvlf as $pptsv_obj) {
                     TTLog::addEntry($pptsv_obj->getId(), 500, TTi18n::getText('Schedule Modified After Verification') . ': ' . UserListFactory::getFullNameById($this->getUserDateObject()->getUser()) . ' ' . TTi18n::getText('Schedule') . ': ' . TTDate::getDate('DATE', $this->getStartTime()), NULL, $pptsvlf->getTable());
                     $pptsv_obj->setDeleted(TRUE);
                     if ($pptsv_obj->isValid()) {
                         $pptsv_obj->Save();
                     }
                 }
             }
         }
     }
     if ($this->getEnableReCalculateDay() == TRUE) {
         //Calculate total time. Mainly for docked.
         //Calculate entire week as Over Schedule (Weekly) OT policy needs to be reapplied if the schedule changes.
         if (is_object($this->getUserDateObject()) and $this->getUserDateObject()->getUser() > 0) {
             //When shifts are assigned to different days, we need to calculate both days the schedule touches, as the shift could be assigned to either of them.
             UserDateTotalFactory::smartReCalculate($this->getUserDateObject()->getUser(), array($this->getUserDateID(), $this->getOldUserDateID(), UserDateFactory::findOrInsertUserDate($this->getUserDateObject()->getUser(), $this->getStartTime()), UserDateFactory::findOrInsertUserDate($this->getUserDateObject()->getUser(), $this->getEndTime())), TRUE, FALSE);
         }
     }
     return TRUE;
 }
    function getOrphansByUserId($user_id, $where = NULL, $order = NULL)
    {
        if ($user_id == '') {
            return FALSE;
        }
        $apf = new AccrualPolicyFactory();
        $udtf = new UserDateTotalFactory();
        $udf = new UserDateFactory();
        $ph = array('user_id' => $user_id);
        //Make sure we check if user_date rows are deleted where user_date_total rows are not.
        $query = '
					select 	a.*
					from	' . $this->getTable() . ' as a
					LEFT JOIN ' . $udtf->getTable() . ' as b ON a.user_date_total_id = b.id
					LEFT JOIN ' . $udf->getTable() . ' as c ON b.user_date_id = c.id
					LEFT JOIN ' . $apf->getTable() . ' as d ON a.accrual_policy_id = d.id
					where	a.user_id = ?
						AND (
								( b.id is NULL OR b.deleted = 1 )
								OR
								( b.deleted = 0 AND ( c.id is NULL OR c.deleted = 1) )
							)
						AND ( a.type_id = 10 OR a.type_id = 20 OR ( a.type_id = 75 AND d.type_id = 30 ) )
						AND a.deleted = 0';
        $query .= $this->getWhereSQL($where);
        $query .= $this->getSortSQL($order);
        $this->rs = $this->db->Execute($query, $ph);
        return $this;
    }
    function getReportHoursByTimePeriodAndUserIdAndCompanyIdAndStartDateAndEndDate($time_period, $user_ids, $company_id, $start_date, $end_date, $where = NULL, $order = NULL)
    {
        if ($time_period == '') {
            return FALSE;
        }
        if ($user_ids == '') {
            return FALSE;
        }
        if ($company_id == '') {
            return FALSE;
        }
        if ($start_date == '') {
            return FALSE;
        }
        if ($end_date == '') {
            return FALSE;
        }
        /*
        if ( $order == NULL ) {
        	$order = array( 'date_stamp' => 'asc' );
        	$strict = FALSE;
        } else {
        	$strict = TRUE;
        }
        */
        $uf = new UserFactory();
        $udf = new UserDateFactory();
        $ph = array('company_id' => $company_id, 'start_date' => $this->db->BindDate($start_date), 'end_date' => $this->db->BindDate($end_date));
        $query = '
					select 	user_id,
							status_id,
							type_id,
							over_time_policy_id,
							absence_policy_id,
							premium_policy_id,
							avg(total_time) as avg,
							min(total_time) as min,
							max(total_time) as max,
							count(*) as date_units
					from (
							select 	b.user_id,
									(EXTRACT(' . $time_period . ' FROM b.date_stamp) || \'-\' || EXTRACT(month FROM b.date_stamp) || \'-\' || EXTRACT(year FROM b.date_stamp) ) as date,
									a.type_id,
									a.status_id,
									over_time_policy_id,
									absence_policy_id,
									premium_policy_id,
									sum(total_time) as total_time
							from	' . $this->getTable() . ' as a,
									' . $udf->getTable() . ' as b,
									' . $uf->getTable() . ' as c
							where 	a.user_date_id = b.id
								AND b.user_id = c.id
								AND c.company_id = ?
								AND b.date_stamp >= ?
								AND b.date_stamp <= ?
								AND b.user_id in (' . $this->getListSQL($user_ids, $ph) . ')
								AND a.total_time > 0
								AND ( a.deleted = 0 AND b.deleted=0 AND c.deleted=0)
							GROUP BY user_id,(EXTRACT(' . $time_period . ' FROM b.date_stamp) || \'-\' || EXTRACT(month FROM b.date_stamp) || \'-\' || EXTRACT(year FROM b.date_stamp) ),a.status_id,a.type_id,over_time_policy_id,absence_policy_id,premium_policy_id
						) tmp
					GROUP BY user_id,status_id,type_id,over_time_policy_id,absence_policy_id,premium_policy_id
					';
        /*
        		$query = '
        					select 	user_id,
        							status_id,
        							type_id,
        							over_time_policy_id,
        							absence_policy_id,
        							premium_policy_id,
        							avg(total_time) as avg,
        							min(total_time) as min,
        							max(total_time) as max,
        							count(*) as date_units
        					from (
        
        						select 	b.user_id,
        								(date_part(\''.$time_period.'\', b.date_stamp) || \'-\' || date_part(\'month\', b.date_stamp) || \'-\' || date_part(\'year\', b.date_stamp) ) as date,
        								a.type_id,
        								a.status_id,
        								over_time_policy_id,
        								absence_policy_id,
        								premium_policy_id,
        								sum(total_time) as total_time
        						from	'. $this->getTable() .' as a,
        								'. $udf->getTable() .' as b,
        								'. $uf->getTable() .' as c
        						where 	a.user_date_id = b.id
        							AND b.user_id = c.id
        							AND c.company_id = ?
        							AND b.date_stamp >= ?
        							AND b.date_stamp <= ?
        							AND b.user_id in ('. $this->getListSQL($user_ids, $ph) .')
        							AND a.total_time > 0
        							AND ( a.deleted = 0 AND b.deleted=0 AND c.deleted=0)
        							GROUP BY user_id,(date_part(\''. $time_period.'\', b.date_stamp) || \'-\' || date_part(\'month\', b.date_stamp) || \'-\' || date_part(\'year\', b.date_stamp) ),a.status_id,a.type_id,over_time_policy_id,absence_policy_id,premium_policy_id
        						) tmp
        					GROUP BY user_id,status_id,type_id,over_time_policy_id,absence_policy_id,premium_policy_id
        					';
        */
        //$query .= $this->getWhereSQL( $where );
        //$query .= $this->getSortSQL( $order );
        $this->rs = $this->db->Execute($query, $ph);
        return $this;
    }
             foreach ($udtlf as $udt_obj) {
                 $udt_obj->setDeleted($delete);
                 if ($id_count == $i) {
                     $udt_obj->setEnableCalcSystemTotalTime(TRUE);
                 }
                 $udt_obj->Save();
             }
             $i++;
         }
     }
     Redirect::Page(URLBuilder::getURL(array('user_id' => $user_id, 'filter_date' => $filter_date), 'UserDateTotalList.php'));
     break;
 default:
     if ((!isset($user_date_id) or isset($user_date_id) and $user_date_id == '') and $user_id != '' and $filter_date != '') {
         Debug::Text('User Date ID not passed, inserting one.', __FILE__, __LINE__, __METHOD__, 10);
         $user_date_id = UserDateFactory::findOrInsertUserDate($user_id, $filter_date);
     }
     if ($user_date_id != '') {
         $udtlf = new UserDateTotalListFactory();
         $udtlf->getByUserDateIDAndStatusAndType($user_date_id, array(10, 20, 30), array(10, 20, 30, 40, 100), $current_user_prefs->getItemsPerPage(), $page, NULL, $sort_array);
         $pager = new Pager($udtlf);
         $blf = new BranchListFactory();
         $branch_options = $blf->getByCompanyIdArray($current_company->getId());
         $dlf = new DepartmentListFactory();
         $department_options = $dlf->getByCompanyIdArray($current_company->getId());
         //Absence policies
         $otplf = new AbsencePolicyListFactory();
         $absence_policy_options = $otplf->getByCompanyIDArray($current_company->getId(), TRUE);
         //Overtime policies
         $otplf = new OverTimePolicyListFactory();
         $over_time_policy_options = $otplf->getByCompanyIDArray($current_company->getId(), TRUE);
    function getPayPeriodReportByUserIdAndEntryNameIdAndStartDateAndEndDate($id, $entry_name_id, $start_date = NULL, $end_date = NULL, $exclude_id = NULL, $where = NULL, $order = NULL)
    {
        if ($id == '') {
            return FALSE;
        }
        if ($entry_name_id == '') {
            return FALSE;
        }
        if ($start_date == '') {
            $start_date = 0;
        }
        if ($end_date == '') {
            $end_date = TTDate::getTime();
        }
        $ppf = new PayPeriodFactory();
        $ppsuf = new PayPeriodScheduleUserFactory();
        $psf = new PayStubFactory();
        $uf = new UserFactory();
        $udf = new UserDateFactory();
        $ph = array('start_date' => $this->db->BindTimeStamp($start_date), 'end_date' => $this->db->BindTimeStamp($end_date), 'user_id' => $id, 'exclude_id' => (int) $exclude_id);
        //Include pay periods with no pay stubs for ROEs.
        //If the company has multiple pay period schedules, this will include pay periods from all schedules, even if the employee was never assigned
        //to a different one. Therefore only include pay periods that have at least one user_date entry assigned to it.
        $query = '
					select 	x.id as pay_period_id,
							y.id as user_id,
							x.start_date as pay_period_start_date,
							x.end_date as pay_period_end_date,
							x.transaction_date as pay_period_transaction_date,
							tmp.amount as amount,
							tmp.units as units
					from 	' . $ppf->getTable() . ' x
						LEFT JOIN ' . $uf->getTable() . ' as y ON x.company_id = y.company_id
						LEFT JOIN 	(
										select 	b.user_id as user_id,
												b.pay_period_id as pay_period_id,
												sum(amount) as amount,
												sum(units) as units
										from	' . $this->getTable() . ' as a,
												' . $psf->getTable() . ' as b,
												' . $ppf->getTable() . ' as c
										where	a.pay_stub_id = b.id
											AND b.pay_period_id = c.id
											AND c.start_date >= ?
											AND c.start_date < ?
											AND b.user_id = ?
											AND a.id != ?
											AND	a.pay_stub_entry_name_id in (' . $this->getListSQL($entry_name_id, $ph) . ')
											AND ( a.deleted = 0 AND b.deleted = 0 AND c.deleted = 0 )
										group by b.user_id,b.pay_period_id
									) as tmp ON y.id = tmp.user_id AND x.id = tmp.pay_period_id ';
        $ph[] = $id;
        $ph[] = $this->db->BindTimeStamp($start_date);
        $ph[] = $this->db->BindTimeStamp($end_date);
        $query .= '
					where y.id = ?
						AND x.start_date >= ?
						AND x.start_date < ?
						AND EXISTS (select 1 from ' . $udf->getTable() . ' as ud WHERE x.id = ud.pay_period_id AND y.id = ud.user_id )
						AND x.deleted = 0
				';
        $query .= $this->getWhereSQL($where);
        $query .= $this->getSortSQL($order, FALSE);
        $this->ExecuteSQL($query, $ph);
        return $this;
    }
    function getSearchByCompanyIdAndArrayCriteria($company_id, $filter_data, $limit = NULL, $page = NULL, $where = NULL, $order = NULL)
    {
        if ($company_id == '') {
            return FALSE;
        }
        if (!is_array($order)) {
            //Use Filter Data ordering if its set.
            if (isset($filter_data['sort_column']) and $filter_data['sort_order']) {
                $order = array(Misc::trimSortPrefix($filter_data['sort_column']) => $filter_data['sort_order']);
            }
        }
        $additional_order_fields = array('d.name', 'e.name', 'f.name', 'g.name', 'h.status_id', 'i.severity_id', 'i.type_id', 'c.first_name', 'c.last_name', 'b.date_stamp');
        if ($order == NULL) {
            //$order = array( 'status_id' => 'asc', 'last_name' => 'asc', 'first_name' => 'asc', 'middle_name' => 'asc');
            $order = array('i.severity_id' => 'desc', 'c.last_name' => 'asc', 'b.date_stamp' => 'asc', 'i.type_id' => 'asc');
            $strict = FALSE;
        } else {
            //Do order by column conversions, because if we include these columns in the SQL
            //query, they contaminate the data array.
            if (isset($order['default_branch'])) {
                $order['d.name'] = $order['default_branch'];
                unset($order['default_branch']);
            }
            if (isset($order['default_department'])) {
                $order['e.name'] = $order['default_department'];
                unset($order['default_department']);
            }
            if (isset($order['user_group'])) {
                $order['f.name'] = $order['user_group'];
                unset($order['user_group']);
            }
            if (isset($order['title'])) {
                $order['g.name'] = $order['title'];
                unset($order['title']);
            }
            if (isset($order['exception_policy_type_id'])) {
                $order['i.type_id'] = $order['exception_policy_type_id'];
                unset($order['exception_policy_type_id']);
            }
            if (isset($order['severity_id'])) {
                $order['i.severity_id'] = $order['severity_id'];
                unset($order['severity_id']);
            }
            if (isset($order['severity'])) {
                $order['i.severity_id'] = $order['severity'];
                unset($order['severity']);
            }
            if (isset($order['exception_policy_type'])) {
                $order['i.type_id'] = $order['exception_policy_type'];
                unset($order['exception_policy_type']);
            }
            if (isset($order['exception_policy_type_id'])) {
                $order['i.type_id'] = $order['exception_policy_type_id'];
                unset($order['exception_policy_type_id']);
            }
            if (isset($order['first_name'])) {
                $order['c.first_name'] = $order['first_name'];
                unset($order['first_name']);
            }
            if (isset($order['last_name'])) {
                $order['c.last_name'] = $order['last_name'];
                unset($order['last_name']);
            }
            if (isset($order['date_stamp'])) {
                $order['b.date_stamp'] = $order['date_stamp'];
                unset($order['date_stamp']);
            }
            //Always sort by last name,first name after other columns
            if (!isset($order['c.last_name'])) {
                $order['c.last_name'] = 'asc';
            }
            if (!isset($order['c.first_name'])) {
                $order['c.first_name'] = 'asc';
            }
            if (!isset($order['b.date_stamp'])) {
                $order['b.date_stamp'] = 'asc';
            }
            if (!isset($order['i.severity_id'])) {
                $order['i.severity_id'] = 'desc';
            }
            $strict = TRUE;
        }
        //Debug::Arr($order,'Order Data:', __FILE__, __LINE__, __METHOD__,10);
        //Debug::Arr($filter_data,'Filter Data:', __FILE__, __LINE__, __METHOD__,10);
        $udf = new UserDateFactory();
        $uf = new UserFactory();
        $bf = new BranchFactory();
        $df = new DepartmentFactory();
        $ugf = new UserGroupFactory();
        $utf = new UserTitleFactory();
        $ppf = new PayPeriodFactory();
        $epf = new ExceptionPolicyFactory();
        $ph = array('company_id' => $company_id);
        $query = '
					select 	a.*,
							b.date_stamp as user_date_stamp,
							i.severity_id as severity_id,
							i.type_id as exception_policy_type_id,
							b.user_id as user_id
					from 	' . $this->getTable() . ' as a
						LEFT JOIN ' . $udf->getTable() . ' as b ON a.user_date_id = b.id
						LEFT JOIN ' . $uf->getTable() . ' as c ON b.user_id = c.id
						LEFT JOIN ' . $bf->getTable() . ' as d ON c.default_branch_id = d.id
						LEFT JOIN ' . $df->getTable() . ' as e ON c.default_department_id = e.id
						LEFT JOIN ' . $ugf->getTable() . ' as f ON c.group_id = f.id
						LEFT JOIN ' . $utf->getTable() . ' as g ON c.title_id = g.id
						LEFT JOIN ' . $ppf->getTable() . ' as h ON b.pay_period_id = h.id
						LEFT JOIN ' . $epf->getTable() . ' as i ON a.exception_policy_id = i.id
					where	c.company_id = ?
					';
        if (isset($filter_data['permission_children_ids']) and isset($filter_data['permission_children_ids'][0]) and !in_array(-1, (array) $filter_data['permission_children_ids'])) {
            $query .= ' AND c.id in (' . $this->getListSQL($filter_data['permission_children_ids'], $ph) . ') ';
        }
        if (isset($filter_data['id']) and isset($filter_data['id'][0]) and !in_array(-1, (array) $filter_data['id'])) {
            $query .= ' AND c.id in (' . $this->getListSQL($filter_data['id'], $ph) . ') ';
        }
        if (isset($filter_data['user_id']) and isset($filter_data['user_id'][0]) and !in_array(-1, (array) $filter_data['user_id'])) {
            $query .= ' AND c.id in (' . $this->getListSQL($filter_data['user_id'], $ph) . ') ';
        }
        if (isset($filter_data['status_id']) and isset($filter_data['status_id'][0]) and !in_array(-1, (array) $filter_data['status_id'])) {
            $query .= ' AND c.status_id in (' . $this->getListSQL($filter_data['status_id'], $ph) . ') ';
        }
        if (isset($filter_data['type_id']) and isset($filter_data['type_id'][0]) and !in_array(-1, (array) $filter_data['type_id'])) {
            $query .= ' AND a.type_id in (' . $this->getListSQL($filter_data['type_id'], $ph) . ') ';
        }
        if (isset($filter_data['severity_id']) and isset($filter_data['severity_id'][0]) and !in_array(-1, (array) $filter_data['severity_id'])) {
            $query .= ' AND i.severity_id in (' . $this->getListSQL($filter_data['severity_id'], $ph) . ') ';
        }
        if (isset($filter_data['exception_policy_type_id']) and isset($filter_data['exception_policy_type_id'][0]) and !in_array(-1, (array) $filter_data['exception_policy_type_id'])) {
            $query .= ' AND i.type_id in (' . $this->getListSQL($filter_data['exception_policy_type_id'], $ph) . ') ';
        }
        if (isset($filter_data['pay_period_id']) and isset($filter_data['pay_period_id'][0]) and !in_array(-1, (array) $filter_data['pay_period_id'])) {
            $query .= ' AND b.pay_period_id in (' . $this->getListSQL($filter_data['pay_period_id'], $ph) . ') ';
        }
        if (isset($filter_data['pay_period_status_id']) and isset($filter_data['pay_period_status_id'][0]) and !in_array(-1, (array) $filter_data['pay_period_status_id'])) {
            $query .= ' AND h.status_id in (' . $this->getListSQL($filter_data['pay_period_status_id'], $ph) . ') ';
        }
        if (isset($filter_data['group_id']) and isset($filter_data['group_id'][0]) and !in_array(-1, (array) $filter_data['group_id'])) {
            if (isset($filter_data['include_subgroups']) and (bool) $filter_data['include_subgroups'] == TRUE) {
                $uglf = new UserGroupListFactory();
                $filter_data['group_id'] = $uglf->getByCompanyIdAndGroupIdAndSubGroupsArray($company_id, $filter_data['group_id'], TRUE);
            }
            $query .= ' AND c.group_id in (' . $this->getListSQL($filter_data['group_id'], $ph) . ') ';
        }
        if (isset($filter_data['default_branch_id']) and isset($filter_data['default_branch_id'][0]) and !in_array(-1, (array) $filter_data['default_branch_id'])) {
            $query .= ' AND c.default_branch_id in (' . $this->getListSQL($filter_data['default_branch_id'], $ph) . ') ';
        }
        if (isset($filter_data['default_department_id']) and isset($filter_data['default_department_id'][0]) and !in_array(-1, (array) $filter_data['default_department_id'])) {
            $query .= ' AND c.default_department_id in (' . $this->getListSQL($filter_data['default_department_id'], $ph) . ') ';
        }
        if (isset($filter_data['title_id']) and isset($filter_data['title_id'][0]) and !in_array(-1, (array) $filter_data['title_id'])) {
            $query .= ' AND c.title_id in (' . $this->getListSQL($filter_data['title_id'], $ph) . ') ';
        }
        /*
        if ( isset($filter_data['sin']) AND trim($filter_data['sin']) != '' ) {
        	$ph[] = trim($filter_data['sin']);
        	$query  .=	' AND a.sin LIKE ?';
        }
        */
        $query .= '
						AND ( a.deleted = 0 AND c.deleted = 0 AND h.deleted = 0 )
					';
        $query .= $this->getWhereSQL($where);
        $query .= $this->getSortSQL($order, $strict, $additional_order_fields);
        if ($limit == NULL) {
            $this->rs = $this->db->Execute($query, $ph);
        } else {
            $this->rs = $this->db->PageExecute($query, $limit, $page, $ph);
        }
        return $this;
    }
 function postInstall()
 {
     global $config_vars;
     Debug::text('postInstall: ' . $this->getVersion(), __FILE__, __LINE__, __METHOD__, 9);
     //Update permission for new modules.
     $clf = TTnew('CompanyListFactory');
     $clf->getAll();
     if ($clf->getRecordCount() > 0) {
         $i = 0;
         foreach ($clf as $c_obj) {
             if ($c_obj->getStatus() != 30) {
                 Debug::text($i . '/' . $clf->getRecordCount() . '. Company: ' . $c_obj->getName(), __FILE__, __LINE__, __METHOD__, 9);
                 //Disable detailed audit logging while updating permissions, as this can create millions of records and slow the upgrade down substantially.
                 $config_vars['other']['disable_audit_log_detail'] = TRUE;
                 $config_vars['other']['disable_audit_log'] = TRUE;
                 $pclf = TTnew('PermissionControlListFactory');
                 // Update all the HR related permissions for the Standard/Business Edition (KPIs, reviews, qualifications, etc..., but *not* job vacancy or job applicants)
                 $pclf->getByCompanyID($c_obj->getID(), NULL, NULL, NULL, array('id' => 'asc'));
                 if ($pclf->getRecordCount() > 0) {
                     $pf = TTnew('PermissionFactory');
                     $preset_options = $pf->getOptions('preset');
                     $preset_level_options = $pf->getOptions('preset_level');
                     ksort($preset_options);
                     foreach ($pclf as $pc_obj) {
                         $level = $pc_obj->getLevel();
                         // 1, 10, 12, 15, 20, 25
                         if ($level >= 10) {
                             //Only process levels 10 and higher, as those are supervisors and only ones that need adjusting.
                             $old_permission_arr = $pc_obj->getPermission();
                             if (is_array($old_permission_arr)) {
                                 foreach ($preset_options as $preset => $preset_name) {
                                     // preset: 10, 18, 20, 30, 40
                                     if ($level == $preset_level_options[$preset]) {
                                         $permission_arr = $pf->getPresetPermissions($preset, array(70, 75, 80));
                                         //Module: Human Resources
                                         //Debug::Arr( $permission_arr, ' New Permissions: ', __FILE__, __LINE__, __METHOD__,10);
                                         $pc_obj->setPermission($permission_arr, $old_permission_arr);
                                     }
                                 }
                             }
                         }
                     }
                 }
                 unset($pclf, $pf, $preset_options, $preset_level_options, $old_permission_arr, $level, $pc_obj);
                 //Re-enable audit logging after permissions were updated.
                 $config_vars['other']['disable_audit_log_detail'] = FALSE;
                 $config_vars['other']['disable_audit_log'] = FALSE;
                 //Delete duplicate OPEN shifts before todays date.
                 $sf = new ScheduleFactory();
                 $udf = new UserDateFactory();
                 $ph = array('id' => $this->db->BindDate(time()));
                 $query = 'update ' . $sf->getTable() . ' set deleted = 1 where user_date_id in ( select id from ' . $udf->getTable() . ' where user_id = 0 and date_stamp <= ? and deleted = 0 ) and created_by is NULL AND deleted = 0';
                 $this->db->Execute($query, $ph);
                 unset($query, $ph);
                 //Assign all absence policies to every policy group.
                 $aplf = TTnew('AbsencePolicyListFactory');
                 $aplf->getByCompanyId($c_obj->getId());
                 if ($aplf->getRecordCount() > 0) {
                     foreach ($aplf as $ap_obj) {
                         $ap_ids[] = $ap_obj->getId();
                     }
                 }
                 $pglf = TTnew('PolicyGroupListFactory');
                 $pglf->getByCompanyId($c_obj->getId());
                 if ($pglf->getRecordCount() > 0) {
                     foreach ($pglf as $pg_obj) {
                         if (isset($ap_ids)) {
                             $pg_obj->setAbsencePolicy($ap_ids);
                             if ($pg_obj->isValid()) {
                                 $pg_obj->Save();
                             }
                         }
                     }
                 }
                 unset($aplf, $pglf, $ap_obj, $pg_obj, $ap_ids);
             }
             $i++;
         }
     }
     return TRUE;
 }
 /**
  * ReCalculate timesheet/policies
  * @return bool
  */
 function reCalculateTimeSheet($pay_period_ids, $user_ids = NULL)
 {
     //Debug::text('Recalculating Employee Timesheet: User ID: '. $user_ids .' Pay Period ID: '. $pay_period_ids, __FILE__, __LINE__, __METHOD__,10);
     //Debug::setVerbosity(11);
     if (!$this->getPermissionObject()->Check('punch', 'enabled') or !($this->getPermissionObject()->Check('punch', 'edit') or $this->getPermissionObject()->Check('punch', 'edit_child'))) {
         return $this->getPermissionObject()->PermissionDenied();
     }
     //Make sure pay period is not CLOSED.
     //We can re-calc on locked though.
     $pplf = TTnew('PayPeriodListFactory');
     $pplf->getByIdList($pay_period_ids);
     if ($pplf->getRecordCount() > 0) {
         $pp_obj = $pplf->getCurrent();
         if ($pp_obj->getStatus() != 20) {
             $udlf = TTnew('UserDateListFactory');
             if (is_array($user_ids) and count($user_ids) > 0 and isset($user_ids[0]) and $user_ids[0] > 0) {
                 $udlf->getByUserIdAndPayPeriodID($user_ids, $pay_period_ids);
             } elseif ($this->getPermissionObject()->Check('punch', 'edit') == TRUE) {
                 //Make sure they have the permissions to recalculate all employees.
                 TTLog::addEntry($this->getCurrentCompanyObject()->getId(), TTi18n::gettext('Notice'), TTi18n::gettext('Recalculating Company TimeSheet'), $this->getCurrentUserObject()->getId(), 'user_date_total');
                 $udlf->getByCompanyIdAndPayPeriodID($this->getCurrentCompanyObject()->getId(), $pay_period_ids);
             } else {
                 return $this->getPermissionObject()->PermissionDenied();
             }
             if ($udlf->getRecordCount() > 0) {
                 Debug::text('Found days to re-calculate: ' . $udlf->getRecordCount(), __FILE__, __LINE__, __METHOD__, 10);
                 $this->getProgressBarObject()->start($this->getAMFMessageID(), $udlf->getRecordCount(), NULL, TTi18n::getText('ReCalculating...'));
                 $x = 1;
                 $prev_date_stamp = FALSE;
                 foreach ($udlf as $ud_obj) {
                     Debug::text($x . ' / ' . $udlf->getRecordCount() . ' - User Date Id: ' . $ud_obj->getId() . ' Date: ' . $ud_obj->getDateStamp(TRUE) . ' User ID: ' . $ud_obj->getUser(), __FILE__, __LINE__, __METHOD__, 10);
                     if ($prev_date_stamp != FALSE and abs($ud_obj->getDateStamp() - $prev_date_stamp) > 86400) {
                         Debug::text('Found gap between user_date rows! - User Date Id: ' . $ud_obj->getId() . ' Date: ' . $ud_obj->getDateStamp(TRUE) . ' Previous Date: ' . TTDate::getDate('DATE', $prev_date_stamp) . ' User ID: ' . $ud_obj->getUser(), __FILE__, __LINE__, __METHOD__, 10);
                         for ($n = $prev_date_stamp; $n < $ud_obj->getDateStamp(); $n += 86400) {
                             $tmp_user_date_id = UserDateFactory::findOrInsertUserDate($ud_obj->getUser(), TTDate::getBeginDayEpoch($n));
                             Debug::text('Filling gap in user_date rows! - Date: ' . TTDate::getDate('DATE', $n) . ' User ID: ' . $ud_obj->getUser() . ' New User Date ID: ' . $tmp_user_date_id, __FILE__, __LINE__, __METHOD__, 10);
                             UserDateTotalFactory::reCalculateDay($tmp_user_date_id, TRUE);
                         }
                         unset($n, $tmp_user_date_id);
                     }
                     TTLog::addEntry($ud_obj->getId(), 500, TTi18n::gettext('Recalculating Employee TimeSheet') . ': ' . $ud_obj->getUserObject()->getFullName() . ' ' . TTi18n::gettext('Date') . ': ' . TTDate::getDate('DATE', $ud_obj->getDateStamp()), $this->getCurrentUserObject()->getId(), 'user_date_total');
                     $udlf->StartTransaction();
                     //If a transaction wraps the entire recalculation process, a deadlock is likely to occur for large batches.
                     UserDateTotalFactory::reCalculateDay($ud_obj->getId(), TRUE);
                     $udlf->CommitTransaction();
                     $this->getProgressBarObject()->set($this->getAMFMessageID(), $x);
                     $prev_date_stamp = $ud_obj->getDateStamp();
                     $x++;
                 }
                 $this->getProgressBarObject()->stop($this->getAMFMessageID());
             } else {
                 Debug::text('No User Date rows to calculate!', __FILE__, __LINE__, __METHOD__, 10);
             }
         } else {
             Debug::text('Pay Period is CLOSED: ', __FILE__, __LINE__, __METHOD__, 10);
         }
     }
     return $this->returnHandler(TRUE);
 }
    function getMidDayExceptionsByStartDateAndEndDateAndPayPeriodStatus($start_date, $end_date, $pay_period_status_id)
    {
        if ($start_date == '') {
            return FALSE;
        }
        if ($end_date == '') {
            return FALSE;
        }
        if ($pay_period_status_id == '') {
            return FALSE;
        }
        $epf = new ExceptionPolicyFactory();
        $ef = new ExceptionFactory();
        $epcf = new ExceptionPolicyControlFactory();
        $pgf = new PolicyGroupFactory();
        $pguf = new PolicyGroupUserFactory();
        $uf = new UserFactory();
        $cf = new CompanyFactory();
        $udf = new UserDateFactory();
        $sf = new ScheduleFactory();
        $pcf = new PunchControlFactory();
        $pf = new PunchFactory();
        $ppf = new PayPeriodFactory();
        $current_epoch = time();
        if (strncmp($this->db->databaseType, 'mysql', 5) == 0) {
            $to_timestamp_sql = 'FROM_UNIXTIME';
        } else {
            $to_timestamp_sql = 'to_timestamp';
        }
        $ph = array('current_time1' => $this->db->BindTimeStamp($current_epoch), 'current_time2' => $this->db->BindTimeStamp($current_epoch), 'current_epoch1' => $current_epoch, 'start_date' => $this->db->BindDate($start_date), 'end_date' => $this->db->BindDate($end_date));
        //Exceptions that need to be calculated in the middle of the day:
        //Definitely: In Late, Out Late, Missed CheckIn
        //Possible: Over Daily Scheduled Time, Over Weekly Scheduled Time, Over Daily Time, Over Weekly Time, Long Lunch (can't run this fast enough), Long Break (can't run this fast enough),
        //Optimize calcQuickExceptions:
        // Loop through exception policies where In Late/Out Late/Missed CheckIn are enabled.
        // Loop through ACTIVE users assigned to these exceptions policies.
        // Only find days that are scheduled AND ( NO punch after schedule start time OR NO punch after schedule end time )
        //      For Missed CheckIn they do not need to be scheduled.
        // Exclude days that already have the exceptions triggered on them (?) (What about split shifts?)
        //	- Just exclude exceptions not assigned to punch/punch_control_id, if there is more than one in the day I don't think it helps much anyways.
        //
        //Currently Over Weekly/Daily time exceptions are only triggered on a Out punch.
        $query = '	select distinct udf.*
					FROM ' . $epf->getTable() . ' as epf
					LEFT JOIN ' . $epcf->getTable() . ' as epcf ON ( epf.exception_policy_control_id = epcf.id )
					LEFT JOIN ' . $pgf->getTable() . ' as pgf ON ( epcf.id = pgf.exception_policy_control_id )
					LEFT JOIN ' . $pguf->getTable() . ' as pguf ON ( pgf.id = pguf.policy_group_id )
					LEFT JOIN ' . $uf->getTable() . ' as uf ON ( pguf.user_id = uf.id )
					LEFT JOIN ' . $cf->getTable() . ' as cf ON ( uf.company_id = cf.id )
					LEFT JOIN ' . $udf->getTable() . ' as udf ON ( uf.id = udf.user_id )
					LEFT JOIN ' . $ppf->getTable() . ' as ppf ON ( ppf.id = udf.pay_period_id )
					LEFT JOIN ' . $ef->getTable() . ' as ef ON ( udf.id = ef.user_date_id AND ef.exception_policy_id = epf.id AND ef.type_id != 5 )
					LEFT JOIN ' . $sf->getTable() . ' as sf ON ( udf.id = sf.user_date_id AND ( sf.start_time <= ? OR sf.end_time <= ? ) )
					LEFT JOIN ' . $pcf->getTable() . ' as pcf ON ( udf.id = pcf.user_date_id AND pcf.deleted = 0 )
					LEFT JOIN ' . $pf->getTable() . ' as pf ON 	(
																pcf.id = pf.punch_control_id AND pf.deleted = 0
																AND (
																		( epf.type_id = \'S4\' AND ( pf.time_stamp >= sf.start_time OR pf.time_stamp <= sf.end_time ) )
																		OR
																		( epf.type_id = \'S6\' AND ( pf.time_stamp >= sf.end_time ) )
																		OR
																		( epf.type_id = \'C1\' AND ( pf.status_id = 10 AND pf.time_stamp <= ' . $to_timestamp_sql . '(?-epf.grace) ) )
																	)
																)
					WHERE ( epf.type_id in (\'S4\',\'S6\', \'C1\') AND epf.active = 1 )
						AND ( uf.status_id = 10 AND cf.status_id != 30 )
						AND ( udf.date_stamp >= ? AND udf.date_stamp <= ? )
						AND ppf.status_id in (' . $this->getListSQL($pay_period_status_id, $ph) . ')
						AND ( ( ( epf.type_id in (\'S4\',\'S6\') AND ( sf.id IS NOT NULL AND sf.deleted = 0 ) AND pf.id IS NULL ) OR epf.type_id = \'C1\' ) AND ef.id IS NULL  )
						AND ( epf.deleted = 0 AND epcf.deleted = 0 AND pgf.deleted = 0 AND uf.deleted = 0 AND cf.deleted = 0 AND udf.deleted = 0 )
				';
        //Don't check deleted = 0 on PCF/PF tables, as we need to check IS NULL on them instead.
        //Debug::Arr($ph, 'Query: '. $query, __FILE__, __LINE__, __METHOD__, 10);
        $this->ExecuteSQL($query, $ph);
        return $this;
    }
    function getScheduleSummaryReportByCompanyIdAndArrayCriteria($company_id, $filter_data, $limit = NULL, $page = NULL, $where = NULL, $order = NULL)
    {
        if ($company_id == '') {
            return FALSE;
        }
        if (!is_array($order)) {
            //Use Filter Data ordering if its set.
            if (isset($filter_data['sort_column']) and $filter_data['sort_order']) {
                $order = array(Misc::trimSortPrefix($filter_data['sort_column']) => $filter_data['sort_order']);
            }
        }
        $additional_order_fields = array('schedule_policy_id', 'schedule_policy', 'first_name', 'last_name', 'user_status_id', 'group_id', 'group', 'title_id', 'title', 'default_branch_id', 'default_branch', 'default_department_id', 'default_department', 'total_time', 'date_stamp', 'pay_period_id');
        $sort_column_aliases = array('updated_date' => 'a.updated_date', 'created_date' => 'a.created_date');
        $order = $this->getColumnsFromAliases($order, $sort_column_aliases);
        if ($order == NULL) {
            $order = array('c.pay_period_id' => 'asc', 'c.user_id' => 'asc', 'a.start_time' => 'asc');
            $strict = FALSE;
        } else {
            $strict = TRUE;
        }
        //Debug::Arr($order,'Order Data:', __FILE__, __LINE__, __METHOD__,10);
        //Debug::Arr($filter_data,'Filter Data:', __FILE__, __LINE__, __METHOD__,10);
        if (isset($filter_data['exclude_user_ids'])) {
            $filter_data['exclude_user_id'] = $filter_data['exclude_user_ids'];
        }
        if (isset($filter_data['include_user_ids'])) {
            $filter_data['include_user_id'] = $filter_data['include_user_ids'];
        }
        if (isset($filter_data['user_status_ids'])) {
            $filter_data['user_status_id'] = $filter_data['user_status_ids'];
        }
        if (isset($filter_data['user_title_ids'])) {
            $filter_data['title_id'] = $filter_data['user_title_ids'];
        }
        if (isset($filter_data['group_ids'])) {
            $filter_data['group_id'] = $filter_data['group_ids'];
        }
        if (isset($filter_data['default_branch_ids'])) {
            $filter_data['default_branch_id'] = $filter_data['default_branch_ids'];
        }
        if (isset($filter_data['default_department_ids'])) {
            $filter_data['default_department_id'] = $filter_data['default_department_ids'];
        }
        if (isset($filter_data['branch_ids'])) {
            $filter_data['branch_id'] = $filter_data['branch_ids'];
        }
        if (isset($filter_data['department_ids'])) {
            $filter_data['department_id'] = $filter_data['department_ids'];
        }
        if (isset($filter_data['schedule_branch_id'])) {
            $filter_data['branch_id'] = $filter_data['schedule_branch_id'];
        }
        if (isset($filter_data['schedule_department_id'])) {
            $filter_data['department_id'] = $filter_data['schedule_department_id'];
        }
        if (isset($filter_data['exclude_job_ids'])) {
            $filter_data['exclude_job_id'] = $filter_data['exclude_job_ids'];
        }
        if (isset($filter_data['include_job_ids'])) {
            $filter_data['include_job_id'] = $filter_data['include_job_ids'];
        }
        if (isset($filter_data['job_group_ids'])) {
            $filter_data['job_group_id'] = $filter_data['job_group_ids'];
        }
        if (isset($filter_data['job_item_ids'])) {
            $filter_data['job_item_id'] = $filter_data['job_item_ids'];
        }
        if (isset($filter_data['pay_period_ids'])) {
            $filter_data['pay_period_id'] = $filter_data['pay_period_ids'];
        }
        if (isset($filter_data['start_time'])) {
            $filter_data['start_date'] = $filter_data['start_time'];
        }
        if (isset($filter_data['end_time'])) {
            $filter_data['end_date'] = $filter_data['end_time'];
        }
        $spf = new SchedulePolicyFactory();
        $apf = new AbsencePolicyFactory();
        $uf = new UserFactory();
        $bf = new BranchFactory();
        $df = new DepartmentFactory();
        $ugf = new UserGroupFactory();
        $utf = new UserTitleFactory();
        $udf = new UserDateFactory();
        $ppf = new PayPeriodFactory();
        $uwf = new UserWageFactory();
        if (getTTProductEdition() >= TT_PRODUCT_CORPORATE) {
            $jf = new JobFactory();
            $jif = new JobItemFactory();
        }
        $ph = array('company_id' => $company_id, 'company_id2' => $company_id);
        //"group" is a reserved word in MySQL.
        $query = '
					select
							a.id as id,
							a.id as schedule_id,
							a.status_id as status_id,
							a.start_time as start_time,
							a.end_time as end_time,

							a.user_date_id as user_date_id,
							a.branch_id as branch_id,
							j.name as branch,
							a.department_id as department_id,
							k.name as department,
							a.job_id as job_id,
							a.job_item_id as job_item_id,
							a.total_time as total_time,
							a.schedule_policy_id as schedule_policy_id,
							i.name as schedule_policy,

							a.note as note,

							a.absence_policy_id as absence_policy_id,
							apf.name as absence_policy,
							apf.type_id as absence_policy_type_id,

							c.user_id as user_id,
							c.date_stamp as date_stamp,
							ppf.id as pay_period_id,
							ppf.start_date as pay_period_start_date,
							ppf.end_date as pay_period_end_date,
							ppf.transaction_date as pay_period_transaction_date,

							c.pay_period_id as pay_period_id,

							d.first_name as first_name,
							d.last_name as last_name,
							d.status_id as user_status_id,
							d.group_id as group_id,
							g.name as "group",
							d.title_id as title_id,
							h.name as title,
							d.default_branch_id as default_branch_id,
							e.name as default_branch,
							d.default_department_id as default_department_id,
							f.name as default_department,
							d.created_by as user_created_by,

							m.id as user_wage_id,
							m.hourly_rate as user_wage_hourly_rate,
							m.labor_burden_percent as user_labor_burden_percent,
							m.effective_date as user_wage_effective_date,

							y.first_name as created_by_first_name,
							y.middle_name as created_by_middle_name,
							y.last_name as created_by_last_name,
							z.first_name as updated_by_first_name,
							z.middle_name as updated_by_middle_name,
							z.last_name as updated_by_last_name';
        if (getTTProductEdition() >= TT_PRODUCT_CORPORATE) {
            $query .= ',
						w.name as job_name,
						w.status_id as job_status_id,
						w.manual_id as job_manual_id,
						w.branch_id as job_branch_id,
						w.department_id as job_department_id,
						w.group_id as job_group_id';
        }
        $query .= '
					from 	' . $this->getTable() . ' as a
							LEFT JOIN ' . $spf->getTable() . ' as i ON ( a.schedule_policy_id = i.id AND i.deleted = 0)
							LEFT JOIN ' . $apf->getTable() . ' as apf ON ( a.absence_policy_id = apf.id AND apf.deleted = 0)
							LEFT JOIN ' . $udf->getTable() . ' as c ON a.user_date_id = c.id
							LEFT JOIN ' . $ppf->getTable() . ' as ppf ON c.pay_period_id = ppf.id
							LEFT JOIN ' . $uf->getTable() . ' as d ON ( c.user_id = d.id AND d.deleted = 0 )

							LEFT JOIN ' . $bf->getTable() . ' as e ON ( d.default_branch_id = e.id AND e.deleted = 0)
							LEFT JOIN ' . $df->getTable() . ' as f ON ( d.default_department_id = f.id AND f.deleted = 0)
							LEFT JOIN ' . $ugf->getTable() . ' as g ON ( d.group_id = g.id AND g.deleted = 0 )
							LEFT JOIN ' . $utf->getTable() . ' as h ON ( d.title_id = h.id AND h.deleted = 0 )

							LEFT JOIN ' . $bf->getTable() . ' as j ON ( a.branch_id = j.id AND j.deleted = 0)
							LEFT JOIN ' . $df->getTable() . ' as k ON ( a.department_id = k.id AND k.deleted = 0)

							LEFT JOIN ' . $uwf->getTable() . ' as m ON m.id = (select m.id
																		from ' . $uwf->getTable() . ' as m
																		where m.user_id = c.user_id
																			and m.effective_date <= c.date_stamp
																			and m.deleted = 0
																			order by m.effective_date desc limit 1)
					';
        if (getTTProductEdition() >= TT_PRODUCT_CORPORATE) {
            $query .= '	LEFT JOIN ' . $jf->getTable() . ' as w ON a.job_id = w.id';
            $query .= '	LEFT JOIN ' . $jif->getTable() . ' as x ON a.job_item_id = x.id';
        }
        $query .= '
						LEFT JOIN ' . $uf->getTable() . ' as y ON ( a.created_by = y.id AND y.deleted = 0 )
						LEFT JOIN ' . $uf->getTable() . ' as z ON ( a.updated_by = z.id AND z.deleted = 0 )
					WHERE ( d.company_id = ? OR a.company_id = ? )';
        $query .= isset($filter_data['permission_children_ids']) ? $this->getWhereClauseSQL('d.id', $filter_data['permission_children_ids'], 'numeric_list', $ph) : NULL;
        $query .= isset($filter_data['id']) ? $this->getWhereClauseSQL('a.id', $filter_data['id'], 'numeric_list', $ph) : NULL;
        //Need to include/exclude users based on c.user_id, as we need to support OPEN shifts and user_id=0 which can only happen in user_date table.
        $query .= isset($filter_data['include_user_id']) ? $this->getWhereClauseSQL('c.user_id', $filter_data['include_user_id'], 'numeric_list', $ph) : NULL;
        $query .= isset($filter_data['exclude_user_id']) ? $this->getWhereClauseSQL('c.user_id', $filter_data['exclude_user_id'], 'not_numeric_list', $ph) : NULL;
        $query .= isset($filter_data['user_status_id']) ? $this->getWhereClauseSQL('d.status_id', $filter_data['user_status_id'], 'numeric_list', $ph) : NULL;
        if (isset($filter_data['include_user_subgroups']) and (bool) $filter_data['include_user_subgroups'] == TRUE) {
            $uglf = new UserGroupListFactory();
            $filter_data['group_id'] = $uglf->getByCompanyIdAndGroupIdAndSubGroupsArray($company_id, $filter_data['group_id'], TRUE);
        }
        $query .= isset($filter_data['group_id']) ? $this->getWhereClauseSQL('d.group_id', $filter_data['group_id'], 'numeric_list', $ph) : NULL;
        $query .= isset($filter_data['default_branch_id']) ? $this->getWhereClauseSQL('d.default_branch_id', $filter_data['default_branch_id'], 'numeric_list', $ph) : NULL;
        $query .= isset($filter_data['default_department_id']) ? $this->getWhereClauseSQL('d.default_department_id', $filter_data['default_department_id'], 'numeric_list', $ph) : NULL;
        $query .= isset($filter_data['title_id']) ? $this->getWhereClauseSQL('d.title_id', $filter_data['title_id'], 'numeric_list', $ph) : NULL;
        $query .= isset($filter_data['branch_id']) ? $this->getWhereClauseSQL('a.branch_id', $filter_data['branch_id'], 'numeric_list', $ph) : NULL;
        $query .= isset($filter_data['department_id']) ? $this->getWhereClauseSQL('a.department_id', $filter_data['department_id'], 'numeric_list', $ph) : NULL;
        $query .= isset($filter_data['status_id']) ? $this->getWhereClauseSQL('a.status_id', $filter_data['status_id'], 'numeric_list', $ph) : NULL;
        $query .= isset($filter_data['schedule_policy_id']) ? $this->getWhereClauseSQL('a.pay_period_id', $filter_data['schedule_policy_id'], 'numeric_list', $ph) : NULL;
        $query .= isset($filter_data['pay_period_id']) ? $this->getWhereClauseSQL('c.pay_period_id', $filter_data['pay_period_id'], 'numeric_list', $ph) : NULL;
        $query .= isset($filter_data['tag']) ? $this->getWhereClauseSQL('d.id', array('company_id' => $company_id, 'object_type_id' => 200, 'tag' => $filter_data['tag']), 'tag', $ph) : NULL;
        //Use the job_id in the schedule table so we can filter by '0' or No Job
        $query .= isset($filter_data['include_job_id']) ? $this->getWhereClauseSQL('a.job_id', $filter_data['include_job_id'], 'numeric_list', $ph) : NULL;
        $query .= isset($filter_data['exclude_job_id']) ? $this->getWhereClauseSQL('a.job_id', $filter_data['exclude_job_id'], 'not_numeric_list', $ph) : NULL;
        if (isset($filter_data['include_job_subgroups']) and (bool) $filter_data['include_job_subgroups'] == TRUE) {
            $jglf = new JobGroupListFactory();
            $filter_data['job_group_id'] = $jglf->getByCompanyIdAndGroupIdAndSubGroupsArray($company_id, $filter_data['job_group_id'], TRUE);
        }
        $query .= isset($filter_data['job_group_id']) ? $this->getWhereClauseSQL('w.group_id', $filter_data['job_group_id'], 'numeric_list', $ph) : NULL;
        $query .= isset($filter_data['job_item_id']) ? $this->getWhereClauseSQL('a.job_item_id', $filter_data['job_item_id'], 'numeric_list', $ph) : NULL;
        if (isset($filter_data['start_date']) and trim($filter_data['start_date']) != '') {
            $ph[] = $this->db->BindTimeStamp($filter_data['start_date']);
            $query .= ' AND a.start_time >= ?';
        }
        if (isset($filter_data['end_date']) and trim($filter_data['end_date']) != '') {
            $ph[] = $this->db->BindTimeStamp($filter_data['end_date']);
            $query .= ' AND a.start_time <= ?';
        }
        $query .= isset($filter_data['created_by']) ? $this->getWhereClauseSQL(array('a.created_by', 'y.first_name', 'y.last_name'), $filter_data['created_by'], 'user_id_or_name', $ph) : NULL;
        $query .= isset($filter_data['updated_by']) ? $this->getWhereClauseSQL(array('a.updated_by', 'z.first_name', 'z.last_name'), $filter_data['updated_by'], 'user_id_or_name', $ph) : NULL;
        $query .= '
						AND (a.deleted = 0 AND c.deleted = 0 )
					';
        $query .= $this->getWhereSQL($where);
        $query .= $this->getSortSQL($order, $strict, $additional_order_fields);
        //Debug::Arr($ph,'Query: '. $query, __FILE__, __LINE__, __METHOD__,10);
        $this->ExecuteSQL($query, $ph, $limit, $page);
        return $this;
    }
    function getByCompanyIdAndArrayCriteria($company_id, $filter_data, $limit = NULL, $page = NULL, $where = NULL, $order = NULL)
    {
        if ($company_id == '') {
            return FALSE;
        }
        if ($order == NULL) {
            $order = array('a.status_id' => 'asc', 'b.date_stamp' => 'desc', 'a.type_id' => 'asc');
            $strict = FALSE;
        } else {
            $strict = TRUE;
        }
        $udf = new UserDateFactory();
        $uf = new UserFactory();
        $ph = array('company_id' => $company_id);
        $query = '
					select 	a.*,
							b.date_stamp as date_stamp
					from	' . $this->getTable() . ' as a,
							' . $udf->getTable() . ' as b,
							' . $uf->getTable() . ' as c
					where 	a.user_date_id = b.id
						AND b.user_id = c.id
						AND c.company_id = ? ';
        if (isset($filter_data['permission_children_ids']) and isset($filter_data['permission_children_ids'][0]) and !in_array(-1, (array) $filter_data['permission_children_ids'])) {
            $query .= ' AND b.user_id in (' . $this->getListSQL($filter_data['permission_children_ids'], $ph) . ') ';
        }
        if (isset($filter_data['user_id']) and isset($filter_data['user_id'][0]) and !in_array(-1, (array) $filter_data['user_id'])) {
            $query .= ' AND b.user_id in (' . $this->getListSQL($filter_data['user_id'], $ph) . ') ';
        }
        if (isset($filter_data['start_date']) and trim($filter_data['start_date']) != '') {
            $ph[] = $this->db->BindDate($filter_data['start_date']);
            $query .= ' AND b.date_stamp >= ?';
        }
        if (isset($filter_data['end_date']) and trim($filter_data['end_date']) != '') {
            $ph[] = $this->db->BindDate($filter_data['end_date']);
            $query .= ' AND b.date_stamp <= ?';
        }
        $query .= '		AND ( a.deleted = 0 AND b.deleted = 0 AND c.deleted = 0 ) ';
        $query .= $this->getWhereSQL($where);
        $query .= $this->getSortSQL($order);
        Debug::Text('Query: ' . $query, __FILE__, __LINE__, __METHOD__, 10);
        if ($limit == NULL) {
            $this->rs = $this->db->Execute($query, $ph);
        } else {
            $this->rs = $this->db->PageExecute($query, $limit, $page, $ph);
        }
        return $this;
    }
Beispiel #16
0
        if ($c_obj->getStatus() != 30) {
            $ppslf = new PayPeriodScheduleListFactory();
            $ulf = new UserListFactory();
            $ulf->getByCompanyId($c_obj->getId());
            if ($ulf->getRecordCount() > 0) {
                $i = 0;
                foreach ($ulf as $u_obj) {
                    if ($u_obj->getStatus() != 10) {
                        continue;
                    }
                    Debug::text($i . '. User: '******'22-Jan-08');
                        UserDateFactory::findOrInsertUserDate($u_obj->getId(), TTDate::getBeginDayEpoch($epoch));
                    }
                    $i++;
                }
            }
        } else {
            Debug::text('Company is not ACTIVE: ' . $c_obj->getId(), __FILE__, __LINE__, __METHOD__, 10);
        }
    }
}
Debug::writeToLog();
Debug::Display();
    function getLastPunchByCompanyIdAndArrayCriteria($company_id, $filter_data, $limit = NULL, $page = NULL, $where = NULL, $order = NULL)
    {
        if ($company_id == '') {
            return FALSE;
        }
        if (!is_array($order)) {
            //Use Filter Data ordering if its set.
            if (isset($filter_data['sort_column']) and $filter_data['sort_order']) {
                $order = array(Misc::trimSortPrefix($filter_data['sort_column']) => $filter_data['sort_order']);
            }
        }
        //$additional_order_fields = array('b.name', 'c.name', 'd.name', 'e.name');
        $additional_order_fields = array('b.branch_id', 'c.date_stamp', 'd.last_name', 'a.time_stamp', 'a.status_id', 'b.branch_id', 'b.department_id', 'e.type_id');
        if ($order == NULL) {
            $order = array('b.branch_id' => 'asc', 'd.last_name' => 'asc', 'a.time_stamp' => 'desc', 'a.punch_control_id' => 'asc', 'a.status_id' => 'asc');
            $strict = FALSE;
        } else {
            $strict = TRUE;
        }
        //Debug::Arr($order,'Order Data:', __FILE__, __LINE__, __METHOD__,10);
        //Debug::Arr($filter_data,'Filter Data:', __FILE__, __LINE__, __METHOD__,10);
        if (isset($filter_data['exclude_user_ids'])) {
            $filter_data['exclude_id'] = $filter_data['exclude_user_ids'];
        }
        if (isset($filter_data['include_user_ids'])) {
            $filter_data['id'] = $filter_data['include_user_ids'];
        }
        if (isset($filter_data['user_status_ids'])) {
            $filter_data['status_id'] = $filter_data['user_status_ids'];
        }
        if (isset($filter_data['user_title_ids'])) {
            $filter_data['title_id'] = $filter_data['user_title_ids'];
        }
        if (isset($filter_data['group_ids'])) {
            $filter_data['group_id'] = $filter_data['group_ids'];
        }
        if (isset($filter_data['branch_ids'])) {
            $filter_data['default_branch_id'] = $filter_data['branch_ids'];
        }
        if (isset($filter_data['department_ids'])) {
            $filter_data['default_department_id'] = $filter_data['department_ids'];
        }
        if (isset($filter_data['punch_branch_ids'])) {
            $filter_data['punch_branch_id'] = $filter_data['punch_branch_ids'];
        }
        if (isset($filter_data['punch_department_ids'])) {
            $filter_data['punch_department_id'] = $filter_data['punch_department_ids'];
        }
        if (isset($filter_data['exclude_job_ids'])) {
            $filter_data['exclude_id'] = $filter_data['exclude_job_ids'];
        }
        if (isset($filter_data['include_job_ids'])) {
            $filter_data['include_job_id'] = $filter_data['include_job_ids'];
        }
        if (isset($filter_data['job_group_ids'])) {
            $filter_data['job_group_id'] = $filter_data['job_group_ids'];
        }
        if (isset($filter_data['job_item_ids'])) {
            $filter_data['job_item_id'] = $filter_data['job_item_ids'];
        }
        $uf = new UserFactory();
        $udf = new UserDateFactory();
        $pcf = new PunchControlFactory();
        $sf = new StationFactory();
        if (getTTProductEdition() >= TT_PRODUCT_CORPORATE) {
            $jf = new JobFactory();
            $jif = new JobItemFactory();
        }
        $ph = array('company_id' => $company_id);
        $query = '
					select
							a.id as punch_id,
							a.punch_control_id as punch_control_id,
							a.type_id as type_id,
							a.status_id as status_id,
							a.time_stamp as time_stamp,
							a.actual_time_stamp as actual_time_stamp,

							b.user_date_id as user_date_id,
							c.date_stamp as date_stamp,
							b.branch_id as branch_id,
							b.department_id as department_id,
							b.job_id as job_id,
							b.job_item_id as job_item_id,
							b.note as note,

							c.user_id as user_id,

							e.type_id as station_type_id,
							e.station_id as station_station_id,
							e.source as station_source,
							e.description as station_description

					from 	' . $this->getTable() . ' as a
							LEFT JOIN ' . $pcf->getTable() . ' as b ON a.punch_control_id = b.id
							LEFT JOIN ' . $udf->getTable() . ' as c ON b.user_date_id = c.id
							LEFT JOIN ' . $uf->getTable() . ' as d ON c.user_id = d.id
							LEFT JOIN ' . $sf->getTable() . ' as e ON a.station_id = e.id
							LEFT JOIN (
								select tmp2_d.id, max(tmp2_a.time_stamp) as max_punch_time_stamp
									from 	' . $this->getTable() . ' as tmp2_a
									LEFT JOIN ' . $pcf->getTable() . ' as tmp2_b ON tmp2_a.punch_control_id = tmp2_b.id
									LEFT JOIN ' . $udf->getTable() . ' as tmp2_c ON tmp2_b.user_date_id = tmp2_c.id
									LEFT JOIN ' . $uf->getTable() . ' as tmp2_d ON tmp2_c.user_id = tmp2_d.id
									WHERE tmp2_d.company_id = ?';
        if (isset($filter_data['start_date']) and trim($filter_data['start_date']) != '') {
            $ph[] = $this->db->BindDate($filter_data['start_date']);
            $query .= ' AND tmp2_c.date_stamp >= ?';
        }
        if (isset($filter_data['end_date']) and trim($filter_data['end_date']) != '') {
            $ph[] = $this->db->BindDate($filter_data['end_date']);
            $query .= ' AND tmp2_c.date_stamp <= ?';
        }
        $query .= '
										AND tmp2_a.time_stamp is not null
										AND ( tmp2_a.deleted = 0 AND tmp2_b.deleted = 0 AND tmp2_c.deleted = 0 )
									group by tmp2_d.id
							) as tmp2 ON c.user_id = tmp2.id AND a.time_stamp = tmp2.max_punch_time_stamp

					';
        if (getTTProductEdition() >= TT_PRODUCT_CORPORATE) {
            $query .= '	LEFT JOIN ' . $jf->getTable() . ' as x ON b.job_id = x.id';
            $query .= '	LEFT JOIN ' . $jif->getTable() . ' as y ON b.job_item_id = y.id';
        }
        $ph[] = $company_id;
        $query .= '	WHERE tmp2.id IS NOT NULL AND d.company_id = ?';
        if (isset($filter_data['permission_children_ids']) and isset($filter_data['permission_children_ids'][0]) and !in_array(-1, (array) $filter_data['permission_children_ids'])) {
            $query .= ' AND d.id in (' . $this->getListSQL($filter_data['permission_children_ids'], $ph) . ') ';
        }
        if (isset($filter_data['id']) and isset($filter_data['id'][0]) and !in_array(-1, (array) $filter_data['id'])) {
            $query .= ' AND d.id in (' . $this->getListSQL($filter_data['id'], $ph) . ') ';
        }
        if (isset($filter_data['exclude_id']) and isset($filter_data['exclude_id'][0]) and !in_array(-1, (array) $filter_data['exclude_id'])) {
            $query .= ' AND d.id not in (' . $this->getListSQL($filter_data['exclude_id'], $ph) . ') ';
        }
        if (isset($filter_data['status_id']) and isset($filter_data['status_id'][0]) and !in_array(-1, (array) $filter_data['status_id'])) {
            $query .= ' AND d.status_id in (' . $this->getListSQL($filter_data['status_id'], $ph) . ') ';
        }
        if (isset($filter_data['group_id']) and isset($filter_data['group_id'][0]) and !in_array(-1, (array) $filter_data['group_id'])) {
            if (isset($filter_data['include_subgroups']) and (bool) $filter_data['include_subgroups'] == TRUE) {
                $uglf = new UserGroupListFactory();
                $filter_data['group_id'] = $uglf->getByCompanyIdAndGroupIdAndSubGroupsArray($company_id, $filter_data['group_id'], TRUE);
            }
            $query .= ' AND d.group_id in (' . $this->getListSQL($filter_data['group_id'], $ph) . ') ';
        }
        if (isset($filter_data['default_branch_id']) and isset($filter_data['default_branch_id'][0]) and !in_array(-1, (array) $filter_data['default_branch_id'])) {
            $query .= ' AND d.default_branch_id in (' . $this->getListSQL($filter_data['default_branch_id'], $ph) . ') ';
        }
        if (isset($filter_data['default_department_id']) and isset($filter_data['default_department_id'][0]) and !in_array(-1, (array) $filter_data['default_department_id'])) {
            $query .= ' AND d.default_department_id in (' . $this->getListSQL($filter_data['default_department_id'], $ph) . ') ';
        }
        if (isset($filter_data['title_id']) and isset($filter_data['title_id'][0]) and !in_array(-1, (array) $filter_data['title_id'])) {
            $query .= ' AND d.title_id in (' . $this->getListSQL($filter_data['title_id'], $ph) . ') ';
        }
        if (isset($filter_data['punch_branch_id']) and isset($filter_data['punch_branch_id'][0]) and !in_array(-1, (array) $filter_data['punch_branch_id'])) {
            $query .= ' AND b.branch_id in (' . $this->getListSQL($filter_data['punch_branch_id'], $ph) . ') ';
        }
        if (isset($filter_data['punch_department_id']) and isset($filter_data['punch_department_id'][0]) and !in_array(-1, (array) $filter_data['punch_department_id'])) {
            $query .= ' AND b.department_id in (' . $this->getListSQL($filter_data['punch_department_id'], $ph) . ') ';
        }
        //Use the job_id in the punch_control table so we can filter by '0' or No Job
        if (isset($filter_data['include_job_id']) and isset($filter_data['include_job_id'][0]) and !in_array(-1, (array) $filter_data['include_job_id'])) {
            $query .= ' AND b.job_id in (' . $this->getListSQL($filter_data['include_job_id'], $ph) . ') ';
        }
        if (isset($filter_data['exclude_job_id']) and isset($filter_data['exclude_job_id'][0]) and !in_array(-1, (array) $filter_data['exclude_job_id'])) {
            $query .= ' AND b.job_id not in (' . $this->getListSQL($filter_data['exclude_job_id'], $ph) . ') ';
        }
        if (isset($filter_data['job_group_id']) and isset($filter_data['job_group_id'][0]) and !in_array(-1, (array) $filter_data['job_group_id'])) {
            if (isset($filter_data['include_job_subgroups']) and (bool) $filter_data['include_job_subgroups'] == TRUE) {
                $uglf = new UserGroupListFactory();
                $filter_data['job_group_id'] = $uglf->getByCompanyIdAndGroupIdAndjob_subgroupsArray($company_id, $filter_data['job_group_id'], TRUE);
            }
            $query .= ' AND x.group_id in (' . $this->getListSQL($filter_data['job_group_id'], $ph) . ') ';
        }
        if (isset($filter_data['job_item_id']) and isset($filter_data['job_item_id'][0]) and !in_array(-1, (array) $filter_data['job_item_id'])) {
            $query .= ' AND b.job_item_id in (' . $this->getListSQL($filter_data['job_item_id'], $ph) . ') ';
        }
        if (isset($filter_data['start_date']) and trim($filter_data['start_date']) != '') {
            /*
            $ph[] = $this->db->BindDate($filter_data['start_date']);
            $query  .=	' AND c.date_stamp >= ?';
            */
            $ph[] = $this->db->BindTimeStamp($filter_data['start_date']);
            $query .= ' AND a.time_stamp >= ?';
        }
        if (isset($filter_data['end_date']) and trim($filter_data['end_date']) != '') {
            $ph[] = $this->db->BindTimeStamp($filter_data['end_date']);
            $query .= ' AND a.time_stamp <= ?';
        }
        //The Transfer where clause is an attempt to keep transferred punches from appearing twice.
        $query .= '
						AND ( a.transfer = 0 OR ( a.transfer = 1 AND a.status_id = 10) )
						AND ( a.deleted = 0 AND b.deleted =0 AND c.deleted = 0 AND d.deleted = 0 )
					';
        $query .= $this->getWhereSQL($where);
        $query .= $this->getSortSQL($order, $strict, $additional_order_fields);
        $this->ExecuteSQL($query, $ph, $limit, $page);
        return $this;
    }
    function getAPISearchByCompanyIdAndArrayCriteria($company_id, $filter_data, $limit = NULL, $page = NULL, $where = NULL, $order = NULL)
    {
        if ($company_id == '') {
            return FALSE;
        }
        if (!is_array($order)) {
            //Use Filter Data ordering if its set.
            if (isset($filter_data['sort_column']) and $filter_data['sort_order']) {
                $order = array(Misc::trimSortPrefix($filter_data['sort_column']) => $filter_data['sort_order']);
            }
        }
        $additional_order_fields = array('schedule_policy_id', 'schedule_policy', 'first_name', 'last_name', 'user_status_id', 'group_id', 'group', 'title_id', 'title', 'default_branch_id', 'default_branch', 'default_department_id', 'default_department', 'total_time', 'date_stamp', 'pay_period_id');
        if ($order == NULL) {
            $order = array('c.pay_period_id' => 'asc', 'c.user_id' => 'asc', 'a.start_time' => 'asc');
            $strict = FALSE;
        } else {
            $strict = TRUE;
        }
        //Debug::Arr($order,'Order Data:', __FILE__, __LINE__, __METHOD__,10);
        //Debug::Arr($filter_data,'Filter Data:', __FILE__, __LINE__, __METHOD__,10);
        if (isset($filter_data['exclude_user_ids'])) {
            $filter_data['exclude_id'] = $filter_data['exclude_user_ids'];
        }
        if (isset($filter_data['include_user_ids'])) {
            $filter_data['id'] = $filter_data['include_user_ids'];
        }
        if (isset($filter_data['user_status_ids'])) {
            $filter_data['status_id'] = $filter_data['user_status_ids'];
        }
        if (isset($filter_data['user_title_ids'])) {
            $filter_data['title_id'] = $filter_data['user_title_ids'];
        }
        if (isset($filter_data['group_ids'])) {
            $filter_data['group_id'] = $filter_data['group_ids'];
        }
        if (isset($filter_data['default_branch_ids'])) {
            $filter_data['default_branch_id'] = $filter_data['default_branch_ids'];
        }
        if (isset($filter_data['default_department_ids'])) {
            $filter_data['default_department_id'] = $filter_data['default_department_ids'];
        }
        if (isset($filter_data['branch_ids'])) {
            $filter_data['branch_id'] = $filter_data['branch_ids'];
        }
        if (isset($filter_data['department_ids'])) {
            $filter_data['department_id'] = $filter_data['department_ids'];
        }
        if (isset($filter_data['exclude_job_ids'])) {
            $filter_data['exclude_id'] = $filter_data['exclude_job_ids'];
        }
        if (isset($filter_data['include_job_ids'])) {
            $filter_data['include_job_id'] = $filter_data['include_job_ids'];
        }
        if (isset($filter_data['job_group_ids'])) {
            $filter_data['job_group_id'] = $filter_data['job_group_ids'];
        }
        if (isset($filter_data['job_item_ids'])) {
            $filter_data['job_item_id'] = $filter_data['job_item_ids'];
        }
        if (isset($filter_data['pay_period_ids'])) {
            $filter_data['pay_period_id'] = $filter_data['pay_period_ids'];
        }
        if (isset($filter_data['start_time'])) {
            $filter_data['start_date'] = $filter_data['start_time'];
        }
        if (isset($filter_data['end_time'])) {
            $filter_data['end_date'] = $filter_data['end_time'];
        }
        $spf = new SchedulePolicyFactory();
        $uf = new UserFactory();
        $bf = new BranchFactory();
        $df = new DepartmentFactory();
        $ugf = new UserGroupFactory();
        $utf = new UserTitleFactory();
        $udf = new UserDateFactory();
        $uwf = new UserWageFactory();
        if (getTTProductEdition() == TT_PRODUCT_PROFESSIONAL) {
            $jf = new JobFactory();
            $jif = new JobItemFactory();
        }
        $ph = array('company_id' => $company_id);
        $query = '
					select
							a.id as id,
							a.id as schedule_id,
							a.status_id as status_id,
							a.start_time as start_time,
							a.end_time as end_time,

							a.user_date_id as user_date_id,
							a.branch_id as branch_id,
							j.name as branch,
							a.department_id as department_id,
							k.name as department,
							a.job_id as job_id,
							a.job_item_id as job_item_id,
							a.total_time as total_time,
							a.schedule_policy_id as schedule_policy_id,
							a.absence_policy_id as absence_policy_id,

							i.name as schedule_policy,

							c.user_id as user_id,
							c.date_stamp as date_stamp,
							c.pay_period_id as pay_period_id,

							d.first_name as first_name,
							d.last_name as last_name,
							d.status_id as user_status_id,
							d.group_id as group_id,
							g.name as group,
							d.title_id as title_id,
							h.name as title,
							d.default_branch_id as default_branch_id,
							e.name as default_branch,
							d.default_department_id as default_department_id,
							f.name as default_department,
							d.created_by as user_created_by,

							m.id as user_wage_id,
							m.effective_date as user_wage_effective_date,

							y.first_name as created_by_first_name,
							y.middle_name as created_by_middle_name,
							y.last_name as created_by_last_name,
							z.first_name as updated_by_first_name,
							z.middle_name as updated_by_middle_name,
							z.last_name as updated_by_last_name';
        if (getTTProductEdition() == TT_PRODUCT_PROFESSIONAL) {
            $query .= ',
						w.name as job_name,
						w.status_id as job_status_id,
						w.manual_id as job_manual_id,
						w.branch_id as job_branch_id,
						w.department_id as job_department_id,
						w.group_id as job_group_id';
        }
        $query .= '
					from 	' . $this->getTable() . ' as a
							LEFT JOIN ' . $spf->getTable() . ' as i ON a.schedule_policy_id = i.id
							LEFT JOIN ' . $udf->getTable() . ' as c ON a.user_date_id = c.id
							LEFT JOIN ' . $uf->getTable() . ' as d ON c.user_id = d.id

							LEFT JOIN ' . $bf->getTable() . ' as e ON ( d.default_branch_id = e.id AND e.deleted = 0)
							LEFT JOIN ' . $df->getTable() . ' as f ON ( d.default_department_id = f.id AND f.deleted = 0)
							LEFT JOIN ' . $ugf->getTable() . ' as g ON ( d.group_id = g.id AND g.deleted = 0 )
							LEFT JOIN ' . $utf->getTable() . ' as h ON ( d.title_id = h.id AND h.deleted = 0 )

							LEFT JOIN ' . $bf->getTable() . ' as j ON ( a.branch_id = j.id AND j.deleted = 0)
							LEFT JOIN ' . $df->getTable() . ' as k ON ( a.department_id = k.id AND k.deleted = 0)

							LEFT JOIN ' . $uwf->getTable() . ' as m ON m.id = (select m.id
																		from ' . $uwf->getTable() . ' as m
																		where m.user_id = c.user_id
																			and m.effective_date <= c.date_stamp
																			and m.deleted = 0
																			order by m.effective_date desc limit 1)
					';
        if (getTTProductEdition() == TT_PRODUCT_PROFESSIONAL) {
            $query .= '	LEFT JOIN ' . $jf->getTable() . ' as w ON a.job_id = w.id';
            $query .= '	LEFT JOIN ' . $jif->getTable() . ' as x ON a.job_item_id = x.id';
        }
        $query .= '
						LEFT JOIN ' . $uf->getTable() . ' as y ON ( a.created_by = y.id AND y.deleted = 0 )
						LEFT JOIN ' . $uf->getTable() . ' as z ON ( a.updated_by = z.id AND z.deleted = 0 )
					WHERE d.company_id = ?';
        if (isset($filter_data['permission_children_ids']) and isset($filter_data['permission_children_ids'][0]) and !in_array(-1, (array) $filter_data['permission_children_ids'])) {
            $query .= ' AND d.id in (' . $this->getListSQL($filter_data['permission_children_ids'], $ph) . ') ';
        }
        if (isset($filter_data['id']) and isset($filter_data['id'][0]) and !in_array(-1, (array) $filter_data['id'])) {
            $query .= ' AND a.id in (' . $this->getListSQL($filter_data['id'], $ph) . ') ';
        }
        if (isset($filter_data['exclude_id']) and isset($filter_data['exclude_id'][0]) and !in_array(-1, (array) $filter_data['exclude_id'])) {
            $query .= ' AND d.id not in (' . $this->getListSQL($filter_data['exclude_id'], $ph) . ') ';
        }
        if (isset($filter_data['user_id']) and isset($filter_data['user_id'][0]) and !in_array(-1, (array) $filter_data['user_id'])) {
            $query .= ' AND c.user_id in (' . $this->getListSQL($filter_data['user_id'], $ph) . ') ';
        }
        if (isset($filter_data['user_status_id']) and isset($filter_data['user_status_id'][0]) and !in_array(-1, (array) $filter_data['user_status_id'])) {
            $query .= ' AND d.status_id in (' . $this->getListSQL($filter_data['user_status_id'], $ph) . ') ';
        }
        if (isset($filter_data['group_id']) and isset($filter_data['group_id'][0]) and !in_array(-1, (array) $filter_data['group_id'])) {
            if (isset($filter_data['include_subgroups']) and (bool) $filter_data['include_subgroups'] == TRUE) {
                $uglf = new UserGroupListFactory();
                $filter_data['group_id'] = $uglf->getByCompanyIdAndGroupIdAndSubGroupsArray($company_id, $filter_data['group_id'], TRUE);
            }
            $query .= ' AND d.group_id in (' . $this->getListSQL($filter_data['group_id'], $ph) . ') ';
        }
        if (isset($filter_data['default_branch_id']) and isset($filter_data['default_branch_id'][0]) and !in_array(-1, (array) $filter_data['default_branch_id'])) {
            $query .= ' AND d.default_branch_id in (' . $this->getListSQL($filter_data['default_branch_id'], $ph) . ') ';
        }
        if (isset($filter_data['default_department_id']) and isset($filter_data['default_department_id'][0]) and !in_array(-1, (array) $filter_data['default_department_id'])) {
            $query .= ' AND d.default_department_id in (' . $this->getListSQL($filter_data['default_department_id'], $ph) . ') ';
        }
        if (isset($filter_data['title_id']) and isset($filter_data['title_id'][0]) and !in_array(-1, (array) $filter_data['title_id'])) {
            $query .= ' AND d.title_id in (' . $this->getListSQL($filter_data['title_id'], $ph) . ') ';
        }
        if (isset($filter_data['branch_id']) and isset($filter_data['branch_id'][0]) and !in_array(-1, (array) $filter_data['branch_id'])) {
            $query .= ' AND a.branch_id in (' . $this->getListSQL($filter_data['branch_id'], $ph) . ') ';
        }
        if (isset($filter_data['department_id']) and isset($filter_data['department_id'][0]) and !in_array(-1, (array) $filter_data['department_id'])) {
            $query .= ' AND a.department_id in (' . $this->getListSQL($filter_data['department_id'], $ph) . ') ';
        }
        if (isset($filter_data['status_id']) and isset($filter_data['status_id'][0]) and !in_array(-1, (array) $filter_data['status_id'])) {
            $query .= ' AND a.status_id in (' . $this->getListSQL($filter_data['status_id'], $ph) . ') ';
        }
        if (isset($filter_data['schedule_policy_id']) and isset($filter_data['schedule_policy_id'][0]) and !in_array(-1, (array) $filter_data['schedule_policy_id'])) {
            $query .= ' AND a.schedule_policy_id in (' . $this->getListSQL($filter_data['schedule_policy_id'], $ph) . ') ';
        }
        if (isset($filter_data['pay_period_id']) and isset($filter_data['pay_period_id'][0]) and !in_array(-1, (array) $filter_data['pay_period_id'])) {
            $query .= ' AND c.pay_period_id in (' . $this->getListSQL($filter_data['pay_period_id'], $ph) . ') ';
        }
        //Use the job_id in the schedule table so we can filter by '0' or No Job
        if (isset($filter_data['include_job_id']) and isset($filter_data['include_job_id'][0]) and !in_array(-1, (array) $filter_data['include_job_id'])) {
            $query .= ' AND a.job_id in (' . $this->getListSQL($filter_data['include_job_id'], $ph) . ') ';
        }
        if (isset($filter_data['exclude_job_id']) and isset($filter_data['exclude_job_id'][0]) and !in_array(-1, (array) $filter_data['exclude_job_id'])) {
            $query .= ' AND a.job_id not in (' . $this->getListSQL($filter_data['exclude_job_id'], $ph) . ') ';
        }
        if (isset($filter_data['job_group_id']) and isset($filter_data['job_group_id'][0]) and !in_array(-1, (array) $filter_data['job_group_id'])) {
            if (isset($filter_data['include_job_subgroups']) and (bool) $filter_data['include_job_subgroups'] == TRUE) {
                $uglf = new UserGroupListFactory();
                $filter_data['job_group_id'] = $uglf->getByCompanyIdAndGroupIdAndjob_subgroupsArray($company_id, $filter_data['job_group_id'], TRUE);
            }
            $query .= ' AND w.group_id in (' . $this->getListSQL($filter_data['job_group_id'], $ph) . ') ';
        }
        if (isset($filter_data['job_item_id']) and isset($filter_data['job_item_id'][0]) and !in_array(-1, (array) $filter_data['job_item_id'])) {
            $query .= ' AND b.job_item_id in (' . $this->getListSQL($filter_data['job_item_id'], $ph) . ') ';
        }
        if (isset($filter_data['start_date']) and trim($filter_data['start_date']) != '') {
            $ph[] = $this->db->BindTimeStamp($filter_data['start_date']);
            $query .= ' AND a.start_time >= ?';
        }
        if (isset($filter_data['end_date']) and trim($filter_data['end_date']) != '') {
            $ph[] = $this->db->BindTimeStamp($filter_data['end_date']);
            $query .= ' AND a.start_time <= ?';
        }
        if (isset($filter_data['created_by']) and isset($filter_data['created_by'][0]) and !in_array(-1, (array) $filter_data['created_by'])) {
            $query .= ' AND a.created_by in (' . $this->getListSQL($filter_data['created_by'], $ph) . ') ';
        }
        if (isset($filter_data['updated_by']) and isset($filter_data['updated_by'][0]) and !in_array(-1, (array) $filter_data['updated_by'])) {
            $query .= ' AND a.updated_by in (' . $this->getListSQL($filter_data['updated_by'], $ph) . ') ';
        }
        $query .= '
						AND (a.deleted = 0 AND c.deleted = 0 AND d.deleted = 0)
					';
        $query .= $this->getWhereSQL($where);
        $query .= $this->getSortSQL($order, $strict, $additional_order_fields);
        Debug::text('Query: ' . $query, __FILE__, __LINE__, __METHOD__, 10);
        if ($limit == NULL) {
            $this->rs = $this->db->Execute($query, $ph);
        } else {
            $this->rs = $this->db->PageExecute($query, $limit, $page, $ph);
        }
        return $this;
    }
    function getByUserIdAndFolder($user_id, $folder, $limit = NULL, $page = NULL, $where = NULL, $order = NULL)
    {
        if ($user_id == '') {
            return FALSE;
        }
        $strict = TRUE;
        if ($order == NULL) {
            $strict = FALSE;
            $order = array('a.status_id' => '= 10 desc', 'a.created_date' => 'desc');
        }
        //Folder is: INBOX, SENT
        $key = Option::getByValue($folder, $this->getOptions('folder'));
        if ($key !== FALSE) {
            $folder = $key;
        }
        $rf = new RequestFactory();
        $uf = new UserFactory();
        $udf = new UserDateFactory();
        $pptsvf = new PayPeriodTimeSheetVerifyFactory();
        $ph = array('user_id' => $user_id);
        $folder_sent_query = NULL;
        $folder_inbox_query = NULL;
        $folder_inbox_query_a = NULL;
        $folder_inbox_query_ab = NULL;
        $folder_inbox_query_b = NULL;
        $folder_inbox_query_c = NULL;
        if ($folder == 10) {
            $ph['id'] = $user_id;
            $ph['created_by1'] = $user_id;
            $ph['created_by2'] = $user_id;
            $ph['created_by3'] = $user_id;
            $ph['created_by4'] = $user_id;
            $folder_inbox_query = ' AND a.created_by != ?';
            $folder_inbox_query_a = ' OR d.id = ?';
            $folder_inbox_query_ab = ' OR e.user_id = ?';
            //$folder_inbox_query_b = ' OR a.parent_id in ( select parent_id FROM '. $this->getTable() .' WHERE created_by = '. $user_id .' ) ';
            $folder_inbox_query_b = ' OR a.parent_id in ( select parent_id FROM ' . $this->getTable() . ' WHERE created_by = ? AND parent_id != 0 ) ';
            $folder_inbox_query_c = ' OR a.parent_id in ( select id FROM ' . $this->getTable() . ' WHERE created_by = ? AND parent_id = 0 ) ';
        } elseif ($folder == 20) {
            $ph['created_by4'] = $user_id;
            $folder_sent_query = ' OR a.created_by = ?';
        }
        //Need to include all threads that user has posted to.
        $query = '
					SELECT a.*,
							CASE WHEN a.object_type_id = 5 THEN d.id WHEN a.object_type_id = 50 THEN c.user_id WHEN a.object_type_id = 90 THEN e.user_id END as sent_to_user_id
					FROM ' . $this->getTable() . ' as a
						LEFT JOIN ' . $uf->getTable() . ' as d ON a.object_type_id = 5 AND a.object_id = d.id
						LEFT JOIN ' . $uf->getTable() . ' as f ON a.created_by = f.id
						LEFT JOIN ' . $rf->getTable() . ' as b ON a.object_type_id = 50 AND a.object_id = b.id
						LEFT JOIN ' . $udf->getTable() . ' as c ON b.user_date_id = c.id
						LEFT JOIN ' . $pptsvf->getTable() . ' as e ON a.object_type_id = 90 AND a.object_id = e.id
					WHERE
							a.object_type_id in (5,50,90)
							AND
							(

								(
									(
										c.user_id = ?
										' . $folder_sent_query . '
										' . $folder_inbox_query_a . '
										' . $folder_inbox_query_ab . '
										' . $folder_inbox_query_b . '
										' . $folder_inbox_query_c . '
									)
									' . $folder_inbox_query . '
								)
							)

						AND ( a.deleted = 0 AND f.deleted = 0
								AND ( b.id IS NULL OR ( b.id IS NOT NULL AND b.deleted = 0 ) )
								AND ( c.id IS NULL OR ( c.id IS NOT NULL AND c.deleted = 0 ) )
								AND ( d.id IS NULL OR ( d.id IS NOT NULL AND d.deleted = 0 ) )
								AND ( e.id IS NULL OR ( e.id IS NOT NULL AND e.deleted = 0 ) )
								AND NOT ( b.id IS NULL AND c.id IS NULL AND d.id IS NULL AND e.id IS NULL )
							)
					';
        $query .= $this->getWhereSQL($where);
        $query .= $this->getSortSQL($order, $strict, array('sent_to_user_id'));
        //Debug::text('Query: '. $query , __FILE__, __LINE__, __METHOD__,9);
        if ($limit == NULL) {
            //Run query without limit
            $this->rs = $this->db->Execute($query, $ph);
        } else {
            $this->rs = $this->db->PageExecute($query, $limit, $page, $ph);
        }
        return $this;
    }
    function getAPISearchByCompanyIdAndArrayCriteria($company_id, $filter_data, $limit = NULL, $page = NULL, $where = NULL, $order = NULL)
    {
        if ($company_id == '') {
            return FALSE;
        }
        if (!is_array($order)) {
            //Use Filter Data ordering if its set.
            if (isset($filter_data['sort_column']) and $filter_data['sort_order']) {
                $order = array(Misc::trimSortPrefix($filter_data['sort_column']) => $filter_data['sort_order']);
            }
        }
        if (isset($filter_data['user_group_id'])) {
            $filter_data['group_id'] = $filter_data['user_group_id'];
        }
        if (isset($filter_data['user_title_id'])) {
            $filter_data['title_id'] = $filter_data['user_title_id'];
        }
        if (isset($filter_data['include_user_id'])) {
            $filter_data['user_id'] = $filter_data['include_user_id'];
        }
        if (isset($filter_data['exception_policy_severity_id'])) {
            $filter_data['severity_id'] = $filter_data['exception_policy_severity_id'];
        }
        $additional_order_fields = array('d.name', 'e.name', 'f.name', 'g.name', 'h.status_id', 'i.severity_id', 'i.type_id', 'c.first_name', 'c.last_name', 'c.country', 'c.province', 'b.date_stamp', 'pgf.name', 'pscf.name', 'ppsf.name');
        $sort_column_aliases = array('status' => 'status_id', 'type' => 'type_id');
        $order = $this->getColumnsFromAliases($order, $sort_column_aliases);
        if ($order == NULL) {
            //$order = array( 'status_id' => 'asc', 'last_name' => 'asc', 'first_name' => 'asc', 'middle_name' => 'asc');
            $order = array('i.severity_id' => 'desc', 'c.last_name' => 'asc', 'b.date_stamp' => 'asc', 'i.type_id' => 'asc');
            $strict = FALSE;
        } else {
            //Do order by column conversions, because if we include these columns in the SQL
            //query, they contaminate the data array.
            if (isset($order['default_branch'])) {
                $order['d.name'] = $order['default_branch'];
                unset($order['default_branch']);
            }
            if (isset($order['default_department'])) {
                $order['e.name'] = $order['default_department'];
                unset($order['default_department']);
            }
            if (isset($order['user_group'])) {
                $order['f.name'] = $order['user_group'];
                unset($order['user_group']);
            }
            if (isset($order['title'])) {
                $order['g.name'] = $order['title'];
                unset($order['title']);
            }
            if (isset($order['exception_policy_type_id'])) {
                $order['i.type_id'] = $order['exception_policy_type_id'];
                unset($order['exception_policy_type_id']);
            }
            if (isset($order['severity_id'])) {
                $order['i.severity_id'] = $order['severity_id'];
                unset($order['severity_id']);
            }
            if (isset($order['severity'])) {
                $order['i.severity_id'] = $order['severity'];
                unset($order['severity']);
            }
            if (isset($order['exception_policy_type'])) {
                $order['i.type_id'] = $order['exception_policy_type'];
                unset($order['exception_policy_type']);
            }
            if (isset($order['exception_policy_type_id'])) {
                $order['i.type_id'] = $order['exception_policy_type_id'];
                unset($order['exception_policy_type_id']);
            }
            if (isset($order['first_name'])) {
                $order['c.first_name'] = $order['first_name'];
                unset($order['first_name']);
            }
            if (isset($order['last_name'])) {
                $order['c.last_name'] = $order['last_name'];
                unset($order['last_name']);
            }
            if (isset($order['country'])) {
                $order['c.country'] = $order['country'];
                unset($order['country']);
            }
            if (isset($order['province'])) {
                $order['c.province'] = $order['province'];
                unset($order['province']);
            }
            if (isset($order['date_stamp'])) {
                $order['b.date_stamp'] = $order['date_stamp'];
                unset($order['date_stamp']);
            }
            if (isset($order['policy_group'])) {
                $order['pgf.name'] = $order['policy_group'];
                unset($order['policy_group']);
            }
            if (isset($order['permission_group'])) {
                $order['pscf.name'] = $order['permission_group'];
                unset($order['permission_group']);
            }
            if (isset($order['pay_period_schedule'])) {
                $order['ppsf.name'] = $order['pay_period_schedule'];
                unset($order['pay_period_schedule']);
            }
            //Always sort by last name,first name after other columns
            if (!isset($order['c.last_name'])) {
                $order['c.last_name'] = 'asc';
            }
            if (!isset($order['c.first_name'])) {
                $order['c.first_name'] = 'asc';
            }
            if (!isset($order['b.date_stamp'])) {
                $order['b.date_stamp'] = 'asc';
            }
            if (!isset($order['i.severity_id'])) {
                $order['i.severity_id'] = 'desc';
            }
            $strict = TRUE;
        }
        //Debug::Arr($order,'Order Data:', __FILE__, __LINE__, __METHOD__,10);
        //Debug::Arr($filter_data,'Filter Data:', __FILE__, __LINE__, __METHOD__,10);
        $udf = new UserDateFactory();
        $uf = new UserFactory();
        $bf = new BranchFactory();
        $df = new DepartmentFactory();
        $ugf = new UserGroupFactory();
        $utf = new UserTitleFactory();
        $ppf = new PayPeriodFactory();
        $ppsf = new PayPeriodScheduleFactory();
        $epf = new ExceptionPolicyFactory();
        $epcf = new ExceptionPolicyControlFactory();
        $pguf = new PolicyGroupUserFactory();
        $pgf = new PolicyGroupFactory();
        $pf = new PunchFactory();
        $pcf = new PunchControlFactory();
        $pscf = new PermissionControlFactory();
        $puf = new PermissionUserFactory();
        $ph = array('company_id' => $company_id);
        $query = '
					select 	a.*,
							b.date_stamp as date_stamp,
							b.pay_period_id as pay_period_id,
							h.pay_period_schedule_id as pay_period_schedule_id,
							i.severity_id as severity_id,
							i.type_id as exception_policy_type_id,
							b.user_id as user_id,
                            h.start_date as pay_period_start_date,
							h.end_date as pay_period_end_date,
							h.transaction_date as pay_period_transaction_date,
							c.first_name as first_name,
							c.last_name as last_name,
                            c.country as country,
                            c.province as province,
							c.status_id as user_status_id,
							c.group_id as group_id,
							f.name as "group",
							c.title_id as title_id,
							g.name as title,
							c.default_branch_id as default_branch_id,
							d.name as default_branch,
							c.default_department_id as default_department_id,
							e.name as default_department,

							pcf.branch_id as branch_id,
							bf.name as branch,
							pcf.department_id as department_id,
							df.name as department,
                            pgf.name as policy_group,
                            pscf.name as permission_group,
                            ppsf.name as pay_period_schedule,

							y.first_name as created_by_first_name,
							y.middle_name as created_by_middle_name,
							y.last_name as created_by_last_name,
							z.first_name as updated_by_first_name,
							z.middle_name as updated_by_middle_name,
							z.last_name as updated_by_last_name
					from 	' . $this->getTable() . ' as a
						LEFT JOIN ' . $pf->getTable() . ' as pf ON ( a.punch_id IS NOT NULL AND a.punch_id = pf.id AND pf.deleted = 0)
						LEFT JOIN ' . $pcf->getTable() . ' as pcf ON ( ( ( pf.id IS NOT NULL AND pf.punch_control_id = pcf.id ) OR ( a.punch_control_id is NOT NULL AND a.punch_control_id = pcf.id ) ) AND pcf.deleted = 0)
						LEFT JOIN ' . $bf->getTable() . ' as bf ON pcf.branch_id = bf.id
						LEFT JOIN ' . $df->getTable() . ' as df ON pcf.department_id = df.id

						LEFT JOIN ' . $udf->getTable() . ' as b ON a.user_date_id = b.id
						LEFT JOIN ' . $uf->getTable() . ' as c ON b.user_id = c.id
						LEFT JOIN ' . $bf->getTable() . ' as d ON c.default_branch_id = d.id
						LEFT JOIN ' . $df->getTable() . ' as e ON c.default_department_id = e.id
						LEFT JOIN ' . $ugf->getTable() . ' as f ON c.group_id = f.id
						LEFT JOIN ' . $utf->getTable() . ' as g ON c.title_id = g.id
						LEFT JOIN ' . $ppf->getTable() . ' as h ON b.pay_period_id = h.id
                        LEFT JOIN ' . $ppsf->getTable() . ' as ppsf ON ppsf.id = h.pay_period_schedule_id
						LEFT JOIN ' . $epf->getTable() . ' as i ON a.exception_policy_id = i.id
                        LEFT JOIN ' . $epcf->getTable() . ' as epcf ON epcf.id = i.exception_policy_control_id
						LEFT JOIN ' . $pguf->getTable() . ' as pguf ON b.user_id = pguf.user_id
                        LEFT JOIN ' . $pgf->getTable() . ' as pgf ON pguf.policy_group_id = pgf.id
                        LEFT JOIN ' . $puf->getTable() . ' as puf ON c.id = puf.user_id
                        LEFT JOIN ' . $pscf->getTable() . ' as pscf ON pscf.id = puf.permission_control_id
						LEFT JOIN ' . $uf->getTable() . ' as y ON ( a.created_by = y.id AND y.deleted = 0 )
						LEFT JOIN ' . $uf->getTable() . ' as z ON ( a.updated_by = z.id AND z.deleted = 0 )
					where	c.company_id = ?
					';
        if (isset($filter_data['permission_children_ids']) and isset($filter_data['permission_children_ids'][0]) and !in_array(-1, (array) $filter_data['permission_children_ids'])) {
            $query .= ' AND c.id in (' . $this->getListSQL($filter_data['permission_children_ids'], $ph) . ') ';
        }
        if (isset($filter_data['id']) and isset($filter_data['id'][0]) and !in_array(-1, (array) $filter_data['id'])) {
            $query .= ' AND a.id in (' . $this->getListSQL($filter_data['id'], $ph) . ') ';
        }
        if (isset($filter_data['user_id']) and isset($filter_data['user_id'][0]) and !in_array(-1, (array) $filter_data['user_id'])) {
            $query .= ' AND c.id in (' . $this->getListSQL($filter_data['user_id'], $ph) . ') ';
        }
        $query .= isset($filter_data['exclude_user_id']) ? $this->getWhereClauseSQL('c.id', $filter_data['exclude_user_id'], 'not_numeric_list', $ph) : NULL;
        if (isset($filter_data['user_status_id']) and isset($filter_data['user_status_id'][0]) and !in_array(-1, (array) $filter_data['user_status_id'])) {
            $query .= ' AND c.status_id in (' . $this->getListSQL($filter_data['user_status_id'], $ph) . ') ';
        }
        if (isset($filter_data['type_id']) and isset($filter_data['type_id'][0]) and !in_array(-1, (array) $filter_data['type_id'])) {
            $query .= ' AND a.type_id in (' . $this->getListSQL($filter_data['type_id'], $ph) . ') ';
        }
        if (isset($filter_data['severity_id']) and isset($filter_data['severity_id'][0]) and !in_array(-1, (array) $filter_data['severity_id'])) {
            $query .= ' AND i.severity_id in (' . $this->getListSQL($filter_data['severity_id'], $ph) . ') ';
        }
        if (isset($filter_data['exception_policy_type_id']) and isset($filter_data['exception_policy_type_id'][0]) and !in_array(-1, (array) $filter_data['exception_policy_type_id'])) {
            $query .= ' AND i.type_id in (' . $this->getListSQL($filter_data['exception_policy_type_id'], $ph) . ') ';
        }
        if (isset($filter_data['pay_period_id']) and isset($filter_data['pay_period_id'][0]) and !in_array(-1, (array) $filter_data['pay_period_id'])) {
            $query .= ' AND b.pay_period_id in (' . $this->getListSQL($filter_data['pay_period_id'], $ph) . ') ';
        }
        if (isset($filter_data['pay_period_status_id']) and isset($filter_data['pay_period_status_id'][0]) and !in_array(-1, (array) $filter_data['pay_period_status_id'])) {
            $query .= ' AND h.status_id in (' . $this->getListSQL($filter_data['pay_period_status_id'], $ph) . ') ';
        }
        if (isset($filter_data['group_id']) and isset($filter_data['group_id'][0]) and !in_array(-1, (array) $filter_data['group_id'])) {
            if (isset($filter_data['include_subgroups']) and (bool) $filter_data['include_subgroups'] == TRUE) {
                $uglf = new UserGroupListFactory();
                $filter_data['group_id'] = $uglf->getByCompanyIdAndGroupIdAndSubGroupsArray($company_id, $filter_data['group_id'], TRUE);
            }
            $query .= ' AND c.group_id in (' . $this->getListSQL($filter_data['group_id'], $ph) . ') ';
        }
        if (isset($filter_data['default_branch_id']) and isset($filter_data['default_branch_id'][0]) and !in_array(-1, (array) $filter_data['default_branch_id'])) {
            $query .= ' AND c.default_branch_id in (' . $this->getListSQL($filter_data['default_branch_id'], $ph) . ') ';
        }
        if (isset($filter_data['default_department_id']) and isset($filter_data['default_department_id'][0]) and !in_array(-1, (array) $filter_data['default_department_id'])) {
            $query .= ' AND c.default_department_id in (' . $this->getListSQL($filter_data['default_department_id'], $ph) . ') ';
        }
        if (isset($filter_data['title_id']) and isset($filter_data['title_id'][0]) and !in_array(-1, (array) $filter_data['title_id'])) {
            $query .= ' AND c.title_id in (' . $this->getListSQL($filter_data['title_id'], $ph) . ') ';
        }
        if (isset($filter_data['branch_id']) and isset($filter_data['branch_id'][0]) and !in_array(-1, (array) $filter_data['branch_id'])) {
            $query .= ' AND pcf.branch_id in (' . $this->getListSQL($filter_data['branch_id'], $ph) . ') ';
        }
        if (isset($filter_data['department_id']) and isset($filter_data['department_id'][0]) and !in_array(-1, (array) $filter_data['department_id'])) {
            $query .= ' AND pcf.department_id in (' . $this->getListSQL($filter_data['department_id'], $ph) . ') ';
        }
        if (isset($filter_data['start_date']) and trim($filter_data['start_date']) != '') {
            $ph[] = $this->db->BindDate($filter_data['start_date']);
            $query .= ' AND b.date_stamp >= ?';
        }
        if (isset($filter_data['end_date']) and trim($filter_data['end_date']) != '') {
            $ph[] = $this->db->BindDate($filter_data['end_date']);
            $query .= ' AND b.date_stamp <= ?';
        }
        $query .= isset($filter_data['created_by']) ? $this->getWhereClauseSQL(array('a.created_by', 'y.first_name', 'y.last_name'), $filter_data['created_by'], 'user_id_or_name', $ph) : NULL;
        $query .= isset($filter_data['updated_by']) ? $this->getWhereClauseSQL(array('a.updated_by', 'z.first_name', 'z.last_name'), $filter_data['updated_by'], 'user_id_or_name', $ph) : NULL;
        //Make sure we accept exception rows assign to pay_period_id = 0 (no pay period), as this can happen when punches exist in the future.
        $query .= '
						AND ( a.deleted = 0 AND b.deleted = 0 AND c.deleted = 0 AND pgf.deleted = 0 AND ( h.deleted = 0 OR h.deleted is NULL ) )
					';
        $query .= $this->getWhereSQL($where);
        $query .= $this->getSortSQL($order, $strict, $additional_order_fields);
        //Debug::Arr($ph, 'Query: '. $query, __FILE__, __LINE__, __METHOD__,10);
        $this->ExecuteSQL($query, $ph, $limit, $page);
        return $this;
    }
    function getAPISearchByCompanyIdAndArrayCriteria($company_id, $filter_data, $limit = NULL, $page = NULL, $where = NULL, $order = NULL)
    {
        if ($company_id == '') {
            return FALSE;
        }
        if (!is_array($order)) {
            //Use Filter Data ordering if its set.
            if (isset($filter_data['sort_column']) and $filter_data['sort_order']) {
                $order = array(Misc::trimSortPrefix($filter_data['sort_column']) => $filter_data['sort_order']);
            }
        }
        if (isset($filter_data['user_date_total_type_id'])) {
            $filter_data['type_id'] = $filter_data['user_date_total_type_id'];
        }
        $additional_order_fields = array('first_name', 'last_name', 'date_stamp', 'time_stamp', 'type_id', 'status_id', 'branch', 'department', 'default_branch', 'default_department', 'group', 'title');
        if ($order == NULL) {
            $order = array('c.date_stamp' => 'asc', 'a.status_id' => 'asc', 'a.type_id' => 'asc', 'a.total_time' => 'asc', 'a.status_id' => 'asc');
            $strict = FALSE;
        } else {
            $strict = FALSE;
        }
        //Debug::Arr($order,'Order Data:', __FILE__, __LINE__, __METHOD__,10);
        //Debug::Arr($filter_data,'Filter Data:', __FILE__, __LINE__, __METHOD__,10);
        if (isset($filter_data['exclude_user_ids'])) {
            $filter_data['exclude_id'] = $filter_data['exclude_user_ids'];
        }
        if (isset($filter_data['include_user_ids'])) {
            $filter_data['user_id'] = $filter_data['include_user_ids'];
        }
        if (isset($filter_data['user_title_ids'])) {
            $filter_data['title_id'] = $filter_data['user_title_ids'];
        }
        if (isset($filter_data['group_ids'])) {
            $filter_data['group_id'] = $filter_data['group_ids'];
        }
        if (isset($filter_data['branch_ids'])) {
            $filter_data['default_branch_id'] = $filter_data['branch_ids'];
        }
        if (isset($filter_data['department_ids'])) {
            $filter_data['default_department_id'] = $filter_data['department_ids'];
        }
        if (isset($filter_data['pay_period_ids'])) {
            $filter_data['pay_period_id'] = $filter_data['pay_period_ids'];
        }
        if (isset($filter_data['exclude_job_ids'])) {
            $filter_data['exclude_id'] = $filter_data['exclude_job_ids'];
        }
        if (isset($filter_data['include_job_ids'])) {
            $filter_data['include_job_id'] = $filter_data['include_job_ids'];
        }
        if (isset($filter_data['job_group_ids'])) {
            $filter_data['job_group_id'] = $filter_data['job_group_ids'];
        }
        if (isset($filter_data['job_item_ids'])) {
            $filter_data['job_item_id'] = $filter_data['job_item_ids'];
        }
        $uf = new UserFactory();
        $udf = new UserDateFactory();
        $uwf = new UserWageFactory();
        $bf = new BranchFactory();
        $df = new DepartmentFactory();
        $ugf = new UserGroupFactory();
        $utf = new UserTitleFactory();
        $otpf = new OverTimePolicyFactory();
        $apf = new AbsencePolicyFactory();
        $ppf = new PremiumPolicyFactory();
        $mpf = new MealPolicyFactory();
        $bpf = new BreakPolicyFactory();
        if (getTTProductEdition() >= TT_PRODUCT_CORPORATE) {
            $jf = new JobFactory();
            $jif = new JobItemFactory();
        }
        $ph = array('company_id' => $company_id);
        $query = '
					select
							a.id as id,
							a.user_date_id as user_date_id,
							a.type_id as type_id,
							a.status_id as status_id,
							a.punch_control_id as punch_control_id,

							a.over_time_policy_id as over_time_policy_id,
							otpf.name as over_time_policy,
							a.absence_policy_id as absence_policy_id,
							apf.name as absence_policy,
							apf.type_id as absence_policy_type_id,
							a.premium_policy_id as premium_policy_id,
							ppf.name as premium_policy,
							a.meal_policy_id as meal_policy_id,
							mpf.name as meal_policy,
							a.break_policy_id as break_policy_id,
							bpf.name as break_policy,

							a.start_time_stamp as start_time_stamp,
							a.end_time_stamp as end_time_stamp,

							a.override as override,

							a.branch_id as branch_id,
							j.name as branch,
							a.department_id as department_id,
							k.name as department,
							a.job_id as job_id,
							a.job_item_id as job_item_id,
							a.quantity as quantity,
							a.bad_quantity as bad_quantity,
							a.total_time as total_time,
							a.actual_total_time as actual_total_time,

							c.user_id as user_id,
							c.date_stamp as date_stamp,
							c.pay_period_id as pay_period_id,

							d.first_name as first_name,
							d.last_name as last_name,
							d.status_id as user_status_id,
							d.group_id as group_id,
							g.name as "group",
							d.title_id as title_id,
							h.name as title,
							d.default_branch_id as default_branch_id,
							e.name as default_branch,
							d.default_department_id as default_department_id,
							f.name as default_department,
							d.created_by as user_created_by,

							z.id as user_wage_id,
							z.effective_date as user_wage_effective_date ';
        if (getTTProductEdition() >= TT_PRODUCT_CORPORATE) {
            $query .= ',
						x.name as job,
						x.name as job_name,
						x.status_id as job_status_id,
						x.manual_id as job_manual_id,
						x.branch_id as job_branch_id,
						x.department_id as job_department_id,
						x.group_id as job_group_id,
						y.name as job_item';
        }
        $query .= '
					from 	' . $this->getTable() . ' as a
							LEFT JOIN ' . $udf->getTable() . ' as c ON a.user_date_id = c.id
							LEFT JOIN ' . $uf->getTable() . ' as d ON c.user_id = d.id

							LEFT JOIN ' . $bf->getTable() . ' as e ON ( d.default_branch_id = e.id AND e.deleted = 0)
							LEFT JOIN ' . $df->getTable() . ' as f ON ( d.default_department_id = f.id AND f.deleted = 0)
							LEFT JOIN ' . $ugf->getTable() . ' as g ON ( d.group_id = g.id AND g.deleted = 0 )
							LEFT JOIN ' . $utf->getTable() . ' as h ON ( d.title_id = h.id AND h.deleted = 0 )

							LEFT JOIN ' . $bf->getTable() . ' as j ON ( a.branch_id = j.id AND j.deleted = 0)
							LEFT JOIN ' . $df->getTable() . ' as k ON ( a.department_id = k.id AND k.deleted = 0)

							LEFT JOIN ' . $otpf->getTable() . ' as otpf ON ( a.over_time_policy_id > 0 AND a.over_time_policy_id = otpf.id AND otpf.deleted = 0 )
							LEFT JOIN ' . $apf->getTable() . ' as apf ON ( a.absence_policy_id > 0 AND a.absence_policy_id = apf.id AND apf.deleted = 0 )
							LEFT JOIN ' . $ppf->getTable() . ' as ppf ON ( a.premium_policy_id > 0 AND a.premium_policy_id = ppf.id AND ppf.deleted = 0 )
							LEFT JOIN ' . $mpf->getTable() . ' as mpf ON ( a.meal_policy_id > 0 AND a.meal_policy_id = mpf.id AND mpf.deleted = 0 )
							LEFT JOIN ' . $bpf->getTable() . ' as bpf ON ( a.break_policy_id > 0 AND a.break_policy_id = bpf.id AND bpf.deleted = 0 )

							LEFT JOIN ' . $uwf->getTable() . ' as z ON z.id = (select z.id
																		from ' . $uwf->getTable() . ' as z
																		where z.user_id = c.user_id
																			and z.effective_date <= c.date_stamp
																			and z.wage_group_id = 0
																			and z.deleted = 0
																			order by z.effective_date desc LiMiT 1)
					';
        if (getTTProductEdition() >= TT_PRODUCT_CORPORATE) {
            $query .= '	LEFT JOIN ' . $jf->getTable() . ' as x ON a.job_id = x.id';
            $query .= '	LEFT JOIN ' . $jif->getTable() . ' as y ON a.job_item_id = y.id';
        }
        $query .= '	WHERE d.company_id = ?';
        $query .= isset($filter_data['permission_children_ids']) ? $this->getWhereClauseSQL('d.id', $filter_data['permission_children_ids'], 'numeric_list', $ph) : NULL;
        $query .= isset($filter_data['id']) ? $this->getWhereClauseSQL('a.id', $filter_data['id'], 'numeric_list', $ph) : NULL;
        $query .= isset($filter_data['exclude_id']) ? $this->getWhereClauseSQL('d.id', $filter_data['exclude_id'], 'not_numeric_list', $ph) : NULL;
        $query .= isset($filter_data['user_id']) ? $this->getWhereClauseSQL('c.user_id', $filter_data['user_id'], 'numeric_list', $ph) : NULL;
        $query .= isset($filter_data['user_status_id']) ? $this->getWhereClauseSQL('d.status_id', $filter_data['user_status_id'], 'numeric_list', $ph) : NULL;
        if (isset($filter_data['include_subgroups']) and (bool) $filter_data['include_subgroups'] == TRUE) {
            $uglf = new UserGroupListFactory();
            $filter_data['user_group_id'] = $uglf->getByCompanyIdAndGroupIdAndSubGroupsArray($company_id, $filter_data['user_group_id'], TRUE);
        }
        $query .= isset($filter_data['user_group_id']) ? $this->getWhereClauseSQL('d.group_id', $filter_data['user_group_id'], 'numeric_list', $ph) : NULL;
        $query .= isset($filter_data['user_group']) ? $this->getWhereClauseSQL('g.name', $filter_data['user_group'], 'text', $ph) : NULL;
        $query .= isset($filter_data['group_id']) ? $this->getWhereClauseSQL('d.group_id', $filter_data['group_id'], 'numeric_list', $ph) : NULL;
        $query .= isset($filter_data['default_branch_id']) ? $this->getWhereClauseSQL('d.default_branch_id', $filter_data['default_branch_id'], 'numeric_list', $ph) : NULL;
        $query .= isset($filter_data['default_department_id']) ? $this->getWhereClauseSQL('d.default_department_id', $filter_data['default_department_id'], 'numeric_list', $ph) : NULL;
        $query .= isset($filter_data['title_id']) ? $this->getWhereClauseSQL('d.title_id', $filter_data['title_id'], 'numeric_list', $ph) : NULL;
        $query .= isset($filter_data['status_id']) ? $this->getWhereClauseSQL('a.status_id', $filter_data['status_id'], 'numeric_list', $ph) : NULL;
        $query .= isset($filter_data['type_id']) ? $this->getWhereClauseSQL('a.type_id', $filter_data['type_id'], 'numeric_list', $ph) : NULL;
        $query .= isset($filter_data['pay_period_id']) ? $this->getWhereClauseSQL('c.pay_period_id', $filter_data['pay_period_id'], 'numeric_list', $ph) : NULL;
        $query .= isset($filter_data['branch_id']) ? $this->getWhereClauseSQL('a.branch_id', $filter_data['branch_id'], 'numeric_list', $ph) : NULL;
        $query .= isset($filter_data['department_id']) ? $this->getWhereClauseSQL('a.department_id', $filter_data['department_id'], 'numeric_list', $ph) : NULL;
        $query .= isset($filter_data['job_id']) ? $this->getWhereClauseSQL('a.job_id', $filter_data['job_id'], 'numeric_list', $ph) : NULL;
        $query .= isset($filter_data['include_job_id']) ? $this->getWhereClauseSQL('a.job_id', $filter_data['include_job_id'], 'numeric_list', $ph) : NULL;
        $query .= isset($filter_data['exclude_job_id']) ? $this->getWhereClauseSQL('a.job_id', $filter_data['exclude_job_id'], 'not_numeric_list', $ph) : NULL;
        $query .= isset($filter_data['job_group_id']) ? $this->getWhereClauseSQL('x.group_id', $filter_data['job_group_id'], 'numeric_list', $ph) : NULL;
        $query .= isset($filter_data['job_item_id']) ? $this->getWhereClauseSQL('a.job_item_id', $filter_data['job_item_id'], 'numeric_list', $ph) : NULL;
        $query .= isset($filter_data['include_job_item_id']) ? $this->getWhereClauseSQL('a.job_item_id', $filter_data['include_job_item_id'], 'numeric_list', $ph) : NULL;
        $query .= isset($filter_data['exclude_job_item_id']) ? $this->getWhereClauseSQL('a.job_item_id', $filter_data['exclude_job_item_id'], 'not_numeric_list', $ph) : NULL;
        /*
        		if ( isset($filter_data['permission_children_ids']) AND isset($filter_data['permission_children_ids'][0]) AND !in_array(-1, (array)$filter_data['permission_children_ids']) ) {
        			$query  .=	' AND d.id in ('. $this->getListSQL($filter_data['permission_children_ids'], $ph) .') ';
        		}
        		if ( isset($filter_data['id']) AND isset($filter_data['id'][0]) AND !in_array(-1, (array)$filter_data['id']) ) {
        			$query  .=	' AND a.id in ('. $this->getListSQL($filter_data['id'], $ph) .') ';
        		}
        		if ( isset($filter_data['exclude_id']) AND isset($filter_data['exclude_id'][0]) AND !in_array(-1, (array)$filter_data['exclude_id']) ) {
        			$query  .=	' AND d.id not in ('. $this->getListSQL($filter_data['exclude_id'], $ph) .') ';
        		}
        		if ( isset($filter_data['user_id']) AND isset($filter_data['user_id'][0]) AND !in_array(-1, (array)$filter_data['user_id']) ) {
        			$query  .=	' AND c.user_id in ('. $this->getListSQL($filter_data['user_id'], $ph) .') ';
        		}
        
        		if ( isset($filter_data['user_status_id']) AND isset($filter_data['user_status_id'][0]) AND !in_array(-1, (array)$filter_data['user_status_id']) ) {
        			$query  .=	' AND d.status_id in ('. $this->getListSQL($filter_data['user_status_id'], $ph) .') ';
        		}
        		if ( isset($filter_data['group_id']) AND isset($filter_data['group_id'][0]) AND !in_array(-1, (array)$filter_data['group_id']) ) {
        			if ( isset($filter_data['include_subgroups']) AND (bool)$filter_data['include_subgroups'] == TRUE ) {
        				$uglf = new UserGroupListFactory();
        				$filter_data['group_id'] = $uglf->getByCompanyIdAndGroupIdAndSubGroupsArray( $company_id, $filter_data['group_id'], TRUE);
        			}
        			$query  .=	' AND d.group_id in ('. $this->getListSQL($filter_data['group_id'], $ph) .') ';
        		}
        		if ( isset($filter_data['default_branch_id']) AND isset($filter_data['default_branch_id'][0]) AND !in_array(-1, (array)$filter_data['default_branch_id']) ) {
        			$query  .=	' AND d.default_branch_id in ('. $this->getListSQL($filter_data['default_branch_id'], $ph) .') ';
        		}
        		if ( isset($filter_data['default_department_id']) AND isset($filter_data['default_department_id'][0]) AND !in_array(-1, (array)$filter_data['default_department_id']) ) {
        			$query  .=	' AND d.default_department_id in ('. $this->getListSQL($filter_data['default_department_id'], $ph) .') ';
        		}
        		if ( isset($filter_data['title_id']) AND isset($filter_data['title_id'][0]) AND !in_array(-1, (array)$filter_data['title_id']) ) {
        			$query  .=	' AND d.title_id in ('. $this->getListSQL($filter_data['title_id'], $ph) .') ';
        		}
        		if ( isset($filter_data['branch_id']) AND isset($filter_data['branch_id'][0]) AND !in_array(-1, (array)$filter_data['branch_id']) ) {
        			$query  .=	' AND a.branch_id in ('. $this->getListSQL($filter_data['branch_id'], $ph) .') ';
        		}
        		if ( isset($filter_data['department_id']) AND isset($filter_data['department_id'][0]) AND !in_array(-1, (array)$filter_data['department_id']) ) {
        			$query  .=	' AND a.department_id in ('. $this->getListSQL($filter_data['department_id'], $ph) .') ';
        		}
        		if ( isset($filter_data['status_id']) AND isset($filter_data['status_id'][0]) AND !in_array(-1, (array)$filter_data['status_id']) ) {
        			$query  .=	' AND a.status_id in ('. $this->getListSQL($filter_data['status_id'], $ph) .') ';
        		}
        		if ( isset($filter_data['type_id']) AND isset($filter_data['type_id'][0]) AND !in_array(-1, (array)$filter_data['type_id']) ) {
        			$query  .=	' AND a.type_id in ('. $this->getListSQL($filter_data['type_id'], $ph) .') ';
        		}
        		if ( isset($filter_data['pay_period_id']) AND isset($filter_data['pay_period_id'][0]) AND !in_array(-1, (array)$filter_data['pay_period_id']) ) {
        			$query .= 	' AND c.pay_period_id in ('. $this->getListSQL($filter_data['pay_period_id'], $ph) .') ';
        		}
        
        
        		//Use the job_id in the punch_control table so we can filter by '0' or No Job
        		if ( isset($filter_data['include_job_id']) AND isset($filter_data['include_job_id'][0]) AND !in_array(-1, (array)$filter_data['include_job_id']) ) {
        			$query  .=	' AND a.job_id in ('. $this->getListSQL($filter_data['include_job_id'], $ph) .') ';
        		}
        		if ( isset($filter_data['exclude_job_id']) AND isset($filter_data['exclude_job_id'][0]) AND !in_array(-1, (array)$filter_data['exclude_job_id']) ) {
        			$query  .=	' AND a.job_id not in ('. $this->getListSQL($filter_data['exclude_job_id'], $ph) .') ';
        		}
        		if ( isset($filter_data['job_group_id']) AND isset($filter_data['job_group_id'][0]) AND !in_array(-1, (array)$filter_data['job_group_id']) ) {
        			if ( isset($filter_data['include_job_subgroups']) AND (bool)$filter_data['include_job_subgroups'] == TRUE ) {
        				$uglf = new UserGroupListFactory();
        				$filter_data['job_group_id'] = $uglf->getByCompanyIdAndGroupIdAndjob_subgroupsArray( $company_id, $filter_data['job_group_id'], TRUE);
        			}
        			$query  .=	' AND x.group_id in ('. $this->getListSQL($filter_data['job_group_id'], $ph) .') ';
        		}
        
        		if ( isset($filter_data['job_item_id']) AND isset($filter_data['job_item_id'][0]) AND !in_array(-1, (array)$filter_data['job_item_id']) ) {
        			$query  .=	' AND a.job_item_id in ('. $this->getListSQL($filter_data['job_item_id'], $ph) .') ';
        		}
        */
        if (isset($filter_data['date']) and trim($filter_data['date']) != '') {
            $ph[] = $this->db->BindDate($filter_data['date']);
            $query .= ' AND c.date_stamp = ?';
        }
        if (isset($filter_data['start_date']) and trim($filter_data['start_date']) != '') {
            $ph[] = $this->db->BindDate($filter_data['start_date']);
            $query .= ' AND c.date_stamp >= ?';
        }
        if (isset($filter_data['end_date']) and trim($filter_data['end_date']) != '') {
            $ph[] = $this->db->BindDate($filter_data['end_date']);
            $query .= ' AND c.date_stamp <= ?';
        }
        $query .= '
						AND (a.deleted = 0 AND c.deleted = 0 AND d.deleted = 0)
					';
        $query .= $this->getWhereSQL($where);
        $query .= $this->getSortSQL($order, $strict, $additional_order_fields);
        $this->ExecuteSQL($query, $ph, $limit, $page);
        //Debug::Arr($ph, 'Query: '. $query, __FILE__, __LINE__, __METHOD__,10);
        return $this;
    }
    function getAPISearchByCompanyIdAndArrayCriteria($company_id, $filter_data, $limit = NULL, $page = NULL, $where = NULL, $order = NULL)
    {
        if ($company_id == '') {
            return FALSE;
        }
        if (!is_array($order)) {
            //Use Filter Data ordering if its set.
            if (isset($filter_data['sort_column']) and $filter_data['sort_order']) {
                $order = array(Misc::trimSortPrefix($filter_data['sort_column']) => $filter_data['sort_order']);
            }
        }
        $additional_order_fields = array();
        $sort_column_aliases = array();
        $order = $this->getColumnsFromAliases($order, $sort_column_aliases);
        if ($order == NULL) {
            $order = array('created_date' => 'desc');
            $strict = FALSE;
        } else {
            //Always try to order by status first so INACTIVE employees go to the bottom.
            if (!isset($order['created_date'])) {
                $order = Misc::prependArray(array('created_date' => 'desc'), $order);
            }
            $strict = TRUE;
        }
        //Debug::Arr($order,'Order Data:', __FILE__, __LINE__, __METHOD__,10);
        //Debug::Arr($filter_data,'Filter Data:', __FILE__, __LINE__, __METHOD__,10);
        $uf = new UserFactory();
        $rf = new RequestFactory();
        $udf = new UserDateFactory();
        $pptsvf = new PayPeriodTimeSheetVerifyListFactory();
        if (getTTProductEdition() >= TT_PRODUCT_ENTERPRISE) {
            $uef = new UserExpenseFactory();
        }
        $ph = array('company_id' => $company_id);
        $query = '
					select 	a.*,
							CASE WHEN a.object_type_id = 90 THEN pptsvf.user_id ELSE ud.user_id END as user_id,
							y.first_name as created_by_first_name,
							y.middle_name as created_by_middle_name,
							y.last_name as created_by_last_name,
							z.first_name as updated_by_first_name,
							z.middle_name as updated_by_middle_name,
							z.last_name as updated_by_last_name
					from 	' . $this->getTable() . ' as a
						LEFT JOIN ' . $rf->getTable() . ' as rf ON ( a.object_type_id in (1010,1020,1030,1040,1100) AND a.object_id = rf.id )
						LEFT JOIN ' . $udf->getTable() . ' as ud ON ( rf.user_date_id = ud.id )
						LEFT JOIN ' . $pptsvf->getTable() . ' as pptsvf ON ( a.object_type_id = 90 AND a.object_id = pptsvf.id ) ';
        if (getTTProductEdition() >= TT_PRODUCT_ENTERPRISE) {
            $query .= ' LEFT JOIN ' . $uef->getTable() . ' as uef ON ( a.object_type_id = 200 AND a.object_id = uef.id ) ';
        }
        $query .= '		LEFT JOIN ' . $uf->getTable() . ' as y ON ( a.created_by = y.id AND y.deleted = 0 )
						LEFT JOIN ' . $uf->getTable() . ' as z ON ( a.updated_by = z.id AND z.deleted = 0 )
					where	y.company_id = ?';
        $user_id_column = 'a.created_by';
        if (isset($filter_data['object_type_id']) and in_array($filter_data['object_type_id'], array(1010, 1020, 1030, 1040, 1100))) {
            //Requests
            $user_id_column = 'ud.user_id';
        } elseif (isset($filter_data['object_type_id']) and in_array($filter_data['object_type_id'], array(90))) {
            //TimeSheet
            $user_id_column = 'pptsvf.user_id';
        } elseif (isset($filter_data['object_type_id']) and in_array($filter_data['object_type_id'], array(200))) {
            //Expense
            $user_id_column = 'uef.user_id';
        }
        if (isset($filter_data['permission_children_ids']) and isset($filter_data['permission_children_ids'][0]) and !in_array(-1, (array) $filter_data['permission_children_ids'])) {
            $query .= ' AND ' . $user_id_column . ' in (' . $this->getListSQL($filter_data['permission_children_ids'], $ph) . ') ';
        }
        if (isset($filter_data['id']) and isset($filter_data['id'][0]) and !in_array(-1, (array) $filter_data['id'])) {
            $query .= ' AND a.id in (' . $this->getListSQL($filter_data['id'], $ph) . ') ';
        }
        if (isset($filter_data['exclude_id']) and isset($filter_data['exclude_id'][0]) and !in_array(-1, (array) $filter_data['exclude_id'])) {
            $query .= ' AND a.id not in (' . $this->getListSQL($filter_data['exclude_id'], $ph) . ') ';
        }
        if (isset($filter_data['object_type_id']) and isset($filter_data['object_type_id'][0]) and !in_array(-1, (array) $filter_data['object_type_id'])) {
            $query .= ' AND a.object_type_id in (' . $this->getListSQL($filter_data['object_type_id'], $ph) . ') ';
        }
        if (isset($filter_data['object_id']) and isset($filter_data['object_id'][0]) and !in_array(-1, (array) $filter_data['object_id'])) {
            $query .= ' AND a.object_id in (' . $this->getListSQL($filter_data['object_id'], $ph) . ') ';
        }
        $query .= isset($filter_data['created_by']) ? $this->getWhereClauseSQL(array('a.created_by', 'y.first_name', 'y.last_name'), $filter_data['created_by'], 'user_id_or_name', $ph) : NULL;
        $query .= isset($filter_data['updated_by']) ? $this->getWhereClauseSQL(array('a.updated_by', 'z.first_name', 'z.last_name'), $filter_data['updated_by'], 'user_id_or_name', $ph) : NULL;
        $query .= '
						AND a.deleted = 0
					';
        $query .= $this->getWhereSQL($where);
        $query .= $this->getSortSQL($order, $strict, $additional_order_fields);
        $this->ExecuteSQL($query, $ph, $limit, $page);
        return $this;
    }
 function createSchedule($user_id, $date_stamp, $data = NULL)
 {
     $sf = new ScheduleFactory();
     $sf->setUserDateId(UserDateFactory::findOrInsertUserDate($user_id, $date_stamp));
     if (isset($data['status_id'])) {
         $sf->setStatus($data['status_id']);
     } else {
         $sf->setStatus(10);
     }
     if (isset($data['schedule_policy_id'])) {
         $sf->setSchedulePolicyID($data['schedule_policy_id']);
     }
     if (isset($data['absence_policy_id'])) {
         $sf->setAbsencePolicyID($data['absence_policy_id']);
     }
     if (isset($data['branch_id'])) {
         $sf->setBranch($data['branch_id']);
     }
     if (isset($data['department_id'])) {
         $sf->setDepartment($data['department_id']);
     }
     if (isset($data['job_id'])) {
         $sf->setJob($data['job_id']);
     }
     if (isset($data['job_item_id'])) {
         $sf->setJobItem($data['job_item_id']);
     }
     if ($data['start_time'] != '') {
         $start_time = strtotime($data['start_time'], $date_stamp);
     }
     if ($data['end_time'] != '') {
         Debug::Text('End Time: ' . $data['end_time'] . ' Date Stamp: ' . $date_stamp, __FILE__, __LINE__, __METHOD__, 10);
         $end_time = strtotime($data['end_time'], $date_stamp);
         Debug::Text('bEnd Time: ' . $data['end_time'] . ' - ' . TTDate::getDate('DATE+TIME', $data['end_time']), __FILE__, __LINE__, __METHOD__, 10);
     }
     $sf->setStartTime($start_time);
     $sf->setEndTime($end_time);
     if ($sf->isValid()) {
         $sf->setEnableReCalculateDay(FALSE);
         $insert_id = $sf->Save();
         Debug::Text('Schedule ID: ' . $insert_id, __FILE__, __LINE__, __METHOD__, 10);
         return $insert_id;
     }
     Debug::Text('Failed Creating Schedule!', __FILE__, __LINE__, __METHOD__, 10);
     return FALSE;
 }
 function getHolidayUserDateIDs()
 {
     Debug::text('reCalculating Holiday...', __FILE__, __LINE__, __METHOD__, 10);
     //Get Holiday policies and determine how many days we need to look ahead/behind in order
     //to recalculate the holiday eligilibility/time.
     $holiday_before_days = 0;
     $holiday_after_days = 0;
     if (is_object($this->getUserDateObject()) and is_object($this->getUserDateObject()->getUserObject())) {
         $hplf = TTnew('HolidayPolicyListFactory');
         $hplf->getByCompanyId($this->getUserDateObject()->getUserObject()->getCompany());
         if ($hplf->getRecordCount() > 0) {
             foreach ($hplf as $hp_obj) {
                 if ($hp_obj->getMinimumWorkedPeriodDays() > $holiday_before_days) {
                     $holiday_before_days = $hp_obj->getMinimumWorkedPeriodDays();
                 }
                 if ($hp_obj->getAverageTimeDays() > $holiday_before_days) {
                     $holiday_before_days = $hp_obj->getAverageTimeDays();
                 }
                 if ($hp_obj->getMinimumWorkedAfterPeriodDays() > $holiday_after_days) {
                     $holiday_after_days = $hp_obj->getMinimumWorkedAfterPeriodDays();
                 }
             }
         }
     }
     Debug::text('Holiday Before Days: ' . $holiday_before_days . ' Holiday After Days: ' . $holiday_after_days, __FILE__, __LINE__, __METHOD__, 10);
     if ($holiday_before_days > 0 or $holiday_after_days > 0) {
         $retarr = array();
         $search_start_date = TTDate::getBeginWeekEpoch($this->getUserDateObject()->getDateStamp() - $holiday_after_days * 86400);
         $search_end_date = TTDate::getEndWeekEpoch(TTDate::getEndDayEpoch($this->getUserDateObject()->getDateStamp()) + $holiday_before_days * 86400 + 3601);
         Debug::text('Holiday search start date: ' . TTDate::getDate('DATE', $search_start_date) . ' End date: ' . TTDate::getDate('DATE', $search_end_date) . ' Current Date: ' . TTDate::getDate('DATE', $this->getUserDateObject()->getDateStamp()), __FILE__, __LINE__, __METHOD__, 10);
         $hlf = TTnew('HolidayListFactory');
         //$hlf->getByPolicyGroupUserIdAndStartDateAndEndDate( $this->getUserDateObject()->getUser(), TTDate::getEndWeekEpoch( $this->getUserDateObject()->getDateStamp() )+86400, TTDate::getEndDayEpoch()+($max_average_time_days*86400)+3601 );
         $hlf->getByPolicyGroupUserIdAndStartDateAndEndDate($this->getUserDateObject()->getUser(), $search_start_date, $search_end_date);
         if ($hlf->getRecordCount() > 0) {
             Debug::text('Found Holidays within range: ' . $hlf->getRecordCount(), __FILE__, __LINE__, __METHOD__, 10);
             $udlf = TTnew('UserDateListFactory');
             foreach ($hlf as $h_obj) {
                 Debug::text('ReCalculating Day due to Holiday: ' . TTDate::getDate('DATE', $h_obj->getDateStamp()), __FILE__, __LINE__, __METHOD__, 10);
                 $user_date_ids = $udlf->getArrayByListFactory($udlf->getByUserIdAndDate($this->getUserDateObject()->getUser(), $h_obj->getDateStamp()));
                 if ($user_date_ids == FALSE and TTDate::getBeginDayEpoch($h_obj->getDateStamp()) <= TTDate::getBeginDayEpoch(time())) {
                     //This fixes a bug where if an employee was added after a holiday (ie: Sept 3rd after Labor day of Sept 2nd)
                     //then had time added before the holiday, the holiday would not be calculated as no user_date record would exist.
                     $user_date_ids = (array) UserDateFactory::findOrInsertUserDate($this->getUserDateObject()->getUser(), TTDate::getBeginDayEpoch($h_obj->getDateStamp()));
                     Debug::Text('User Date ID for holiday doesnt exist, creating it now: ' . $user_date_ids[0], __FILE__, __LINE__, __METHOD__, 10);
                 }
                 if (is_array($user_date_ids)) {
                     $retarr = array_merge($retarr, $user_date_ids);
                 }
                 unset($user_date_ids);
             }
         }
     }
     if (isset($retarr) and is_array($retarr) and count($retarr) > 0) {
         //Debug::Arr($retarr, 'bHoliday UserDateIDs: ', __FILE__, __LINE__, __METHOD__, 10);
         return $retarr;
     }
     Debug::text('No Holidays within range...', __FILE__, __LINE__, __METHOD__, 10);
     return FALSE;
 }
Beispiel #25
0
 */
 if ($id != '') {
     Debug::Text(' ID was passed: ' . $id, __FILE__, __LINE__, __METHOD__, 10);
     $udtlf = TTnew('UserDateTotalListFactory');
     $udtlf->getById($id);
     foreach ($udtlf as $udt_obj) {
         //Debug::Arr($station,'Department', __FILE__, __LINE__, __METHOD__,10);
         $user_id = $udt_obj->getUserDateObject()->getUser();
         $udt_data = array('id' => $udt_obj->getId(), 'user_date_id' => $udt_obj->getUserDateId(), 'date_stamp' => $udt_obj->getUserDateObject()->getDateStamp(), 'user_id' => $udt_obj->getUserDateObject()->getUser(), 'user_full_name' => $udt_obj->getUserDateObject()->getUserObject()->getFullName(), 'status_id' => $udt_obj->getStatus(), 'type_id' => $udt_obj->getType(), 'total_time' => $udt_obj->getTotalTime(), 'absence_policy_id' => $udt_obj->getAbsencePolicyID(), 'branch_id' => $udt_obj->getBranch(), 'department_id' => $udt_obj->getDepartment(), 'job_id' => $udt_obj->getJob(), 'job_item_id' => $udt_obj->getJobItem(), 'override' => $udt_obj->getOverride(), 'created_date' => $udt_obj->getCreatedDate(), 'created_by' => $udt_obj->getCreatedBy(), 'updated_date' => $udt_obj->getUpdatedDate(), 'updated_by' => $udt_obj->getUpdatedBy(), 'deleted_date' => $udt_obj->getDeletedDate(), 'deleted_by' => $udt_obj->getDeletedBy());
     }
 } elseif ($action != 'submit') {
     Debug::Text(' ID was NOT passed: ' . $id, __FILE__, __LINE__, __METHOD__, 10);
     //Get user full name
     $ulf = TTnew('UserListFactory');
     $user_obj = $ulf->getById($user_id)->getCurrent();
     $user_date_id = UserDateFactory::getUserDateID($user_id, $date_stamp);
     $udt_data = array('user_id' => $user_id, 'date_stamp' => $date_stamp, 'user_date_id' => $user_date_id, 'user_full_name' => $user_obj->getFullName(), 'branch_id' => $user_obj->getDefaultBranch(), 'department_id' => $user_obj->getDefaultDepartment(), 'total_time' => 0, 'override' => TRUE);
 }
 $aplf = TTnew('AbsencePolicyListFactory');
 $absence_policy_options = Misc::prependArray(array(0 => TTi18n::gettext('-- Please Choose --')), $aplf->getByCompanyIdArray($current_company->getId()));
 $blf = TTnew('BranchListFactory');
 $branch_options = $blf->getByCompanyIdArray($current_company->getId());
 $dlf = TTnew('DepartmentListFactory');
 $department_options = $dlf->getByCompanyIdArray($current_company->getId());
 if ($current_company->getProductEdition() >= 20) {
     $jlf = TTnew('JobListFactory');
     $jlf->getByCompanyIdAndUserIdAndStatus($current_company->getId(), $user_id, array(10, 20, 30, 40));
     $udt_data['job_options'] = $jlf->getArrayByListFactory($jlf, TRUE, TRUE);
     $udt_data['job_manual_id_options'] = $jlf->getManualIDArrayByListFactory($jlf, TRUE);
     $jilf = TTnew('JobItemListFactory');
     $jilf->getByCompanyId($current_company->getId());
    function getAPISearchByCompanyIdAndArrayCriteria($company_id, $filter_data, $limit = NULL, $page = NULL, $where = NULL, $order = NULL)
    {
        if ($company_id == '') {
            return FALSE;
        }
        if (isset($filter_data['user_status_id'])) {
            $filter_data['status_id'] = $filter_data['user_status_id'];
        }
        if (isset($filter_data['user_group_id'])) {
            $filter_data['group_id'] = $filter_data['user_group_id'];
        }
        if (isset($filter_data['user_title_id'])) {
            $filter_data['title_id'] = $filter_data['user_title_id'];
        }
        if (isset($filter_data['include_user_id'])) {
            $filter_data['user_id'] = $filter_data['include_user_id'];
        }
        if (isset($filter_data['exclude_user_id'])) {
            $filter_data['exclude_id'] = $filter_data['exclude_user_id'];
        }
        if (isset($filter_data['accrual_type_id'])) {
            $filter_data['type_id'] = $filter_data['accrual_type_id'];
        }
        if (!is_array($order)) {
            //Use Filter Data ordering if its set.
            if (isset($filter_data['sort_column']) and $filter_data['sort_order']) {
                $order = array(Misc::trimSortPrefix($filter_data['sort_column']) => $filter_data['sort_order']);
            }
        }
        if (isset($filter_data['accrual_type_id'])) {
            $filter_data['type_id'] = $filter_data['accrual_type_id'];
        }
        $additional_order_fields = array('accrual_policy', 'accrual_policy_type_id', 'date_stamp');
        $sort_column_aliases = array('accrual_policy_type' => 'accrual_policy_type_id', 'type' => 'type_id');
        $order = $this->getColumnsFromAliases($order, $sort_column_aliases);
        if ($order == NULL) {
            $order = array('accrual_policy_id' => 'asc', 'date_stamp' => 'desc');
            $strict = FALSE;
        } else {
            $strict = TRUE;
        }
        //Debug::Arr($order,'Order Data:', __FILE__, __LINE__, __METHOD__,10);
        //Debug::Arr($filter_data,'Filter Data:', __FILE__, __LINE__, __METHOD__,10);
        $uf = new UserFactory();
        $udtf = new UserDateTotalFactory();
        $udf = new UserDateFactory();
        $bf = new BranchFactory();
        $df = new DepartmentFactory();
        $ugf = new UserGroupFactory();
        $utf = new UserTitleFactory();
        $apf = new AccrualPolicyFactory();
        $ph = array('company_id' => $company_id);
        $query = '
					select 	a.*,
							ab.name as accrual_policy,
							ab.type_id as accrual_policy_type_id,
							CASE WHEN udf.date_stamp is NOT NULL THEN udf.date_stamp ELSE a.time_stamp END as date_stamp,
							b.first_name as first_name,
							b.last_name as last_name,
							b.country as country,
							b.province as province,

							c.id as default_branch_id,
							c.name as default_branch,
							d.id as default_department_id,
							d.name as default_department,
							e.id as group_id,
							e.name as "user_group",
							f.id as title_id,
							f.name as title
					from 	' . $this->getTable() . ' as a
						LEFT JOIN ' . $apf->getTable() . ' as ab ON ( a.accrual_policy_id = ab.id AND ab.deleted = 0 )
						LEFT JOIN ' . $uf->getTable() . ' as b ON ( a.user_id = b.id AND b.deleted = 0 )

						LEFT JOIN ' . $udtf->getTable() . ' as udtf ON ( a.user_date_total_id = udtf.id AND udtf.deleted = 0 )
						LEFT JOIN ' . $udf->getTable() . ' as udf ON ( udtf.user_date_id = udf.id AND udf.deleted = 0 )

						LEFT JOIN ' . $bf->getTable() . ' as c ON ( b.default_branch_id = c.id AND c.deleted = 0)
						LEFT JOIN ' . $df->getTable() . ' as d ON ( b.default_department_id = d.id AND d.deleted = 0)
						LEFT JOIN ' . $ugf->getTable() . ' as e ON ( b.group_id = e.id AND e.deleted = 0 )
						LEFT JOIN ' . $utf->getTable() . ' as f ON ( b.title_id = f.id AND f.deleted = 0 )
                        LEFT JOIN ' . $uf->getTable() . ' as y ON ( a.created_by = y.id AND y.deleted = 0 )
						LEFT JOIN ' . $uf->getTable() . ' as z ON ( a.updated_by = z.id AND z.deleted = 0 )

					where	b.company_id = ?
					';
        $query .= isset($filter_data['permission_children_ids']) ? $this->getWhereClauseSQL('a.user_id', $filter_data['permission_children_ids'], 'numeric_list', $ph) : NULL;
        $query .= isset($filter_data['user_id']) ? $this->getWhereClauseSQL('a.user_id', $filter_data['user_id'], 'numeric_list', $ph) : NULL;
        $query .= isset($filter_data['id']) ? $this->getWhereClauseSQL('a.id', $filter_data['id'], 'numeric_list', $ph) : NULL;
        $query .= isset($filter_data['exclude_id']) ? $this->getWhereClauseSQL('a.user_id', $filter_data['exclude_id'], 'not_numeric_list', $ph) : NULL;
        if (isset($filter_data['type']) and trim($filter_data['type']) != '' and !isset($filter_data['type_id'])) {
            $filter_data['type_id'] = Option::getByFuzzyValue($filter_data['type'], $this->getOptions('type'));
        }
        $query .= isset($filter_data['type_id']) ? $this->getWhereClauseSQL('a.type_id', $filter_data['type_id'], 'numeric_list', $ph) : NULL;
        if (isset($filter_data['status']) and trim($filter_data['status']) != '' and !isset($filter_data['status_id'])) {
            $filter_data['status_id'] = Option::getByFuzzyValue($filter_data['status'], $this->getOptions('status'));
        }
        $query .= isset($filter_data['accrual_policy_type_id']) ? $this->getWhereClauseSQL('ab.type_id', $filter_data['accrual_policy_type_id'], 'numeric_list', $ph) : NULL;
        $query .= isset($filter_data['accrual_policy_id']) ? $this->getWhereClauseSQL('a.accrual_policy_id', $filter_data['accrual_policy_id'], 'numeric_list', $ph) : NULL;
        $query .= isset($filter_data['status_id']) ? $this->getWhereClauseSQL('b.status_id', $filter_data['status_id'], 'numeric_list', $ph) : NULL;
        $query .= isset($filter_data['group_id']) ? $this->getWhereClauseSQL('b.group_id', $filter_data['group_id'], 'numeric_list', $ph) : NULL;
        $query .= isset($filter_data['default_branch_id']) ? $this->getWhereClauseSQL('b.default_branch_id', $filter_data['default_branch_id'], 'numeric_list', $ph) : NULL;
        $query .= isset($filter_data['default_department_id']) ? $this->getWhereClauseSQL('b.default_department_id', $filter_data['default_department_id'], 'numeric_list', $ph) : NULL;
        $query .= isset($filter_data['title_id']) ? $this->getWhereClauseSQL('b.title_id', $filter_data['title_id'], 'numeric_list', $ph) : NULL;
        $query .= isset($filter_data['country']) ? $this->getWhereClauseSQL('b.country', $filter_data['country'], 'upper_text_list', $ph) : NULL;
        $query .= isset($filter_data['province']) ? $this->getWhereClauseSQL('b.province', $filter_data['province'], 'upper_text_list', $ph) : NULL;
        $query .= isset($filter_data['pay_period_id']) ? $this->getWhereClauseSQL('udf.pay_period_id', $filter_data['pay_period_id'], 'numeric_list', $ph) : NULL;
        if (isset($filter_data['start_date']) and trim($filter_data['start_date']) != '') {
            $ph[] = $this->db->BindDate($filter_data['start_date']);
            $ph[] = $this->db->BindDate($filter_data['start_date']);
            $query .= ' AND ( ( udf.date_stamp is NULL AND a.time_stamp >= ? ) OR ( udf.date_stamp is NOT NULL AND udf.date_stamp >= ? ) )';
        }
        if (isset($filter_data['end_date']) and trim($filter_data['end_date']) != '') {
            $ph[] = $this->db->BindDate($filter_data['end_date']);
            $ph[] = $this->db->BindDate($filter_data['end_date']);
            $query .= ' AND ( ( udf.date_stamp is NULL AND a.time_stamp <= ? ) OR ( udf.date_stamp is NOT NULL AND udf.date_stamp <= ? ) )';
        }
        $query .= isset($filter_data['created_by']) ? $this->getWhereClauseSQL(array('a.created_by', 'y.first_name', 'y.last_name'), $filter_data['created_by'], 'user_id_or_name', $ph) : NULL;
        $query .= isset($filter_data['updated_by']) ? $this->getWhereClauseSQL(array('a.updated_by', 'z.first_name', 'z.last_name'), $filter_data['updated_by'], 'user_id_or_name', $ph) : NULL;
        //Make sure we exclude delete user_date_total records, so we match the accrual balances.
        $query .= '
						AND ( ( a.user_date_total_id is NOT NULL AND udtf.id is NOT NULL AND udtf.deleted = 0 ) OR ( a.user_date_total_id IS NULL AND udtf.id is NULL ) )
						AND a.deleted = 0
					';
        $query .= $this->getWhereSQL($where);
        $query .= $this->getSortSQL($order, $strict, $additional_order_fields);
        //Debug::Arr($ph,'Filter Data:'. $query, __FILE__, __LINE__, __METHOD__,10);
        $this->ExecuteSQL($query, $ph, $limit, $page);
        return $this;
    }