Beispiel #1
0
 /**
  * Store a newly created resource in storage.
  *
  * @return Response
  */
 public function store()
 {
     $input = Input::all();
     $rules = array('tool_name' => 'required', 'acc_name' => 'required', 'emp_id' => 'required', 'emp_name' => 'required', 'access' => 'required');
     $messages = array('tool_name.required' => 'Tool Name is required !', 'emp_id.required' => 'Employee ID is required !', 'emp_name.required' => 'Employee Name is required !', 'access.required' => 'Please select an accesibility !');
     $validation = Validator::make($input, $rules, $messages);
     if ($validation->passes()) {
         $toolname = Accounts::select('account_name')->where('id', '=', Input::get('acc_name'))->get();
         foreach ($toolname as $key => $tool) {
             $accName = $tool->account_name;
         }
         //print_r($account_name);
         //exit;
         $employees = new Employee();
         $employees->emp_id = Input::get('emp_id');
         $employees->emp_name = Input::get('emp_name');
         $employees->acc_id = Input::get('acc_name');
         $employees->tool_name = Input::get('tool_name');
         $employees->access = Input::get('access');
         $employees->save();
         return Redirect::to('/employees');
     } else {
         return Redirect::to('/employees/create')->withErrors($validation);
     }
 }
Beispiel #2
0
 /**
  * Store a newly created resource in storage.
  *
  * @return Response
  */
 public function store()
 {
     // $validation = Employee::validate(Input::all());
     $input = Input::all();
     $rules = array('first_name' => 'required|max:20', 'last_name' => 'required|max:20', 'email' => 'required|email|unique:employees,email', 'username' => 'required|unique:employees,username', 'password' => 'required|confirmed', 'password_confirmation' => 'required', 'phone_number' => 'required|numeric');
     $validation = Validator::make($input, $rules);
     if ($validation->passes()) {
         $employee = new Employee();
         $employee->first_name = Input::get('first_name');
         $employee->last_name = Input::get('last_name');
         $employee->email = Input::get('email');
         $employee->username = Input::get('username');
         $employee->password = Hash::make(Input::get('password'));
         $employee->phone_number = Input::get('phone_number');
         $employee->address1 = Input::get('address1');
         $employee->address2 = Input::get('address2');
         $employee->city = Input::get('city');
         $employee->state = Input::get('state');
         $employee->zip = Input::get('zip');
         $employee->country = Input::get('country');
         $employee->comment = Input::get('comment');
         $employee->save();
         // return "Success";
         Session::flash('success', 'A new employee has been created');
         return Redirect::to('/employees');
     } else {
         return Redirect::to('/employees/create')->withErrors($validation)->withInput();
     }
 }
 /**
  * @desc - สำหรับรับค่าข้อมูล FORM ที่ส่งค่าข้อมูลจาก AJax แบบ Post
  * @return json
  */
 public function addAction()
 {
     //ปิดการใช้งานสำหรับการร้องขอ Ajax
     $this->view->disable();
     //ถ้ากดปุ่มโพสต์
     if ($this->request->isPost() == true) {
         //ถ้าส่งฝ่าน Ajax
         if ($this->request->isAjax() == true) {
             ////อนุญาตให้ส่งข้อมูลครั้งเดียวโดยใช้เงื่อนไขของ  token ตรวจสอบ
             if ($this->security->checkToken()) {
                 // สร้าง Model ข้อมูลตาราง Employee รับค่าข้อมูลจากการส่งข้อมูลภายใต้  FORM ที่มีส่งข้อมูล SSN, FNAME, LNAME, DNO
                 $employee = new Employee();
                 $employee->SSN = $this->request->getPost('SSN', array('striptags', 'trim'));
                 $employee->FNAME = $this->request->getPost('FNAME', array('striptags', 'trim'));
                 $employee->LNAME = $this->request->getPost('LNAME', array('striptags', 'trim'));
                 $employee->DNO = $this->request->getPost('DNO', array('striptags', 'trim'));
                 //รันคำสั่ง SQL insert into employee (SSN, FNAME, LNAME, DNO) value ($_POST['SSN'] ,$_POST['FNAME'] ...)
                 if ($employee->save()) {
                     $this->response->setJsonContent(array("res" => "success"));
                     //ระบุสถานะทำงานเสร็จโดยค่า Code 200 เพื่อส่งข้อมูลการทำงานสำเร็จ
                     $this->response->setStatusCode(200, "OK");
                 } else {
                     $this->response->setJsonContent(array("res" => "error"));
                     //ระบุสถานะทำงานผิดพลาดโดยค่า Code 500 เพื่อส่งข้อมูลการทำงานผิดพลาด
                     $this->response->setStatusCode(500, "Internal Server Error");
                 }
                 $this->response->send();
             }
         }
     }
 }
 public function postAddnewemp()
 {
     $inputs = Input::all();
     if (!empty($inputs['fullname'])) {
         $photoNewName = null;
         // upload photo
         if (Input::hasFile('photo')) {
             $photo = Input::file('photo');
             $photoNewName = date('YmdHis') . '.' . $photo->getClientOriginalExtension();
             $photo->move('image/employee', $photoNewName);
         }
         $employee = new Employee();
         $employee->emp_name = $inputs['fullname'];
         $employee->emp_idcard = $inputs['cardid'];
         $employee->emp_address = $inputs['address'];
         $employee->emp_tel = $inputs['tel'];
         $employee->emp_lineid = $inputs['lineid'];
         $employee->emp_email = $inputs['email'];
         $employee->emp_image = $photoNewName;
         $employee->emp_username = $inputs['username'];
         $employee->emp_password = Hash::Make($inputs['password']);
         $employee->save();
         return Redirect::to('admin/employee/showallemployee')->with('alert', 'สร้างพนักงานสำเร็จ');
     }
     return Redirect::back();
 }
 /**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  */
 public function actionCreate()
 {
     $model = new Employee();
     $user = new RbacUser();
     $disabled = "";
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($model);
     if (Yii::app()->user->checkAccess('employee.create')) {
         if (isset($_POST['Employee'])) {
             $model->attributes = $_POST['Employee'];
             $user->attributes = $_POST['RbacUser'];
             //$location_id = $_POST['Employee']['location'];
             if ($_POST['Employee']['year'] !== "" || $_POST['Employee']['month'] !== "" || $_POST['Employee']['day'] !== "") {
                 $dob = $_POST['Employee']['year'] . '-' . $_POST['Employee']['month'] . '-' . $_POST['Employee']['day'];
                 $model->dob = $dob;
             }
             // validate BOTH $a and $b
             $valid = $model->validate();
             $valid = $user->validate() && $valid;
             if ($valid) {
                 $transaction = $model->dbConnection->beginTransaction();
                 try {
                     if ($model->save()) {
                         $user->employee_id = $model->id;
                         if ($user->save()) {
                             $assignitems = array('items', 'sales', 'employees', 'customers', 'suppliers', 'store', 'receivings', 'reports', 'invoices', 'payments');
                             foreach ($assignitems as $assignitem) {
                                 if (!empty($_POST['RbacUser'][$assignitem])) {
                                     foreach ($_POST['RbacUser'][$assignitem] as $itemId) {
                                         $authassigment = new Authassignment();
                                         $authassigment->userid = $user->id;
                                         $authassigment->itemname = $itemId;
                                         if (!$authassigment->save()) {
                                             $transaction->rollback();
                                             print_r($authassigment->errors);
                                         }
                                     }
                                 }
                             }
                             $transaction->commit();
                             Yii::app()->user->setFlash('success', '<strong>Well done!</strong> successfully saved.');
                             //$this->redirect(array('view', 'id' => $model->id));
                             $this->redirect(array('admin'));
                         } else {
                             Yii::app()->user->setFlash('error', '<strong>Oh snap!</strong> Change a few things up and try submitting again.');
                         }
                     }
                 } catch (Exception $e) {
                     $transaction->rollback();
                     Yii::app()->user->setFlash('error', '<strong>Oh snap!</strong> Change a few things up and try submitting again.' . $e);
                 }
             }
         }
     } else {
         throw new CHttpException(403, 'You are not authorized to perform this action');
     }
     $this->render('create', array('model' => $model, 'user' => $user, 'disabled' => $disabled));
 }
Beispiel #6
0
 /**
  * Creates a new Employee model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  * @return mixed
  */
 public function actionCreate()
 {
     $model = new Employee();
     if ($model->load(Yii::$app->request->post()) && $model->save()) {
         return $this->redirect(['view', 'id' => $model->id]);
     } else {
         return $this->render('create', ['model' => $model]);
     }
 }
Beispiel #7
0
 public static function Create($name, $telephone, $email, $address, $gender, $department, $position, $salary)
 {
     $type = new PartyType('Employee');
     $employee = new Employee($type, $name, $telephone, $email, $address, $gender, $department, $position, $salary, 0);
     if ($employee->save()) {
         return $employee;
     }
     return false;
 }
 public function store()
 {
     $employee = new Employee();
     $employee->employee_id = Input::get('employee_id');
     $employee->code = Input::get('code');
     $employee->name = Input::get('name');
     $employee->contact = Input::get('contact');
     $employee->basic_salary = Input::get('basic_salary');
     $employee->teach_salary = Input::get('teach_salary');
     $employee->save();
     Session::flash('message', 'Sukses menambahkan data pegawai!');
 }
Beispiel #9
0
 /**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  */
 public function actionCreate()
 {
     $model = new Employee();
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($model);
     if (isset($_POST['Employee'])) {
         $model->attributes = $_POST['Employee'];
         if ($model->save()) {
             $this->redirect(array('view', 'id' => $model->id));
         }
     }
     $this->render('create', array('model' => $model));
 }
 protected function createFakerEmployee()
 {
     $faker = Faker::create();
     for ($i = 1; $i < 50; $i++) {
         $employee = new Employee();
         $employee->first_name = $faker->firstName;
         $employee->last_name = $faker->lastName;
         $employee->email = $faker->email;
         $employee->hire_date = $faker->date($format = 'Y-m-d');
         $employee->password = $faker->password;
         $employee->save();
     }
 }
 public function run()
 {
     $employee = new Employee();
     $employee->name = 'Ganesh';
     $employee->email = '*****@*****.**';
     $employee->password = '******';
     $employee->password_confirmation = '00d00@ganesh';
     $employee->mobile = '9999999999';
     $employee->active = 1;
     $employee->save();
     $employee::$rules = [];
     $employee->generateEmployeeId();
 }
 /**
  * Store a newly created resource in storage.
  * POST /clinics
  *
  * @return Response
  */
 public function store()
 {
     $data = Input::all();
     $validator = Validator::make($data, array('password' => 'min:6', 'email' => 'unique:employees', 'status' => 'required', 'clinic_name' => 'required', 'clinic_address' => 'required'));
     if ($validator->fails()) {
         return Redirect::back()->withErrors($validator)->withInput();
     }
     $clinic = Clinic::create(['name' => $data['clinic_name'], 'address' => $data['clinic_address']]);
     $employee = new Employee();
     $employee->clinic_id = $clinic->id;
     $employee->name = Input::get('name');
     $employee->password = Hash::make(Input::get('password'));
     $employee->email = Input::get('email');
     $employee->gender = Input::get('gender');
     $employee->age = Input::get('age');
     $employee->city = Input::get('city');
     $employee->country = Input::get('country');
     $employee->address = Input::get('address');
     if (Input::get('phone') == '') {
         $employee->phone = 'N/A';
     } else {
         $employee->phone = Input::get('phone');
     }
     if (Input::get('cnic') == '') {
         $employee->cnic = 'N/A';
     } else {
         $employee->cnic = Input::get('cnic');
     }
     if (Input::get('branch') == '') {
         $employee->branch = 'N/A';
     } else {
         $employee->branch = Input::get('branch');
     }
     if (Input::get('note') == '') {
         $employee->note = 'N/A';
     } else {
         $employee->note = Input::get('note');
     }
     $employee->status = Input::get('status');
     $employee->role = 'Administrator';
     $employee->save();
     $data = ['link' => URL::to('login'), 'name' => Input::get('name')];
     //      Send email to employee
     Mail::queue('emails.welcome', $data, function ($message) {
         $message->to(Input::get('email'), Input::get('name'))->subject('Welcome to EMR!');
     });
     return Redirect::route('clinics.index');
 }
Beispiel #13
0
 /**
  * Performs the work of inserting or updating the row in the database.
  *
  * If the object is new, it inserts it; otherwise an update is performed.
  * All related objects are also updated in this method.
  *
  * @param      PropelPDO $con
  * @return     int The number of rows affected by this insert/update and any referring fk objects' save() operations.
  * @throws     PropelException
  * @see        save()
  */
 protected function doSave(PropelPDO $con)
 {
     $affectedRows = 0;
     // initialize var to track total num of affected rows
     if (!$this->alreadyInSave) {
         $this->alreadyInSave = true;
         // We call the save method on the following object(s) if they
         // were passed to this object by their coresponding set
         // method.  This object relates to these object(s) by a
         // foreign key reference.
         if ($this->aRole !== null) {
             if ($this->aRole->isModified() || $this->aRole->isNew()) {
                 $affectedRows += $this->aRole->save($con);
             }
             $this->setRole($this->aRole);
         }
         if ($this->aEmployee !== null) {
             if ($this->aEmployee->isModified() || $this->aEmployee->isNew()) {
                 $affectedRows += $this->aEmployee->save($con);
             }
             $this->setEmployee($this->aEmployee);
         }
         if ($this->isNew()) {
             $this->modifiedColumns[] = UserPeer::ID;
         }
         // If this object has been modified, then save it to the database.
         if ($this->isModified()) {
             if ($this->isNew()) {
                 $pk = UserPeer::doInsert($this, $con);
                 $affectedRows += 1;
                 // we are assuming that there is only 1 row per doInsert() which
                 // should always be true here (even though technically
                 // BasePeer::doInsert() can insert multiple rows).
                 $this->setId($pk);
                 //[IMV] update autoincrement primary key
                 $this->setNew(false);
             } else {
                 $affectedRows += UserPeer::doUpdate($this, $con);
             }
             $this->resetModified();
             // [HL] After being saved an object is no longer 'modified'
         }
         $this->alreadyInSave = false;
     }
     return $affectedRows;
 }
 public static function store()
 {
     $params = $_POST;
     $services = Service::all();
     $attributes = array('name' => $params['name'], 'special' => $params['special'], 'introduction' => $params['introduction']);
     $employee = new Employee($attributes);
     $errors = $employee->errors();
     if (count($errors) == 0) {
         $employee->save();
         foreach ($services as $serv) {
             if (isset($_POST[$serv->id])) {
                 OfferedServicesController::create($employee->id, $serv->id);
             }
         }
         Redirect::to('/tyontekijat/' . $employee->id, array('message' => 'Työntekijä lisätty!'));
     } else {
         View::make('employee/new.html', array('errors' => $errors, 'attributes' => $attributes));
     }
 }
Beispiel #15
0
 /**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  */
 public function actionCreate()
 {
     $model = new Employee();
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($model);
     if (isset($_POST['Employee'])) {
         $model->attributes = $_POST['Employee'];
         if ($model->save()) {
             date_default_timezone_set("Asia/Manila");
         }
         $activity = new Activity();
         $activity->act_desc = 'Added Another Employee';
         $activity->act_datetime = date('Y-m-d G:i:s');
         $activity->act_by = User::model()->findByPK(Yii::app()->user->name)->emp_id;
         $activity->save();
         $this->redirect(array('view', 'id' => $model->emp_id));
     }
     $this->render('create', array('model' => $model));
 }
Beispiel #16
0
 public function testUserListView()
 {
     // new employee
     $last_name = 'Test_46473_' . time();
     $emp = new Employee();
     $emp->last_name = $last_name;
     $emp->default_team = 1;
     $emp->status = 'Active';
     $emp->employee_status = 'Active';
     $emp->user_name = 'test_user_name';
     $emp->save();
     $emp_id = $emp->id;
     $this->assertNotNull($emp_id, 'User id should not be null.');
     // list view
     $view = new UsersViewList();
     $view->module = 'Users';
     $view->init($emp);
     $view->lv = new ListViewSmarty();
     $view->display();
     // ensure the new employee shows up in the users list view
     $this->expectOutputRegex('/.*' . $last_name . '.*/');
 }
 public function add_employees()
 {
     foreach ($this->user_data as $key => $ud) {
         $this->user_data[$key]["Employee"]["employeerole_id"] = $this->roles_array[$ud["Employee"]["employeerole_id"]];
         $user = new User();
         if ($user->save($this->user_data[$key]["User"])) {
             $employee = new Employee();
             $this->user_data[$key]["Employee"]["id"] = $user->id;
             $employee->save($this->user_data[$key]["Employee"]);
             if (!(key_exists("id", $this->user_data[$key]["User"]) && !empty($this->user_data[$key]["User"]["id"]))) {
                 $companies_employee = new CompaniesEmployee();
                 $comp_emp_data = array("CompaniesEmployee" => array("company_id" => $this->company_id, "employee_id" => $employee->id));
                 $companies_employee->save($comp_emp_data);
             }
             unset($employee);
             unset($user);
             unset($companies_employee);
         }
     }
 }
Beispiel #18
0
 /**
  * Store a newly created resource in storage.
  *
  * @return Response
  */
 public function store()
 {
     //
     $validator = Validator::make($data = Input::all(), Employee::$rules, Employee::$messages);
     if ($validator->fails()) {
         return Redirect::back()->withErrors($validator)->withInput();
     }
     $employee = new Employee();
     $employee->personal_file_number = Input::get('personal_file_number');
     $employee->first_name = Input::get('fname');
     $employee->last_name = Input::get('lname');
     $employee->middle_name = Input::get('mname');
     $employee->identity_number = Input::get('identity_number');
     if (Input::get('passport_number') != null) {
         $employee->passport_number = Input::get('passport_number');
     } else {
         $employee->passport_number = null;
     }
     if (Input::get('pin') != null) {
         $employee->pin = Input::get('pin');
     } else {
         $employee->pin = null;
     }
     if (Input::get('social_security_number') != null) {
         $employee->social_security_number = Input::get('social_security_number');
     } else {
         $employee->social_security_number = null;
     }
     if (Input::get('hospital_insurance_number') != null) {
         $employee->hospital_insurance_number = Input::get('hospital_insurance_number');
     } else {
         $employee->hospital_insurance_number = null;
     }
     if (Input::get('work_permit_number') != null) {
         $employee->work_permit_number = Input::get('work_permit_number');
     } else {
         $employee->work_permit_number = null;
     }
     $employee->job_title = Input::get('jtitle');
     $employee->basic_pay = Input::get('pay');
     $employee->gender = Input::get('gender');
     $employee->marital_status = Input::get('status');
     $employee->yob = Input::get('dob');
     $employee->citizenship = Input::get('citizenship');
     $employee->mode_of_payment = Input::get('modep');
     if (Input::get('bank_account_number') != null) {
         $employee->bank_account_number = Input::get('bank_account_number');
     } else {
         $employee->bank_account_number = null;
     }
     if (Input::get('bank_eft_code') != null) {
         $employee->bank_eft_code = Input::get('bank_eft_code');
     } else {
         $employee->bank_eft_code = null;
     }
     if (Input::get('swift_code') != null) {
         $employee->swift_code = Input::get('swift_code');
     } else {
         $employee->swift_code = null;
     }
     if (Input::get('email_office') != null) {
         $employee->email_office = Input::get('email_office');
     } else {
         $employee->email_office = null;
     }
     if (Input::get('email_personal') != null) {
         $employee->email_personal = Input::get('email_personal');
     } else {
         $employee->email_personal = null;
     }
     if (Input::get('telephone_mobile') != null) {
         $employee->telephone_mobile = Input::get('telephone_mobile');
     } else {
         $employee->telephone_mobile = null;
     }
     $employee->postal_address = Input::get('address');
     $employee->postal_zip = Input::get('zip');
     $employee->date_joined = Input::get('djoined');
     $employee->bank_id = Input::get('bank_id');
     $employee->bank_branch_id = Input::get('bbranch_id');
     $employee->branch_id = Input::get('branch_id');
     $employee->department_id = Input::get('department_id');
     $employee->job_group_id = Input::get('jgroup_id');
     $employee->type_id = Input::get('type_id');
     if (Input::get('i_tax') != null) {
         $employee->income_tax_applicable = '1';
     } else {
         $employee->income_tax_applicable = '0';
     }
     if (Input::get('i_tax_relief') != null) {
         $employee->income_tax_relief_applicable = '1';
     } else {
         $employee->income_tax_relief_applicable = '0';
     }
     if (Input::get('a_nhif') != null) {
         $employee->hospital_insurance_applicable = '1';
     } else {
         $employee->hospital_insurance_applicable = '0';
     }
     if (Input::get('a_nssf') != null) {
         $employee->social_security_applicable = '1';
     } else {
         $employee->social_security_applicable = '0';
     }
     $employee->organization_id = '1';
     $employee->save();
     Audit::logaudit('Employee', 'create', 'created: ' . $employee->personal_file_number . '-' . $employee->first_name . ' ' . $employee->last_name);
     return Redirect::route('employees.index');
 }
Beispiel #19
0
 /**
  * Save Contact Details
  * @param Employee $employee
  * @returns boolean
  * @throws DaoException
  */
 public function saveJobDetails(Employee $employee)
 {
     try {
         $employee->save();
         return true;
     } catch (Exception $e) {
         throw new DaoException($e->getMessage());
     }
 }
 public function actionWrite()
 {
     if (isset($_POST['Employee'])) {
         $messages = $this->ValidateData(array(array($_POST['Employee']['fullname'], 'emptyfullname', 'emptystring'), array($_POST['Employee']['orgstructureid'], 'emptyorgstructure', 'emptystring'), array($_POST['Employee']['positionid'], 'emptyposition', 'emptystring'), array($_POST['Employee']['employeetypeid'], 'emptyemployeetype', 'emptystring'), array($_POST['Employee']['sexid'], 'emptysex', 'emptystring'), array($_POST['Employee']['birthcityid'], 'emptybirthcity', 'emptystring'), array($_POST['Employee']['birthdate'], 'emptybirthdate', 'emptystring'), array($_POST['Employee']['maritalstatusid'], 'emptymaritalstatus', 'emptystring'), array($_POST['Employee']['joindate'], 'emptyjoindate', 'emptystring'), array($_POST['Employee']['employeestatusid'], 'emptyemployeestatus', 'emptystring'), array($_POST['Employee']['levelorgid'], 'emptylevelorg', 'emptystring')));
         if ($messages == '') {
             if ((int) $_POST['Employee']['employeeid'] > 0) {
                 $model = $this->loadModel($_POST['Employee']['employeeid']);
                 $ab = Addressbook::model()->findbypk($model->addressbookid);
                 $ab->fullname = $_POST['Employee']['fullname'];
                 $ab->save();
                 $model->fullname = $_POST['Employee']['fullname'];
                 $model->oldnik = $_POST['Employee']['oldnik'];
                 $model->orgstructureid = $_POST['Employee']['orgstructureid'];
                 $model->positionid = $_POST['Employee']['positionid'];
                 $model->levelorgid = $_POST['Employee']['levelorgid'];
                 $model->employeetypeid = $_POST['Employee']['employeetypeid'];
                 $model->sexid = $_POST['Employee']['sexid'];
                 $model->birthcityid = $_POST['Employee']['birthcityid'];
                 $model->birthdate = $_POST['Employee']['birthdate'];
                 $model->religionid = $_POST['Employee']['religionid'];
                 $model->maritalstatusid = $_POST['Employee']['maritalstatusid'];
                 $model->referenceby = $_POST['Employee']['referenceby'];
                 $model->joindate = $_POST['Employee']['joindate'];
                 $model->employeestatusid = $_POST['Employee']['employeestatusid'];
                 $model->istrial = $_POST['Employee']['istrial'];
                 $model->accountno = $_POST['Employee']['accountno'];
                 $model->taxno = $_POST['Employee']['taxno'];
             } else {
                 $model = new Employee();
                 $model->attributes = $_POST['Employee'];
             }
             try {
                 if ($model->save()) {
                     $this->DeleteLock($this->menuname, $_POST['Employee']['fullname']);
                     $this->GetSMessage('insertsuccess');
                 } else {
                     $this->GetMessage($model->getErrors());
                 }
             } catch (Exception $e) {
                 $this->GetMessage($e->getMessage());
             }
         }
     }
 }
 public function ajaxProcessHideScreencast()
 {
     if ($employee = new Employee((int) Tools::getValue('id_employee'))) {
         $employee->bo_show_screencast = 0;
         if ($employee->save()) {
             $this->content = '{"status":"ok"}';
         } else {
             $this->content = '{"status":"error","msg":"not saved"}';
         }
     } else {
         $this->content = '{"status":"error", "msg":"employee does not exists"}';
     }
 }
    if (isset($_POST[$field])) {
        $value = $_POST[$field];
        $focus->{$field} = $value;
    }
}
foreach ($focus->additional_column_fields as $field) {
    if (isset($_POST[$field])) {
        $value = $_POST[$field];
        $focus->{$field} = $value;
    }
}
if (!$focus->verify_data()) {
    header("Location: index.php?action=Error&module=Users&error_string=" . urlencode($focus->error_string));
    exit;
} else {
    $focus->save();
    $return_id = $focus->id;
}
if (isset($_POST['return_module']) && $_POST['return_module'] != "") {
    $return_module = $_POST['return_module'];
} else {
    $return_module = "Users";
}
if (isset($_POST['return_action']) && $_POST['return_action'] != "") {
    $return_action = $_POST['return_action'];
} else {
    $return_action = "DetailView";
}
if (isset($_POST['return_id']) && $_POST['return_id'] != "") {
    $return_id = $_POST['return_id'];
}
//Imports
require_once 'db.php';
require_once 'Employee.php';
if (empty($_POST['name'])) {
    header("Location: ../?e=name");
    exit;
}
if (empty($_POST['un'])) {
    header("Location: ../?e=un");
    exit;
}
if (empty($_POST['pw'])) {
    header("Location: ../?e=pw");
    exit;
}
$name = $_POST['name'];
$un = $_POST['un'];
$pw = md5($_POST['pw']);
$con = connect_db();
$employee = new Employee();
$employee->grp = 2;
$employee->name = $name;
$employee->un = $un;
$employee->pw = $pw;
$employee->lists = explode(',', $_POST['listids']);
$employee->save($con);
foreach ($employee->lists as $listID) {
    $employee->addList($con, $listID);
}
$con->close();
header('Location: ../employee?_=' . $employee->id);
 /**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  */
 public function actionImport()
 {
     $model = new Employee();
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($model);
     if (isset($_POST['Employee'])) {
         if (!empty($_FILES)) {
             $tempFile = $_FILES['Employee']['tmp_name']['fileImport'];
             $fileTypes = array('xls', 'xlsx');
             // File extensions
             $fileParts = pathinfo($_FILES['Employee']['name']['fileImport']);
             if (in_array(@$fileParts['extension'], $fileTypes)) {
                 Yii::import('ext.heart.excel.EHeartExcel', true);
                 EHeartExcel::init();
                 $inputFileType = PHPExcel_IOFactory::identify($tempFile);
                 $objReader = PHPExcel_IOFactory::createReader($inputFileType);
                 $objPHPExcel = $objReader->load($tempFile);
                 $sheetData = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
                 $baseRow = 2;
                 $inserted = 0;
                 $read_status = false;
                 while (!empty($sheetData[$baseRow]['A'])) {
                     $read_status = true;
                     //$employee_id=  $sheetData[$baseRow]['A'];
                     $name = $sheetData[$baseRow]['B'];
                     $model2 = new Employee();
                     //$model2->employee_id=  $employee_id;
                     $model2->name = $name;
                     try {
                         if ($model2->save()) {
                             $inserted++;
                         }
                     } catch (Exception $e) {
                         Yii::app()->user->setFlash('error', "{$e->getMessage()}");
                         //$this->refresh();
                     }
                     $baseRow++;
                 }
                 Yii::app()->user->setFlash('success', $inserted . ' row inserted');
             } else {
                 Yii::app()->user->setFlash('warning', 'Wrong file type (xlsx, xls, and ods only)');
             }
         }
         $this->render('admin', array('model' => $model));
     } else {
         $this->render('admin', array('model' => $model));
     }
 }
Beispiel #25
0
 /**
  * Performs the work of inserting or updating the row in the database.
  *
  * If the object is new, it inserts it; otherwise an update is performed.
  * All related objects are also updated in this method.
  *
  * @param      PropelPDO $con
  * @return     int The number of rows affected by this insert/update and any referring fk objects' save() operations.
  * @throws     PropelException
  * @see        save()
  */
 protected function doSave(PropelPDO $con)
 {
     $affectedRows = 0;
     // initialize var to track total num of affected rows
     if (!$this->alreadyInSave) {
         $this->alreadyInSave = true;
         // We call the save method on the following object(s) if they
         // were passed to this object by their coresponding set
         // method.  This object relates to these object(s) by a
         // foreign key reference.
         if ($this->aPatient !== null) {
             if ($this->aPatient->isModified() || $this->aPatient->isNew()) {
                 $affectedRows += $this->aPatient->save($con);
             }
             $this->setPatient($this->aPatient);
         }
         if ($this->aEmployeeRelatedByDoctorId !== null) {
             if ($this->aEmployeeRelatedByDoctorId->isModified() || $this->aEmployeeRelatedByDoctorId->isNew()) {
                 $affectedRows += $this->aEmployeeRelatedByDoctorId->save($con);
             }
             $this->setEmployeeRelatedByDoctorId($this->aEmployeeRelatedByDoctorId);
         }
         if ($this->aWardBed !== null) {
             if ($this->aWardBed->isModified() || $this->aWardBed->isNew()) {
                 $affectedRows += $this->aWardBed->save($con);
             }
             $this->setWardBed($this->aWardBed);
         }
         if ($this->aEmployeeRelatedByWardDocId !== null) {
             if ($this->aEmployeeRelatedByWardDocId->isModified() || $this->aEmployeeRelatedByWardDocId->isNew()) {
                 $affectedRows += $this->aEmployeeRelatedByWardDocId->save($con);
             }
             $this->setEmployeeRelatedByWardDocId($this->aEmployeeRelatedByWardDocId);
         }
         if ($this->isNew()) {
             $this->modifiedColumns[] = VisitPeer::ID;
         }
         // If this object has been modified, then save it to the database.
         if ($this->isModified()) {
             if ($this->isNew()) {
                 $pk = VisitPeer::doInsert($this, $con);
                 $affectedRows += 1;
                 // we are assuming that there is only 1 row per doInsert() which
                 // should always be true here (even though technically
                 // BasePeer::doInsert() can insert multiple rows).
                 $this->setId($pk);
                 //[IMV] update autoincrement primary key
                 $this->setNew(false);
             } else {
                 $affectedRows += VisitPeer::doUpdate($this, $con);
             }
             $this->resetModified();
             // [HL] After being saved an object is no longer 'modified'
         }
         if ($this->collLabReports !== null) {
             foreach ($this->collLabReports as $referrerFK) {
                 if (!$referrerFK->isDeleted()) {
                     $affectedRows += $referrerFK->save($con);
                 }
             }
         }
         if ($this->collVisitMedicines !== null) {
             foreach ($this->collVisitMedicines as $referrerFK) {
                 if (!$referrerFK->isDeleted()) {
                     $affectedRows += $referrerFK->save($con);
                 }
             }
         }
         $this->alreadyInSave = false;
     }
     return $affectedRows;
 }
Beispiel #26
0
 static function ImportEmployee()
 {
     // Делаем запись в таблицу отчетов импорта
     $logreport = new Logreport();
     $logreport->logreport_date = date('Y-m-d');
     $logreport->save();
     self::$logreport_id = $logreport->logreport_id;
     // Идем по файлам импорта из 1С (сотрудники.txt - Сотрудники)
     foreach (['сотрудники.txt'] as $filename) {
         self::$filename = mb_convert_encoding('imp/' . $filename, 'Windows-1251', 'UTF-8');
         if (file_exists(self::$filename)) {
             ini_set('max_execution_time', 1000);
             // 1000 seconds
             ini_set('memory_limit', 1073741824);
             // 1Gbyte Max Memory
             // Определяем показатели импорта
             self::$logreport_errors = 0;
             // Не загружено записей из-за ошибок
             self::$logreport_additions = 0;
             // Записей добавлено
             self::$logreport_amount = 0;
             // Всего записей
             $i = 0;
             $handle = @fopen(self::$filename, "r");
             if ($handle) {
                 while (($subject = fgets($handle, 4096)) !== false) {
                     $i++;
                     $pattern = '/^(.+?)\\|(Поликлиника №\\s?[1,2,3] )?(.+?)\\|(.+?)\\|/ui';
                     preg_match($pattern, $subject, $matches);
                     if ($matches[0] !== NULL) {
                         $pattern = '/(^Поликлиника №)\\s?([1,2,3])\\s?$/ui';
                         $matches[2] = preg_replace($pattern, 'Взрослая $1$2', mb_strtolower($matches[2], 'UTF-8'));
                         if ($matches[3] === 'Поликлиника профилактических осмотров') {
                             $matches[2] = $matches[3];
                         }
                         $pattern = '/^(.+) БУ "Нижневартовская городская поликлиника"$/ui';
                         $matches[3] = preg_replace($pattern, '$1', $matches[3]);
                         $employee_fio = $matches[1];
                         $location = self::AssignLocationForEmployeeImport($matches[3], $matches[2]);
                         $id_dolzh = self::AssignDolzh($matches[4]);
                         // На случай если Здание у сотрудника не определено
                         $buildsql = $location->id_build === null ? 'id_build IS NULL' : 'id_build = :id_build';
                         // Находим сотрудника в базе, если не находим создаем новую запись
                         $Employee = Employee::model()->Find('employee_fio LIKE :employee_fio and id_dolzh = :id_dolzh and id_podraz = :id_podraz and ' . $buildsql, array_merge([':employee_fio' => $employee_fio, ':id_dolzh' => $id_dolzh, ':id_podraz' => $location->id_podraz], $location->id_build === null ? [] : [':id_build' => $location->id_build]));
                         if ($Employee === null) {
                             $Employee = new Employee();
                             $Employee->attributes = ['employee_fio' => $employee_fio, 'id_dolzh' => $id_dolzh, 'id_podraz' => $location->id_podraz, 'id_build' => $location->id_build];
                             $Employeelog = new Employeelog();
                             $Employeelog->id_logreport = self::$logreport_id;
                             $Employeelog->employeelog_type = 1;
                             $Employeelog->employeelog_filename = mb_convert_encoding(self::$filename, 'UTF-8', 'Windows-1251');
                             $Employeelog->employeelog_rownum = $i;
                             $Employeelog->employeelog_message = 'Запись добавлена.';
                             $Employee->scenario = 'import1c';
                             if ($Employee->validate()) {
                                 self::$logreport_additions++;
                                 $Employee->save(false);
                             } else {
                                 $Employeelog->employeelog_type = 3;
                                 $Employeelog->employeelog_message = 'Ошибка при добавлении записи: ';
                                 foreach ($Employee->getErrors() as $fields) {
                                     $Employeelog->employeelog_message .= implode(' ', $fields) . ' ';
                                 }
                                 self::$logreport_errors++;
                             }
                             $Employeelog->employee_fio = $Employee->employee_fio;
                             $Employeelog->dolzh_name = Dolzh::model()->findbyPk($Employee->id_dolzh)->dolzh_name;
                             $Employeelog->podraz_name = Podraz::model()->findbyPk($Employee->id_podraz)->podraz_name;
                             if ($Employee->id_build !== null) {
                                 $Employeelog->build_name = Build::model()->findbyPk($Employee->id_build)->build_name;
                             }
                             $Employeelog->save(false);
                         }
                     } elseif (trim($subject) !== '') {
                         $Employeelog = new Employeelog();
                         $Employeelog->id_logreport = self::$logreport_id;
                         $Employeelog->employeelog_type = 3;
                         $Employeelog->employeelog_filename = mb_convert_encoding(self::$filename, 'UTF-8', 'Windows-1251');
                         $Employeelog->employeelog_rownum = $i;
                         $Employeelog->employeelog_message = 'Ошибка при добавлении записи: Не пройдено регулярное выражение /^(.+?)\\|(Поликлиника №\\s?[1,2,3] )?(.+?)\\|(.+?)\\|/ui';
                         $Employeelog->save(false);
                         self::$logreport_errors++;
                     }
                 }
                 fclose($handle);
             }
             $logreport->logreport_additions += self::$logreport_additions;
             $logreport->logreport_errors += self::$logreport_errors;
             $logreport->logreport_amount = $i;
             $logreport->save();
         }
     }
     echo '<BR>Подразделения:<BR>';
     ARData::Data(Podraz::model(), Podraz::model()->Test())->PrintData();
     echo '<BR>Должности:<BR>';
     ARData::Data(Dolzh::model(), Dolzh::model()->Test())->PrintData();
     echo '<BR>Сотрудники:<BR>';
     ARData::Data(Employee::model(), Employee::model()->Test())->PrintData();
     echo '<BR>Лог:<BR>';
     ARData::Data(Employeelog::model(), Employeelog::model()->Test())->PrintData();
 }
 private function processImport($file)
 {
     if (Session::has('username') && (Session::get('user_type') == "Root" || Session::get('user_type') == "Admin")) {
         if (!in_array($file->getClientOriginalExtension(), array("xls", "xlsx", "csv"))) {
             Input::flash();
             return Redirect::to('employees/import')->with('message', "Invalid file selected.");
         } else {
             $filename = "upload-" . str_random(9) . "." . $file->getClientOriginalExtension();
             $file->move("uploads", $filename);
             $readFile = "uploads/" . $filename;
             $reader = Excel::selectSheetsByIndex(0)->load($readFile, function ($reader) {
             })->get();
             /*
              * 				Before validating each rows of the file uploaded, the file itself is checked if it has the valid attributes (columns)
              * 				using the algorithm found below.
              * 
              * 				1. File is read.
              * 				2. Boolean variable $excelIsValid to check if the file is valid. Set to false by default.
              * 	
              */
             $excelChecker = Excel::selectSheetsByIndex(0)->load($readFile, function ($reader) {
             })->get()->toArray();
             $excelIsValid = false;
             /*
              * 				3. Loop through the excel file and check if at least once all the columns have been present.
              * 				4. If it does, $excelIsValid is set to true.
              * 				5. If $excelIsValid is still false by end of the loop, it is automatically assumed that the file is:
              * 					A.) Empty
              * 					B.) Does not have the right attributes.
              * 					C.) Has valid columns, but does not have any valid entry.
              * 					
              */
             foreach ($excelChecker as $ex) {
                 if (isset($ex["employeenumber"]) && isset($ex["lastname"]) && isset($ex["firstname"]) && isset($ex["startdate"]) && isset($ex["status"])) {
                     $excelIsValid = true;
                 }
             }
             /*				6. If file is invalid, redirect to import form and return an error. */
             if (!$excelIsValid) {
                 Input::flash();
                 File::delete($readFile);
                 return Redirect::to('employees/import')->with('message', "Excel file has invalid attributes. Please download the form.");
             }
             /*				
              * 				CHECKING EXCEL FILE FOR ERRORS WHILE READING THE ROWS
              * 
              * 				1. $hasError is a Boolean variable that is simply used to tell if any error has been found.
              * 					This variable is, by default, set to false. If any error has been detected, it is set to true,
              * 					regardless of how many errors has been detected.
              * 
              * 				2. $rowIndex indexes which row the reader is currently reading. Default value set to 1 because
              * 					the first row of excel files is automatically set as the attribute row. When the reader reads each row,
              * 					$rowIndex is incremented. For example, reader is currently reading row 2, $rowIndex will then be incremented,
              * 					setting its value to 2, thus the row number.
              * 
              * 				3. $rowsWithErrors is the array of the rows with errors. To explain further, let's say excel file has 10 readable (non-attrib)
              * 					rows. No errors were found from rows number 2-8, but errors were found in rows 9, 10, and 11. These 9, 10, and 11
              * 					will then be in the $rowsWithError.
              * 
              * 				4. $error array is the variable that will be used to collect all errors found from the excel file.
              * 					This is a two-dimensional array.
              * 
              * 
              */
             $hasError = false;
             //Detects if there are any errors.
             $hasCorrectRows = false;
             $rowIndex = 1;
             //Indexes which row the reader is reading.
             $rowsWithErrors = array();
             //This is used to contain in an array the row numbers of the rows with error.
             $error = array();
             //Error details collector.
             foreach ($reader as $r) {
                 /*
                  * 				5. Here, we immediately increment the value of $rowIndex, since the variable will be used in the core logic of this method.
                  * 				
                  * 				6. $errorCount variable is a variable used in every loop. Set to 0 when the loop begins, so it always comes back to 0 for every loop.
                  * 					$errorCount is used to track the number of errors for the current row. This variable goes hand in hand with the
                  * 					$rowsWithError array when publishing the rows with errors, and the error details for each row with error.
                  * 
                  * 					This is how $rowsWithError and $rowCount will be used:
                  * 
                  * 					for each $rowWithErrors:
                  * 						Row $rowWithErrors Index:
                  * 							Errors Found :
                  * 							$rowCount 1. Foo bar
                  * 							$rowCount 2. Jane Doe etc..
                  * 
                  * 
                  */
                 $rowIndex += 1;
                 $errorCount = 0;
                 //Counts the number of errors for the currect row.
                 $rowHasError = false;
                 //Check if this row has error. I will use this before the reading of the row ends.
                 //					If $rowHasError is still false by end of the reading, then I will write it in the database.
                 /*
                  * 
                  */
                 $start_date = !empty(trim($r->startdate)) ? trim($r->startdate) : "1994-04-16";
                 $validator = Validator::make(array("employee number" => trim($r->employeenumber), "last name" => trim($r->lastname), "first name" => trim($r->firstname), "username" => trim($r->username), "start date" => trim($r->startdate), "end date" => trim($r->enddate), "email" => trim($r->email), "status" => trim($r->status)), array("employee number" => "required|numeric|unique:tbl_employees,employee_number", "last name" => "required", "first name" => "required", "username" => "unique:tbl_employees,username", "start date" => "required|date:Y-m-d", "end date" => "date:Y-m-d|after:" . $start_date, "email" => "unique:tbl_employees,email", "status" => "required"), array("after" => "The :attribute must be after the employee start date."));
                 if ($validator->fails()) {
                     /* 					7. When error has been found, $rowsWithError is immediately updated. Also, $hasError and $rowHasError are set to true.*/
                     $hasError = true;
                     $rowHasError = true;
                     $rowsWithErrors[$rowIndex] = $rowIndex;
                     /* 					8. Then I will check which fields has error.
                      * 
                     *					9. If an error has been found in a certain field,
                     *					   I will loop through the errors found on that field, increment the $errorCount (which, again, tracks
                     *					   how many errors has been found on a certain row.), update the two-dimensional $error array. 
                     *					   Please note that the first array of $error contains the row number which the errors found belong to.
                     *
                     */
                     if ($validator->messages()->get("employee number")) {
                         foreach ($validator->messages()->get("employee number") as $e) {
                             $errorCount += 1;
                             $error[$rowIndex][$errorCount] = $errorCount . ". " . $e . "<br/>";
                         }
                     }
                     if ($validator->messages()->get("last name")) {
                         foreach ($validator->messages()->get("last name") as $e) {
                             $errorCount += 1;
                             $error[$rowIndex][$errorCount] = $errorCount . ". " . $e . "<br/>";
                         }
                     }
                     if ($validator->messages()->get("first name")) {
                         foreach ($validator->messages()->get("first name") as $e) {
                             $errorCount += 1;
                             $error[$rowIndex][$errorCount] = $errorCount . ". " . $e . "<br/>";
                         }
                     }
                     if ($validator->messages()->get("username")) {
                         foreach ($validator->messages()->get("username") as $e) {
                             $errorCount += 1;
                             $error[$rowIndex][$errorCount] = $errorCount . ". " . $e . "<br/>";
                         }
                     }
                     if ($validator->messages()->get("start date")) {
                         foreach ($validator->messages()->get("start date") as $e) {
                             $errorCount += 1;
                             $error[$rowIndex][$errorCount] = $errorCount . ". " . $e . "<br/>";
                         }
                     }
                     if ($validator->messages()->get("end date")) {
                         foreach ($validator->messages()->get("end date") as $e) {
                             $errorCount += 1;
                             $error[$rowIndex][$errorCount] = $errorCount . ". " . $e . "<br/>";
                         }
                     }
                     if ($validator->messages()->get("email")) {
                         foreach ($validator->messages()->get("email") as $e) {
                             $errorCount += 1;
                             $error[$rowIndex][$errorCount] = $errorCount . ". " . $e . "<br/>";
                         }
                     }
                     if ($validator->messages()->get("status")) {
                         foreach ($validator->messages()->get("status") as $e) {
                             $errorCount += 1;
                             $error[$rowIndex][$errorCount] = $errorCount . ". " . $e . "<br/>";
                         }
                     }
                 }
                 if (!preg_match('/^[\\pL.-\\s]+$/u', $r->firstname) || !preg_match('/^[\\pL.-\\s]+$/u', $r->lastname)) {
                     $hasError = true;
                     //This will only matter if no errors has been found above.
                     $rowHasError = true;
                     //This will only matter if no errors has been found above.
                     $rowsWithErrors[$rowIndex] = $rowIndex;
                     //This will only matter if no errors has been found above.
                     $errorCount += 1;
                     $error[$rowIndex][$errorCount] = $errorCount . ". " . "First name/last name fields must only contain alphabetic characters and whitespaces." . "<br/>";
                 }
                 if (!is_numeric($r->manager)) {
                     $hasError = true;
                     //This will only matter if no errors has been found above.
                     $rowHasError = true;
                     //This will only matter if no errors has been found above.
                     $rowsWithErrors[$rowIndex] = $rowIndex;
                     //This will only matter if no errors has been found above.
                     $errorCount += 1;
                     $error[$rowIndex][$errorCount] = $errorCount . ". " . "Manager ID should be numeric." . "<br/>";
                 }
                 if (is_numeric($r->manager) && !Manager::find($r->manager)) {
                     $hasError = true;
                     //This will only matter if no errors has been found above.
                     $rowHasError = true;
                     //This will only matter if no errors has been found above.
                     $rowsWithErrors[$rowIndex] = $rowIndex;
                     //This will only matter if no errors has been found above.
                     $errorCount += 1;
                     $error[$rowIndex][$errorCount] = $errorCount . ". " . "Invalid manager ID." . "<br/>";
                 }
                 if (empty(trim($r->nsnid)) && !in_array(strtolower($r->status), array("academy", "ojt", "contractual", "graduate", "obsolete"))) {
                     $hasError = true;
                     //This will only matter if no errors has been found above.
                     $rowHasError = true;
                     //This will only matter if no errors has been found above.
                     $rowsWithErrors[$rowIndex] = $rowIndex;
                     //This will only matter if no errors has been found above.
                     $errorCount += 1;
                     $error[$rowIndex][$errorCount] = $errorCount . ". " . "The NSN ID is required." . "<br/>";
                 }
                 if (!empty($r->nsnid) && !is_numeric(trim($r->nsnid)) && !in_array($r->status, array("academy", "ojt", "contractual", "graduate", "obsolete"))) {
                     $hasError = true;
                     //This will only matter if no errors has been found above.
                     $rowHasError = true;
                     //This will only matter if no errors has been found above.
                     $rowsWithErrors[$rowIndex] = $rowIndex;
                     //This will only matter if no errors has been found above.
                     $errorCount += 1;
                     $error[$rowIndex][$errorCount] = $errorCount . ". " . "The NSN ID should be numeric." . "<br/>";
                 }
                 if (!empty($r->nsnid) && Employee::where("nsn_id", "=", $r->nsnid)->first()) {
                     $hasError = true;
                     //This will only matter if no errors has been found above.
                     $rowHasError = true;
                     //This will only matter if no errors has been found above.
                     $rowsWithErrors[$rowIndex] = $rowIndex;
                     //This will only matter if no errors has been found above.
                     $errorCount += 1;
                     $error[$rowIndex][$errorCount] = $errorCount . ". " . "NSN ID already exists." . "<br/>";
                 }
                 if (!empty($r->email) && !filter_var(trim($r->email), FILTER_VALIDATE_EMAIL)) {
                     $hasError = true;
                     //This will only matter if no errors has been found above.
                     $rowHasError = true;
                     //This will only matter if no errors has been found above.
                     $rowsWithErrors[$rowIndex] = $rowIndex;
                     //This will only matter if no errors has been found above.
                     $errorCount += 1;
                     $error[$rowIndex][$errorCount] = $errorCount . ". " . "Invalid e-mail address." . "<br/>";
                 }
                 if (is_numeric($r->businessline) && !BusinessLine::find($r->businessline)) {
                     $hasError = true;
                     //This will only matter if no errors has been found above.
                     $rowHasError = true;
                     //This will only matter if no errors has been found above.
                     $rowsWithErrors[$rowIndex] = $rowIndex;
                     //This will only matter if no errors has been found above.
                     $errorCount += 1;
                     $error[$rowIndex][$errorCount] = $errorCount . ". " . "Invalid Business Line ID." . "<br/>";
                 }
                 if (is_numeric($r->unit) && !Unit::find($r->unit)) {
                     $hasError = true;
                     //This will only matter if no errors has been found above.
                     $rowHasError = true;
                     //This will only matter if no errors has been found above.
                     $rowsWithErrors[$rowIndex] = $rowIndex;
                     //This will only matter if no errors has been found above.
                     $errorCount += 1;
                     $error[$rowIndex][$errorCount] = $errorCount . ". " . "Invalid Unit ID." . "<br/>";
                 }
                 if (is_numeric($r->unit) && is_numeric($r->businessline) && (Unit::find($r->unit) && !Unit::where("id", "=", $r->unit)->where("businessline_id", "=", $r->businessline)->first())) {
                     $hasError = true;
                     //This will only matter if no errors has been found above.
                     $rowHasError = true;
                     //This will only matter if no errors has been found above.
                     $rowsWithErrors[$rowIndex] = $rowIndex;
                     //This will only matter if no errors has been found above.
                     $errorCount += 1;
                     $error[$rowIndex][$errorCount] = $errorCount . ". " . "Selected Unit ID does not belong to the selected Business Line ID." . "<br/>";
                 }
                 if (!in_array(strtolower($r->status), array("ojt", "contractual", "nsn guest", "academy", "graduate", "on-board", "resigned", "obsolete"))) {
                     $hasError = true;
                     //This will only matter if no errors has been found above.
                     $rowHasError = true;
                     //This will only matter if no errors has been found above.
                     $rowsWithErrors[$rowIndex] = $rowIndex;
                     //This will only matter if no errors has been found above.
                     $errorCount += 1;
                     $error[$rowIndex][$errorCount] = $errorCount . ". " . "Invalid employee status." . "<br/>";
                 }
                 if (!$rowHasError) {
                     $hasCorrectRows = true;
                     $desc = "(" . Session::get('user_type') . ") " . "<strong>" . Session::get('username') . "</strong> has added employee <strong>" . trim($r->firstname) . " " . trim($r->lastname) . "</strong>, employee number <strong>" . trim($r->employeenumber) . "</strong>, with status <strong>" . trim($r->status) . "</strong>.";
                     $employee = new Employee();
                     $employee->employee_number = $r->employeenumber;
                     $employee->last_name = trim($r->lastname);
                     $employee->first_name = trim($r->firstname);
                     $employee->username = trim($r->username) != null ? trim($r->username) : null;
                     $employee->nickname = trim($r->nickname) != null ? trim($r->nickname) : null;
                     $employee->manager_id = $r->manager != null ? $r->manager : null;
                     $employee->start_date = $r->startdate;
                     $employee->end_date = $r->enddate != null ? $r->enddate : null;
                     $employee->nsn_id = $r->nsnid != null ? $r->nsnid : null;
                     $employee->email = trim($r->email) != null ? trim($r->email) : null;
                     $employee->business_line_id = $r->businessline != null ? $r->businessline : null;
                     $employee->unit_id = $r->unit != null ? $r->unit : null;
                     $employee->subunit = trim($r->subunit) != null ? trim($r->subunit) : null;
                     $employee->cellphone_number = trim($r->cellphonenumber) != null ? trim($r->cellphonenumber) : null;
                     $employee->status = trim($r->status);
                     $employee->save();
                     //Log the changes made
                     $newLog = new UserLog();
                     $newLog->description = $desc;
                     $newLog->user_id = Session::get('user_id');
                     $newLog->type = "Employees";
                     $newLog->save();
                 }
             }
             File::delete($readFile);
             if ($hasCorrectRows) {
                 //Log the changes made
                 $desc = "(" . Session::get("user_type") . ") <b>" . Session::get("username") . "</b> has imported data to the employees database. ";
                 $newLog = new UserLog();
                 $newLog->description = $desc;
                 $newLog->user_id = Session::get('user_id');
                 $newLog->type = "Employees";
                 $newLog->save();
             }
             return $this->importResult($hasError, $hasCorrectRows, $rowsWithErrors, $error);
         }
     } else {
         return Redirect::to('/');
     }
 }
Beispiel #28
0
 } elseif ($isEmployeeType === 'is_supervisor') {
     //Supervisor:2
     $employee->employee_type = 2;
     $employee->manager_id = $data["department_head"];
     $employee->supervisor_id = 0;
 } elseif ($isEmployeeType === 'is_employee') {
     //Employee:0
     $employee->employee_type = 0;
     $employee->manager_id = $data["department_head"];
     $employee->supervisor_id = $data["supervisor_id"];
 }
 $employee->company_id = $data["company_id"];
 $employee->department_id = $data["department_id"];
 $employee->position_id = $data["position_id"];
 $email = !empty($data['email']) ? $data['email'] : strtolower($employeeUpdate->firstname) . '.' . strtolower($employeeUpdate->lastname) . '@backofficeph.com';
 if ($employee->save()) {
     try {
         // Create the user
         $SentryUser = Sentry::createUser(array('email' => trim($email), 'employee_id' => $employee->id, 'employee_number' => trim(ucwords($data["employee_number"])), 'password' => $data['password'], 'first_name' => trim(ucwords($data['firstname'])), 'last_name' => trim(ucwords($data['lastname'])), 'activated' => true));
         if ($SentryUser) {
             $userId = $SentryUser->id;
             DB::table('employee_setting')->insert(array('employee_id' => $employee->id, 'has_overtime' => 1, 'has_break' => 1, 'break_time' => '01:00:00', 'hours_per_day' => number_format(8, 2)));
             if (isset($userId)) {
                 DB::table('users_groups')->insert(array('user_id' => $userId, 'group_id' => $data["role_id"]));
             }
             Session::put('newEmployeeId', $employee->id);
             //return Redirect::route('adminDashboard');
             return Redirect::route('adminUserNewSchedule', array('newEmployeeId' => $employee->id));
         }
     } catch (Cartalyst\Sentry\Users\LoginRequiredException $e) {
         echo 'Login field is required.';
Beispiel #29
0
        $file = $filename . '.' . $ext;
        Input::file('employees')->move($destination, $file);
        Excel::selectSheetsByIndex(0)->load(public_path() . '/migrations/' . $file, function ($reader) {
            $results = $reader->get();
            foreach ($results as $result) {
                $employee = new Employee();
                $employee->personal_file_number = $result->employment_number;
                $employee->first_name = $result->first_name;
                $employee->last_name = $result->surname;
                $employee->middle_name = $result->other_names;
                $employee->identity_number = $result->id_number;
                $employee->pin = $result->kra_pin;
                $employee->social_security_number = $result->nssf_number;
                $employee->hospital_insurance_number = $result->nhif_number;
                $employee->email_office = $result->email_address;
                $employee->save();
            }
        });
    }
    return Redirect::back()->with('notice', 'Employees have been succeffully imported');
});
/* #################### IMPORT EARNINGS ################################## */
Route::post('import/earnings', function () {
    if (Input::hasFile('earnings')) {
        $destination = public_path() . '/migrations/';
        $filename = str_random(12);
        $ext = Input::file('earnings')->getClientOriginalExtension();
        $file = $filename . '.' . $ext;
        Input::file('earnings')->move($destination, $file);
        Excel::selectSheetsByIndex(0)->load(public_path() . '/migrations/' . $file, function ($reader) {
            $results = $reader->get();
Beispiel #30
0
 public function executeAddStaff(sfWebRequest $request)
 {
     if ($request->isMethod('Post')) {
         /*Varialbes for Redirecting 
         		$user_name = $this->getRequestParameter('user_name');
         		$password = $this->getRequestParameter('password');
         		
         		if (strlen($password) != 0)
         			{
         			$password = md5($password);
         			}
         		
         		else $password = '';*/
         // Setting Department from Selected Designation
         $a = new Criteria();
         $a->add(DesignationPeer::ID, $this->getRequestParameter('designation_id'));
         $designation_record = DesignationPeer::DoSelectOne($a);
         $department_id = $designation_record->getDepartmentId();
         // Checking if Entered Username already exist
         /*if($user_name != NULL)
         		{
         			$c = new Criteria ( );
         			$c->add(UserPeer::STATUS, Constant::RECORD_STATUS_DELETED, Criteria::NOT_EQUAL );
         			$c->add(UserPeer::USER, $user_name);
         			$check_username = UserPeer::doSelectOne($c);
         			
         			if ($check_username)
         				{
         				$this->getUser ()->setFlash ( 'ERROR_MESSAGE', 'Username Already exist. Please Choose Different Username.' );
         				$this->redirect ('Register/add');
         				}
         		}*/
         $employee = new Employee();
         $employee->setRoleId($this->getRequestParameter('role_id'));
         $employee->setName($this->getRequestParameter('name'));
         $employee->setCnic($this->getRequestParameter('cnic'));
         $employee->setDob($this->getRequestParameter('dob'));
         $employee->setGender($this->getRequestParameter('gender[0]'));
         $employee->setContactCell($this->getRequestParameter('contact_cell'));
         $employee->setContactRes($this->getRequestParameter('contact_res'));
         $employee->setContactOff($this->getRequestParameter('contact_off'));
         $employee->setEmergencyContact($this->getRequestParameter('emergency_contact'));
         $employee->setMailAddress($this->getRequestParameter('mail_address'));
         $employee->setDesignationId($this->getRequestParameter('designation_id'));
         $employee->setDepartmentId($department_id);
         //$employee->setRoleId(2);
         $employee->setEmploymentDate($this->getRequestParameter('employment_date'));
         $employee->setLocalResident($this->getRequestParameter('local[0]'));
         $employee->setQualification($this->getRequestParameter('qualification'));
         $employee->setEmpCategory('staff');
         $employee->setStatus(Constant::RECORD_STATUS_ACTIVE);
         $employee->save();
         $this->getUser()->setFlash('SUCCESS_MESSAGE', Constant::REGISTRATION_ACCOUNT_APPROVAL);
         $this->redirect('Employee/list');
         /*if($user_name != NULL)
         			{
         				
         				$user = new User();
         				$user->setEmployeeId($employee_id);
         				$user->setUser($user_name);
         				$user->setPassword($password);
         				$user->setStatus(Constant::RECORD_STATUS_ACTIVE);
         				$user->save();
         	
         				// TODO: Default Rights here
         				
         			}// END if
         				
         			$this->getUser ()->setFlash ( 'SUCCESS_MESSAGE', Constant::REGISTRATION_ACCOUNT_APPROVAL );
         			$this->redirect('Register/list');
         			
         			*/
     }
     // end IF
 }