/**
  * Show the form for creating a new resource.
  *
  * @return Response
  */
 public function create()
 {
     $formgroups = FormGroup::lists('group_desc', 'id')->all();
     $activitytypes = FormType::lists('form_type', 'id')->all();
     $multiselects = MultiSelect::lists('option', 'id')->all();
     $singleselects = SingleSelect::lists('option', 'id')->all();
     return view('form.create', compact('formgroups', 'activitytypes', 'multiselects', 'singleselects'));
 }
Ejemplo n.º 2
0
 /**
  * Build a form group.
  *
  * @param $fid
  * @param Request $request
  * @return FormGroup
  */
 private function buildGroup($fid, Request $request)
 {
     $group = new FormGroup();
     $group->name = $request['name'];
     $group->fid = $fid;
     $permissions = ['create', 'edit', 'delete', 'ingest', 'modify', 'destroy'];
     foreach ($permissions as $permission) {
         if (!is_null($request[$permission])) {
             $group[$permission] = 1;
         } else {
             $group[$permission] = 0;
         }
     }
     $group->save();
     return $group;
 }
 /**
  * Update the specified resource in storage.
  *
  * @param  Request  $request
  * @param  int  $id
  * @return Response
  */
 public function update(Request $request, $id)
 {
     $group = FormGroup::findOrFail($id);
     $this->validate($request, ['group_desc' => 'required||max:100|unique_with:form_groups,' . $id]);
     \DB::beginTransaction();
     try {
         $group->group_desc = strtoupper($request->group_desc);
         $group->secondary_display = $request->secondary_display ? 1 : 0;
         $group->osa = $request->osa ? 1 : 0;
         $group->sos = $request->sos ? 1 : 0;
         $group->custom = $request->custom ? 1 : 0;
         $group->perfect_store = $request->perfect_store ? 1 : 0;
         $group->update();
         \DB::commit();
         Session::flash('flash_message', 'Form Group successfully updated!');
         return redirect()->route("formgroup.edit", [$id]);
     } catch (Exception $e) {
         DB::rollBack();
         return redirect()->back();
     }
 }
 public function storeform(Request $request, $id)
 {
     // dd($request->all());
     $this->validate($request, ['category' => 'required', 'group' => 'required', 'prompt' => 'required', 'formtype' => 'required']);
     \DB::beginTransaction();
     try {
         $template = AuditTemplate::find($id);
         $form_type = FormType::find($request->formtype);
         $prompt = $request->prompt;
         foreach ($request->category as $cat_id) {
             $category = FormCategory::find($cat_id);
             $cat_order = 1;
             $a_cat_id = 0;
             $clast_cnt = AuditTemplateCategory::getLastOrder($template->id);
             if (empty($clast_cnt)) {
                 $a_cat = AuditTemplateCategory::create(['category_order' => $cat_order, 'audit_template_id' => $template->id, 'category_id' => $category->id]);
                 $a_cat_id = $a_cat->id;
             } else {
                 $cat = AuditTemplateCategory::categoryExist($template->id, $category->id);
                 if (empty($cat)) {
                     $cat_order = $clast_cnt->category_order + 1;
                     $a_cat = AuditTemplateCategory::create(['category_order' => $cat_order, 'audit_template_id' => $template->id, 'category_id' => $category->id]);
                     $a_cat_id = $a_cat->id;
                 } else {
                     $a_cat_id = $cat->id;
                 }
             }
             foreach ($request->group as $grp_id) {
                 $group = FormGroup::find($grp_id);
                 $grp_order = 1;
                 $a_grp_id = 0;
                 $glast_cnt = AuditTemplateGroup::getLastOrder($a_cat_id);
                 if (empty($glast_cnt)) {
                     $a_grp = AuditTemplateGroup::create(['group_order' => $grp_order, 'audit_template_category_id' => $a_cat_id, 'form_group_id' => $group->id]);
                     $a_grp_id = $a_grp->id;
                 } else {
                     $grp = AuditTemplateGroup::categoryExist($a_cat_id, $group->id);
                     if (empty($grp)) {
                         $grp_order = $glast_cnt->group_order + 1;
                         $a_grp = AuditTemplateGroup::create(['group_order' => $grp_order, 'audit_template_category_id' => $a_cat_id, 'form_group_id' => $group->id]);
                         $a_grp_id = $a_grp->id;
                     } else {
                         $a_grp_id = $grp->id;
                     }
                 }
                 $form = Form::create(array('audit_template_id' => $template->id, 'form_type_id' => $form_type->id, 'prompt' => strtoupper($prompt), 'required' => $request->required == '1' ? 1 : 0, 'expected_answer' => $request->expected_answer == '1' ? 1 : 0, 'exempt' => $request->exempt == '1' ? 1 : 0));
                 if ($request->formtype == 9) {
                     $multiData = array();
                     foreach ($request->multiselect as $option) {
                         $multiData[] = array('form_id' => $form->id, 'multi_select_id' => $option);
                     }
                     if (count($multiData) > 0) {
                         FormMultiSelect::insert($multiData);
                     }
                 }
                 if ($request->formtype == 10) {
                     $singleData = array();
                     foreach ($request->singleselect as $option) {
                         $singleData[] = array('form_id' => $form->id, 'single_select_id' => $option);
                     }
                     if (count($singleData) > 0) {
                         FormSingleSelect::insert($singleData);
                     }
                 }
                 if ($request->formtype == 11) {
                     if ($request->has('formula')) {
                         $text = $request->formula;
                         preg_match_all('/:(.*?):/', $text, $matches);
                         $index = array();
                         foreach ($matches[1] as $value) {
                             $split_up = explode('_', $value);
                             $last_item = $split_up[count($split_up) - 1];
                             $index[] = $last_item;
                         }
                         $formula1 = $text;
                         foreach ($matches[1] as $key => $a) {
                             $formula1 = str_replace(':' . $a . ':', $index[$key], $formula1);
                         }
                         $formformula = new FormFormula();
                         $formformula->form_id = $form->id;
                         $formformula->formula = $formula1;
                         $formformula->formula_desc = $request->formula;
                         $formformula->save();
                     }
                 }
                 if ($request->formtype == 12) {
                     if ($request->has('condition')) {
                     }
                 }
                 $order = 1;
                 $a_frm_id = 0;
                 $last_cnt = AuditTemplateForm::getLastOrder($a_grp_id);
                 if (!empty($last_cnt)) {
                     $order = $last_cnt->order + 1;
                 }
                 AuditTemplateForm::insert(array('audit_template_group_id' => $a_grp_id, 'order' => $order, 'audit_template_id' => $template->id, 'form_id' => $form->id));
             }
         }
         \DB::commit();
         Session::flash('flash_message', 'Template successfully added!');
         return redirect()->route("audittemplate.form", $id);
     } catch (Exception $e) {
         DB::rollBack();
         Session::flash('flash_message', 'An error occured in adding form!');
         return redirect()->back();
     }
 }
Ejemplo n.º 5
0
 /**
  * Creates the form's admin Group.
  *
  * @param $project
  * @param $request
  * @return FormGroup
  */
 private function makeAdminGroup(Form $form, Request $request)
 {
     $groupName = $form->name;
     $groupName .= ' Admin Group';
     $adminGroup = new FormGroup();
     $adminGroup->name = $groupName;
     $adminGroup->fid = $form->fid;
     $adminGroup->save();
     $formProject = $form->project()->first();
     $projectAdminGroup = $formProject->adminGroup()->first();
     $projectAdmins = $projectAdminGroup->users()->get();
     $idArray = [];
     foreach ($projectAdmins as $projectAdmin) {
         $idArray[] .= $projectAdmin->id;
     }
     if (!is_null($request['admins'])) {
         $idArray = array_unique(array_merge($request['admins'], $idArray));
     }
     if (!empty($idArray)) {
         $adminGroup->users()->attach($idArray);
     }
     $adminGroup->create = 1;
     $adminGroup->edit = 1;
     $adminGroup->delete = 1;
     $adminGroup->ingest = 1;
     $adminGroup->modify = 1;
     $adminGroup->destroy = 1;
     $adminGroup->save();
     return $adminGroup;
 }
Ejemplo n.º 6
0
 public function restoreData(Request $request)
 {
     $this->json_file = null;
     $this->decoded_json = null;
     $users_exempt_from_lockout = new Collection();
     $users_exempt_from_lockout->put(1, 1);
     //Add another one of these with (userid,userid) to exempt extra users
     $this->lockUsers($users_exempt_from_lockout);
     if ($request->session()->has("restore_file_path")) {
         $filepath = $request->session()->get("restore_file_path");
         $request->session()->forget("restore_file_path");
     } else {
         return $this->ajaxResponse(false, "You did not select a valid restore point or upload a valid backup file");
     }
     try {
         $this->json_file = Storage::get($filepath);
     } catch (\Exception $e) {
         $this->ajaxResponse(false, "The backup file couldn't be opened.  Make sure it still exists and the permissions are correct.");
     }
     try {
         $this->decoded_json = json_decode($this->json_file);
         $this->decoded_json->kora3;
     } catch (\Exception $e) {
         $this->ajaxResponse(false, "The backup file contains invalid JSON data, it may be corrupt or damaged.  Check the file or try another one.\n            The restore did not start, so data already in the database was not deleted.");
     }
     $backup_data = $this->decoded_json;
     //Delete all existing data
     try {
         foreach (User::all() as $User) {
             if ($User->id == 1) {
                 //Do not delete the default admin user
                 continue;
             } else {
                 $User->delete();
             }
         }
         foreach (Project::all() as $Project) {
             $Project->delete();
         }
         foreach (Form::all() as $Form) {
             $Form->delete();
         }
         foreach (Field::all() as $Field) {
             $Field->delete();
         }
         foreach (Record::all() as $Record) {
             $Record->delete();
         }
         foreach (Metadata::all() as $Metadata) {
             $Metadata->delete();
         }
         foreach (Token::all() as $Token) {
             $Token->delete();
         }
         foreach (Revision::all() as $Revision) {
             $Revision->delete();
         }
         foreach (DateField::all() as $DateField) {
             $DateField->delete();
         }
         foreach (FormGroup::all() as $FormGroup) {
             $FormGroup->delete();
         }
         foreach (GeneratedListField::all() as $GeneratedListField) {
             $GeneratedListField->delete();
         }
         foreach (ListField::all() as $ListField) {
             $ListField->delete();
         }
         foreach (MultiSelectListField::all() as $MultiSelectListField) {
             $MultiSelectListField->delete();
         }
         foreach (NumberField::all() as $NumberField) {
             $NumberField->delete();
         }
         foreach (ProjectGroup::all() as $ProjectGroup) {
             $ProjectGroup->delete();
         }
         foreach (RichTextField::all() as $RichTextField) {
             $RichTextField->delete();
         }
         foreach (ScheduleField::all() as $ScheduleField) {
             $ScheduleField->delete();
         }
         foreach (TextField::all() as $TextField) {
             $TextField->delete();
         }
     } catch (\Exception $e) {
         $this->ajaxResponse(false, "There was a problem when attempting to remove existing information from the\n            database, the database user may not have permission to do this or the database may be in use.");
     }
     try {
         //This try-catch is for non-QueryExceptions, like if a table is missing entirely from the JSON data
         // User
         foreach ($backup_data->users as $user) {
             try {
                 $new_user = User::create(array("username" => $user->username, "name" => $user->name, "email" => $user->email, "password" => $user->password, "organization" => $user->organization, "language" => $user->language, "regtoken" => $user->regtoken));
                 $new_user->id = $user->id;
                 $new_user->admin = $user->admin;
                 $new_user->active = $user->active;
                 $new_user->remember_token = $user->remember_token;
                 $new_user->created_at = $user->created_at;
                 $new_user->updated_at = $user->updated_at;
                 $new_user->locked_out = true;
                 $new_user->save();
             } catch (\Exception $e) {
                 $this->ajax_error_list->push($e->getMessage());
             }
         }
         // Project
         foreach ($backup_data->projects as $project) {
             //$new_project = Project::create(array("name" => $project->name, "slug" => $project->slug, "description" => $project->description, "adminGID" => $project->adminGID, "active" => $project->active));
             try {
                 $new_project = Project::create(array());
                 $new_project->name = $project->name;
                 $new_project->slug = $project->slug;
                 $new_project->description = $project->description;
                 $new_project->adminGID = $project->adminGID;
                 $new_project->active = $project->active;
                 $new_project->pid = $project->pid;
                 $new_project->created_at = $project->created_at;
                 $new_project->updated_at = $project->updated_at;
                 $new_project->save();
             } catch (QueryException $e) {
                 $this->ajax_error_list->push($e->getMessage());
             }
         }
         // Form
         foreach ($backup_data->forms as $form) {
             try {
                 $new_form = Form::create(array("pid" => $form->pid));
                 $new_form->fid = $form->fid;
                 $new_form->name = $form->name;
                 $new_form->slug = $form->slug;
                 $new_form->description = $form->description;
                 $new_form->adminGID = $form->adminGID;
                 $new_form->layout = $form->layout;
                 $new_form->public_metadata = $form->public_metadata;
                 $new_form->layout = $form->layout;
                 $new_form->adminGID = $form->adminGID;
                 $new_form->created_at = $form->created_at;
                 $new_form->updated_at = $form->updated_at;
                 $new_form->save();
             } catch (QueryException $e) {
                 $this->ajax_error_list->push($e->getMessage());
             }
         }
         // Field
         foreach ($backup_data->fields as $field) {
             try {
                 $new_field = Field::create(array("pid" => $field->pid, "fid" => $field->fid, "order" => $field->order, "type" => $field->type, "name" => $field->name, "slug" => $field->slug, "desc" => $field->desc, "required" => $field->required, "default" => $field->default, "options" => $field->options));
                 $new_field->flid = $field->flid;
                 $new_field->default = $field->default;
                 $new_field->options = $field->options;
                 $new_field->created_at = $field->created_at;
                 $new_field->updated_at = $field->updated_at;
                 $new_field->save();
             } catch (QueryException $e) {
                 $this->ajax_error_list->push($e->getMessage());
             }
         }
         // FormGroup
         foreach ($backup_data->formgroups as $formgroup) {
             try {
                 $new_formgroup = new FormGroup();
                 $new_formgroup->name = $formgroup->group_data->name;
                 $new_formgroup->fid = $formgroup->group_data->fid;
                 $new_formgroup->create = $formgroup->group_data->create;
                 $new_formgroup->edit = $formgroup->group_data->edit;
                 $new_formgroup->ingest = $formgroup->group_data->ingest;
                 $new_formgroup->delete = $formgroup->group_data->delete;
                 $new_formgroup->modify = $formgroup->group_data->modify;
                 $new_formgroup->destroy = $formgroup->group_data->destroy;
                 $new_formgroup->id = $formgroup->group_data->id;
                 $new_formgroup->created_at = $formgroup->group_data->created_at;
                 $new_formgroup->updated_at = $formgroup->group_data->updated_at;
                 $new_formgroup->save();
                 foreach ($formgroup->user_data as $user_id) {
                     $new_formgroup->users()->attach($user_id);
                 }
             } catch (QueryException $e) {
                 $this->ajax_error_list->push($e->getMessage());
             }
         }
         // ProjectGroup
         foreach ($backup_data->projectgroups as $projectgroup) {
             try {
                 $new_projectgroup = new ProjectGroup();
                 $new_projectgroup->id = $projectgroup->group_data->id;
                 $new_projectgroup->name = $projectgroup->group_data->name;
                 $new_projectgroup->pid = $projectgroup->group_data->pid;
                 $new_projectgroup->create = $projectgroup->group_data->create;
                 $new_projectgroup->edit = $projectgroup->group_data->edit;
                 $new_projectgroup->delete = $projectgroup->group_data->delete;
                 $new_projectgroup->created_at = $projectgroup->group_data->created_at;
                 $new_projectgroup->updated_at = $projectgroup->group_data->updated_at;
                 $new_projectgroup->save();
                 foreach ($projectgroup->user_data as $user_id) {
                     $new_projectgroup->users()->attach($user_id);
                 }
             } catch (QueryException $e) {
                 $this->ajax_error_list->push($e->getMessage());
             }
         }
         // Record
         foreach ($backup_data->records as $record) {
             try {
                 $new_record = new Record(array("pid" => $record->pid, "fid" => $record->fid, "owner" => $record->owner, "kid" => $record->kid));
                 $new_record->rid = $record->rid;
                 $new_record->created_at = $record->created_at;
                 $new_record->updated_at = $record->updated_at;
                 $new_record->save();
             } catch (QueryException $e) {
                 $this->ajax_error_list->push($e->getMessage());
             }
         }
         // TextField
         foreach ($backup_data->textfields as $textfield) {
             try {
                 $new_textfield = new TextField(array("rid" => $textfield->rid, "flid" => $textfield->flid, "text" => $textfield->text));
                 $new_textfield->id = $textfield->id;
                 $new_textfield->created_at = $textfield->created_at;
                 $new_textfield->updated_at = $textfield->updated_at;
                 $new_textfield->save();
             } catch (QueryException $e) {
                 $this->ajax_error_list->push($e->getMessage());
             }
         }
         // RichTextField
         foreach ($backup_data->richtextfields as $richtextfield) {
             try {
                 $new_richtextfield = new RichTextField(array("rid" => $richtextfield->rid, "flid" => $richtextfield->flid, "rawtext" => $richtextfield->rawtext));
                 $new_richtextfield->id = $richtextfield->id;
                 $new_richtextfield->created_at = $richtextfield->created_at;
                 $new_richtextfield->updated_at = $richtextfield->updated_at;
                 $new_richtextfield->save();
             } catch (QueryException $e) {
                 $this->ajax_error_list->push($e->getMessage());
             }
         }
         // NumberField
         foreach ($backup_data->numberfields as $numberfield) {
             try {
                 $new_numberfield = new NumberField(array("rid" => $numberfield->rid, "flid" => $numberfield->flid, "number" => $numberfield->number));
                 $new_numberfield->id = $numberfield->id;
                 $new_numberfield->created_at = $numberfield->created_at;
                 $new_numberfield->updated_at = $numberfield->updated_at;
                 $new_numberfield->save();
             } catch (QueryException $e) {
                 $this->ajax_error_list->push($e->getMessage());
             }
         }
         // ListField
         foreach ($backup_data->listfields as $listfield) {
             try {
                 $new_listfield = new ListField(array("rid" => $listfield->rid, "flid" => $listfield->flid, "option" => $listfield->option));
                 $new_listfield->id = $listfield->id;
                 $new_listfield->created_at = $listfield->created_at;
                 $new_listfield->updated_at = $listfield->updated_at;
                 $new_listfield->save();
             } catch (QueryException $e) {
                 $this->ajax_error_list->push($e->getMessage());
             }
         }
         // GeneratedListField
         foreach ($backup_data->generatedlistfields as $generatedlistfield) {
             try {
                 $new_generatedlistfield = new GeneratedListField(array("rid" => $generatedlistfield->rid, "flid" => $generatedlistfield->flid, "options" => $generatedlistfield->options));
                 $new_generatedlistfield->id = $generatedlistfield->id;
                 $new_generatedlistfield->created_at = $generatedlistfield->created_at;
                 $new_generatedlistfield->updated_at = $generatedlistfield->updated_at;
                 $new_generatedlistfield->save();
             } catch (QueryException $e) {
                 $this->ajax_error_list->push($e->getMessage());
             }
         }
         // MultiSelectListField
         foreach ($backup_data->multiselectlistfields as $multiselectlistfield) {
             try {
                 $new_multiselectlistfield = new MultiSelectListField(array("rid" => $multiselectlistfield->rid, "flid" => $multiselectlistfield->flid, "options" => $multiselectlistfield->options));
                 $new_multiselectlistfield->id = $multiselectlistfield->id;
                 $new_multiselectlistfield->created_at = $multiselectlistfield->created_at;
                 $new_multiselectlistfield->updated_at = $multiselectlistfield->updated_at;
                 $new_multiselectlistfield->save();
             } catch (QueryException $e) {
                 $this->ajax_error_list->push($e->getMessage());
             }
         }
         // DateField
         foreach ($backup_data->datefields as $datefield) {
             try {
                 $new_datefield = new DateField();
                 $new_datefield->id = $datefield->id;
                 $new_datefield->rid = $datefield->rid;
                 $new_datefield->flid = $datefield->flid;
                 $new_datefield->circa = $datefield->circa;
                 $new_datefield->month = $datefield->month;
                 $new_datefield->day = $datefield->day;
                 $new_datefield->year = $datefield->year;
                 $new_datefield->era = $datefield->era;
                 $new_datefield->created_at = $datefield->created_at;
                 $new_datefield->updated_at = $datefield->updated_at;
                 $new_datefield->save();
             } catch (QueryException $e) {
                 $this->ajax_error_list->push($e->getMessage());
             }
         }
         // ScheduleField
         foreach ($backup_data->schedulefields as $schedulefield) {
             try {
                 $new_schedulefield = new ScheduleField(array("rid" => $schedulefield->rid, "flid" => $schedulefield->flid, "events" => $schedulefield->events));
                 $new_schedulefield->id = $schedulefield->id;
                 $new_schedulefield->created_at = $schedulefield->created_at;
                 $new_schedulefield->updated_at = $schedulefield->updated_at;
                 $new_schedulefield->save();
             } catch (QueryException $e) {
                 $this->ajax_error_list->push($e->getMessage());
             }
         }
         // GeolocatorField
         foreach ($backup_data->geolocatorfields as $geolocatorfield) {
             try {
                 $new_geolocatorfield = new GeolocatorField(array("rid" => $geolocatorfield->rid, "flid" => $geolocatorfield->flid, "locations" => $geolocatorfield->locations));
                 $new_geolocatorfield->id = $geolocatorfield->id;
                 $new_geolocatorfield->created_at = $geolocatorfield->created_at;
                 $new_geolocatorfield->updated_at = $new_geolocatorfield->updated_at;
                 $new_geolocatorfield->save();
             } catch (QueryException $e) {
                 $this->ajax_error_list->push($e->getMessage());
             }
         }
         // Token
         foreach ($backup_data->tokens as $token) {
             try {
                 $new_token = new Token(array('token' => $token->token, 'type' => $token->type));
                 $new_token->id = $token->id;
                 $new_token->created_at = $token->created_at;
                 $new_token->updated_at = $token->updated_at;
                 $new_token->save();
             } catch (QueryException $e) {
                 $this->ajax_error_list->push($e->getMessage());
             }
         }
         // Metadata
         foreach ($backup_data->metadatas as $metadata) {
             try {
                 $new_metadata = new Metadata(array());
                 $new_metadata->flid = $metadata->flid;
                 $new_metadata->pid = $metadata->pid;
                 $new_metadata->fid = $metadata->fid;
                 $new_metadata->name = $metadata->name;
                 $new_metadata->created_at = $metadata->created_at;
                 $new_metadata->updated_at = $metadata->updated_at;
                 $new_metadata->save();
             } catch (QueryException $e) {
                 $this->ajax_error_list->push($e->getMessage());
             }
         }
         // Revision
         foreach ($backup_data->revisions as $revision) {
             try {
                 $new_revision = new Revision(array('id' => $revision->id, 'fid' => $revision->fid, 'rid' => $revision->rid, 'userId' => $revision->userId, 'type' => $revision->type, 'data' => $revision->data, 'oldData' => $revision->oldData, 'rollback' => $revision->rollback));
                 $new_revision->created_at = $revision->created_at;
                 $new_revision->updated_at = $revision->updated_at;
                 $new_revision->save();
             } catch (QueryException $e) {
                 $this->ajax_error_list->push($e->getMessage());
             }
         }
     } catch (\Exception $e) {
         $this->ajax_error_list->push($e->getMessage());
         $this->ajaxResponse(false, "An unknown error prevented the restore from completing.\n                You can try restoring from a different backup file or restore point.\n                Users will stay locked out until you run a successful restore or manually unlock them above.\n                For this error, it's not recommended that you unlock users unless you have resolved the problem");
     }
     if (count($this->ajax_error_list) != 0) {
         $this->ajaxResponse(false, "Not all of your data was restored, check the errors below for details.\n            The errors are in order that they occurred, if you can resolve the first error, it will often correct\n            one or more of the errors below it.\n            Users will stay locked out until you run a successful restore or manually unlock them above.");
     } else {
         $this->unlockUsers();
         $this->ajaxResponse(true, "The restore completed successfully.");
     }
 }
 public function run()
 {
     Model::unguard();
     DB::statement('SET FOREIGN_KEY_CHECKS=0;');
     DB::table('form_categories')->truncate();
     DB::table('form_groups')->truncate();
     DB::table('forms')->truncate();
     DB::table('single_selects')->truncate();
     DB::table('form_single_selects')->truncate();
     DB::table('multi_selects')->truncate();
     DB::table('form_multi_selects')->truncate();
     DB::table('form_formulas')->truncate();
     DB::table('form_conditions')->truncate();
     DB::table('audit_template_forms')->truncate();
     DB::table('audit_template_groups')->truncate();
     DB::table('audit_template_categories')->truncate();
     // \DB::beginTransaction();
     // try {
     $folderpath = 'database/seeds/seed_files';
     $folders = File::directories($folderpath);
     $latest = '11232015';
     foreach ($folders as $value) {
         $_dir = explode("/", $value);
         $cnt = count($_dir);
         $name = $_dir[$cnt - 1];
         $latest_date = DateTime::createFromFormat('mdY', $latest);
         $now = DateTime::createFromFormat('mdY', $name);
         if ($now > $latest_date) {
             $latest = $name;
         }
     }
     // $this->filename = $folderpath.$latest.'/mtprimarysales.csv';
     $files = File::allFiles($folderpath . "/" . $latest . "/templates");
     foreach ($files as $file) {
         echo (string) $file, "\n";
         $reader = ReaderFactory::create(Type::XLSX);
         // for XLSX files
         $reader->open($file);
         //   // Accessing the sheet name when reading
         foreach ($reader->getSheetIterator() as $sheet) {
             if ($sheet->getName() == 'Sheet1') {
                 $cnt = 0;
                 foreach ($sheet->getRowIterator() as $row) {
                     if ($cnt > 0) {
                         if ($row[1] != '') {
                             $start_date = $row[4];
                             $end_date = $row[5];
                             $template = AuditTemplate::firstOrCreate(['template' => $row[1]]);
                             $template->start_date = $start_date;
                             $template->end_date = $end_date;
                             $template->update();
                             $category = FormCategory::firstOrCreate(['category' => $row[3]]);
                             // dd($category);
                             $group = FormGroup::firstOrCreate(['group_desc' => $row[6]]);
                             $type = $row[11];
                             if (strtoupper($type) == 'DOUBLE') {
                                 $form_type = FormType::where('form_type', "NUMERIC")->first();
                             } else {
                                 $form_type = FormType::where('form_type', strtoupper($type))->first();
                             }
                             $image = "";
                             if (!empty($row[15])) {
                                 $image = $row[15];
                             }
                             if ($form_type->id == 11) {
                                 $index1 = array();
                                 $index2 = array();
                                 preg_match_all('/{(.*?)}/', $row[12], $matches);
                                 foreach ($matches[1] as $key => $a) {
                                     $data = DB::table('temp_forms')->where('code', $a)->first();
                                     if (!empty($data)) {
                                         $other_form = FormRepository::insertForm($template, $a, $data->type, $data->required, $data->prompt, $data->choices, $data->expected_answer, $image, null, null, null);
                                         $index1[$a] = $other_form->id;
                                         $index2[$a] = $other_form->prompt . '_' . $other_form->id;
                                     } else {
                                         $other_form = DB::table('forms')->where('code', $a)->first();
                                         // echo $a;
                                         if (empty($other_form)) {
                                             // dd($a);
                                         }
                                         // $other_form = FormRepository::insertForm($template,$a,$data->form_type_id,$data->required,$data->prompt,null,$data->expected_answer,null,$image);
                                         $index1[$a] = '!' . $other_form->id;
                                         $index2[$a] = $other_form->prompt . '_' . $other_form->id;
                                     }
                                 }
                                 $formula1 = $row[12];
                                 $formula2 = $row[12];
                                 foreach ($matches[1] as $key => $a) {
                                     $formula1 = str_replace('{' . $a . '}', $index1[$a], $formula1);
                                     $formula2 = str_replace('{' . $a . '}', ' :' . $index2[$a] . ': ', $formula2);
                                 }
                                 $form = FormRepository::insertForm($template, $row[7], $row[11], $row[10], $row[9], $formula1, null, $image, $formula2, null, null);
                             } elseif ($form_type->id == 12) {
                                 $options = explode("~", $row[12]);
                                 preg_match_all('/(.*?){(.*?)}/', $row[12], $matches);
                                 $data_con = array();
                                 $options = explode("~", $row[12]);
                                 foreach ($options as $option) {
                                     $with_value = preg_match('/{(.*?)}/', $option, $match);
                                     $x1 = array();
                                     $x2 = array();
                                     $_opt1 = "";
                                     $_opt2 = "";
                                     if ($with_value) {
                                         $codes = explode('^', $match[1]);
                                         if (count($codes) > 0) {
                                             foreach ($codes as $code) {
                                                 if ($code != '') {
                                                     $other_data = DB::table('temp_forms')->where('code', $code)->first();
                                                     if (empty($other_data)) {
                                                         $other_data = DB::table('forms')->where('code', $code)->first();
                                                     }
                                                     $other_form = FormRepository::insertForm($template, $code, $other_data->type, $other_data->required, $other_data->prompt, $other_data->choices, $other_data->expected_answer, null, null, null, null);
                                                     $x1[] = $other_form->id;
                                                     $x2[] = $other_form->prompt . '_' . $other_form->id;
                                                 }
                                             }
                                         }
                                         if (count($x1) > 0) {
                                             $_opt1 = implode("^", $x1);
                                         }
                                         if (count($x2) > 0) {
                                             $_opt2 = implode("^", $x2);
                                         }
                                     }
                                     $data_con[] = ['option' => strtoupper(strtok($option, '{')), 'condition' => $_opt1, 'condition_desc' => $_opt2];
                                 }
                                 // dd($data_con);
                                 $form = FormRepository::insertForm($template, $row[7], $row[11], $row[10], $row[9], $row[12], $row[14], $image, array(), $data_con, $row[16]);
                             } else {
                                 $form = FormRepository::insertForm($template, $row[7], $row[11], $row[10], $row[9], $row[12], $row[14], $image, null, null, $row[16]);
                             }
                             $cat_order = 1;
                             $a_cat_id = 0;
                             $clast_cnt = AuditTemplateCategory::getLastOrder($template->id);
                             if (empty($clast_cnt)) {
                                 $a_cat = AuditTemplateCategory::create(['category_order' => $cat_order, 'audit_template_id' => $template->id, 'category_id' => $category->id]);
                                 $a_cat_id = $a_cat->id;
                             } else {
                                 $cat = AuditTemplateCategory::categoryExist($template->id, $category->id);
                                 if (empty($cat)) {
                                     $cat_order = $clast_cnt->category_order + 1;
                                     $a_cat = AuditTemplateCategory::create(['category_order' => $cat_order, 'audit_template_id' => $template->id, 'category_id' => $category->id]);
                                     $a_cat_id = $a_cat->id;
                                 } else {
                                     $a_cat_id = $cat->id;
                                 }
                             }
                             $grp_order = 1;
                             $a_grp_id = 0;
                             $glast_cnt = AuditTemplateGroup::getLastOrder($a_cat_id);
                             if (empty($glast_cnt)) {
                                 $a_grp = AuditTemplateGroup::create(['group_order' => $grp_order, 'audit_template_category_id' => $a_cat_id, 'form_group_id' => $group->id]);
                                 $a_grp_id = $a_grp->id;
                             } else {
                                 $grp = AuditTemplateGroup::categoryExist($a_cat_id, $group->id);
                                 if (empty($grp)) {
                                     $grp_order = $glast_cnt->group_order + 1;
                                     $a_grp = AuditTemplateGroup::create(['group_order' => $grp_order, 'audit_template_category_id' => $a_cat_id, 'form_group_id' => $group->id]);
                                     $a_grp_id = $a_grp->id;
                                 } else {
                                     $a_grp_id = $grp->id;
                                 }
                             }
                             $order = 1;
                             $a_frm_id = 0;
                             $last_cnt = AuditTemplateForm::getLastOrder($a_grp_id);
                             if (!empty($last_cnt)) {
                                 $order = $last_cnt->order + 1;
                             }
                             AuditTemplateForm::create(array('audit_template_group_id' => $a_grp_id, 'order' => $order, 'audit_template_id' => $template->id, 'form_id' => $form->id));
                         }
                     }
                     $cnt++;
                 }
             }
             // }elseif($sheet->getName() == 'Others') {
             // 	// $cnt = 0;
             // 	// foreach ($sheet->getRowIterator() as $row) {
             // 	// 	if($cnt > 0){
             // 	// 		if(!is_null($row[2])){
             // 	// 			$prompt = addslashes($row[1]);
             // 	// 			DB::statement('INSERT INTO temp_forms (code, prompt, required, type, choices) VALUES ("'.$row[0].'","'.$prompt.'","'.$row[2].'","'.$row[3].'","'.$row[4].'");');
             // 	// 		}
             // 	// 	}
             // 	// 	$cnt++;
             // 	// }
             // }else{
             // }
         }
         $reader->close();
     }
     $users = User::all();
     foreach ($users as $user) {
         $mapping = UserMapping::where('user_name', $user->name)->where('start_date', $start_date)->where('end_date', $end_date)->first();
         if (!empty($mapping)) {
             $mapping->mapped_stores = $user->stores->count();
             $mapping->update();
         } else {
             UserMapping::create(['user_name' => $user->name, 'start_date' => $start_date, 'end_date' => $end_date, 'mapped_stores' => $user->stores->count()]);
         }
     }
     DB::statement('SET FOREIGN_KEY_CHECKS=1;');
     Model::reguard();
 }
 public function index(Request $request)
 {
     $user = $request->id;
     $type = $request->type;
     $user = User::find($user);
     $storelist = $user->stores()->orderBy('store')->get();
     $result = array();
     foreach ($storelist as $store) {
         $result[] = $store->audit_template_id;
     }
     $list = array_unique($result);
     // get store list
     if ($type == "stores") {
         $writer = WriterFactory::create(Type::CSV);
         $writer->openToBrowser('stores.txt');
         $writer->addRow(['id', 'store', 'grade_matrix_id', 'audit_template_id', 'template', 'start_date', 'end_date', 'store_code']);
         foreach ($storelist as $store) {
             $store_ids[] = $store->id;
             $data[0] = $store->id;
             $data[1] = $store->store;
             $data[2] = $store->gradematrix->passing;
             $data[3] = $store->audit_template_id;
             $data[4] = $store->audittemplate->template;
             $data[5] = 0;
             $data[6] = 0;
             $data[7] = 0;
             $data[8] = 0;
             $data[9] = $store->audittemplate->start_date;
             $data[10] = $store->audittemplate->end_date;
             $data[11] = $store->store_code;
             $data[12] = $store->account->account;
             $data[13] = $store->customer->customer_code;
             $data[14] = $store->customer->customer;
             $data[15] = $store->region->region_code;
             $data[16] = $store->region->region;
             $data[17] = $store->distributor->distributor_code;
             $data[18] = $store->distributor->distributor;
             $data[19] = $store->audittemplate->template_code;
             $writer->addRow($data);
         }
         $writer->close();
     }
     // get template categories
     if ($type == "temp_categories") {
         $categories = AuditTemplateCategory::select('audit_template_categories.id', 'audit_template_categories.audit_template_id', 'audit_template_categories.category_id', 'form_categories.category', 'audit_template_categories.category_order', 'form_categories.perfect_store')->join('form_categories', 'form_categories.id', '=', 'audit_template_categories.category_id')->whereIn('audit_template_id', $list)->orderBy('audit_template_id')->orderBy('category_order')->get();
         $writer = WriterFactory::create(Type::CSV);
         $writer->openToBrowser('temp_category.txt');
         $writer->addRow(['id', 'audit_template_id', 'category_id', 'category', 'category_order', 'perfect_store']);
         foreach ($categories as $category) {
             $data[0] = $category->id;
             $data[1] = $category->audit_template_id;
             $data[2] = $category->category_order;
             $data[3] = $category->category_id;
             $data[4] = $category->category;
             $data[5] = $category->perfect_store;
             $writer->addRow($data);
         }
         $writer->close();
     }
     // get template groups
     if ($type == "temp_groups") {
         $c_list = array();
         $categories = AuditTemplateCategory::select('audit_template_categories.id', 'audit_template_categories.audit_template_id', 'audit_template_categories.category_id', 'form_categories.category', 'audit_template_categories.category_order')->join('form_categories', 'form_categories.id', '=', 'audit_template_categories.category_id')->whereIn('audit_template_id', $list)->orderBy('audit_template_id')->orderBy('category_order')->get();
         foreach ($categories as $category) {
             $c_list[] = $category->id;
         }
         $groups = AuditTemplateGroup::select('audit_template_groups.id', 'audit_template_groups.form_group_id', 'form_groups.group_desc', 'audit_template_categories.audit_template_id', 'audit_template_groups.group_order', 'audit_template_groups.audit_template_category_id', 'form_groups.perfect_store')->join('audit_template_categories', 'audit_template_categories.id', '=', 'audit_template_groups.audit_template_category_id')->join('form_groups', 'form_groups.id', '=', 'audit_template_groups.form_group_id')->whereIn('audit_template_category_id', $c_list)->orderBy('audit_template_id')->orderBy('audit_template_category_id')->orderBy('group_order')->get();
         $writer = WriterFactory::create(Type::CSV);
         $writer->openToBrowser('temp_group.txt');
         $writer->addRow(['id', 'audit_template_id', 'audit_template_category_id', 'group_order', 'form_group_id', 'group_desc', 'perfect_store']);
         foreach ($groups as $group) {
             $data[0] = $group->id;
             $data[1] = $group->audit_template_id;
             $data[2] = $group->audit_template_category_id;
             $data[3] = $group->group_order;
             $data[4] = $group->form_group_id;
             $data[5] = $group->group_desc;
             $data[6] = $group->perfect_store;
             $writer->addRow($data);
         }
         $writer->close();
     }
     // get template questions
     if ($type == "temp_questions") {
         // dd($list);
         $forms = AuditTemplateForm::select('audit_template_forms.id', 'audit_template_forms.order', 'audit_template_forms.audit_template_group_id', 'audit_template_forms.audit_template_id', 'audit_template_forms.form_id', 'forms.form_type_id', 'forms.prompt', 'forms.required', 'forms.expected_answer', 'forms.exempt', 'forms.image', 'forms.default_answer')->join('audit_template_groups', 'audit_template_groups.id', '=', 'audit_template_forms.audit_template_group_id')->join('audit_template_categories', 'audit_template_categories.id', '=', 'audit_template_groups.audit_template_category_id')->join('forms', 'forms.id', '=', 'audit_template_forms.form_id')->join('form_categories', 'form_categories.id', '=', 'audit_template_categories.category_id')->join('form_groups', 'form_groups.id', '=', 'audit_template_groups.form_group_id')->whereIn('audit_template_forms.audit_template_id', $list)->get();
         // dd($forms);
         $writer = WriterFactory::create(Type::CSV);
         $writer->openToBrowser('questions.txt');
         $writer->addRow(['id', 'order', 'audit_template_group_id', 'audit_template_id', 'form_id', 'form_type_id', 'prompt', 'required', 'expected_answer', 'exempt', 'image', 'default_answer']);
         foreach ($forms as $form) {
             $data[0] = $form->id;
             $data[1] = $form->order;
             $data[2] = $form->audit_template_group_id;
             $data[3] = $form->audit_template_id;
             $data[4] = $form->form_id;
             $data[5] = $form->form_type_id;
             $prompt = "null";
             if (!empty($form->prompt)) {
                 $prompt = preg_replace("/[\\n\\r]+/", " ", $form->prompt);
             }
             $data[6] = $prompt;
             $data[7] = $form->required;
             $data[8] = $form->expected_answer;
             $data[9] = $form->exempt;
             $data[10] = $form->form->image;
             $data[11] = $form->default_answer;
             // var_dump($data);
             $writer->addRow($data);
         }
         $writer->close();
     }
     // get template forms
     if ($type == "temp_forms") {
         $forms = Form::whereIn('forms.audit_template_id', $list)->get();
         $writer = WriterFactory::create(Type::CSV);
         $writer->openToBrowser('forms.txt');
         $writer->addRow(['id', 'audit_template_id', 'form_type_id', 'prompt', 'required', 'expected_answer', 'exempt', 'image', 'default_answer']);
         foreach ($forms as $form) {
             $data[0] = $form->id;
             $data[1] = $form->audit_template_id;
             $data[2] = $form->form_type_id;
             $data[3] = preg_replace("/[\\n\\r]+/", " ", $form->prompt);
             $data[4] = $form->required;
             $data[5] = $form->expected_answer;
             $data[6] = $form->exempt;
             $data[7] = $form->image;
             $data[8] = $form->default_answer;
             $writer->addRow($data);
         }
         $writer->close();
     }
     // get single selects
     if ($type == "single_selects") {
         $forms = Form::whereIn('forms.audit_template_id', $list)->where('form_type_id', 10)->get();
         $form_ids = array();
         foreach ($forms as $form) {
             $form_ids[] = $form->id;
         }
         $selections = FormSingleSelect::select('form_single_selects.form_id', 'single_selects.id', 'single_selects.option')->join('single_selects', 'single_selects.id', '=', 'form_single_selects.single_select_id')->whereIn('form_single_selects.form_id', $form_ids)->orderBy('form_single_selects.form_id')->get();
         // dd($selections);
         $writer = WriterFactory::create(Type::CSV);
         $writer->openToBrowser('single_selects.txt');
         $writer->addRow(['form_id', 'id', 'option']);
         foreach ($selections as $selection) {
             $data[0] = $selection->form_id;
             $data[1] = $selection->id;
             $data[2] = $selection->option;
             $writer->addRow($data);
         }
         $writer->close();
     }
     // get multiple selects
     if ($type == "multi_selects") {
         $forms = Form::whereIn('forms.audit_template_id', $list)->where('form_type_id', 9)->get();
         $form_ids = array();
         foreach ($forms as $form) {
             $form_ids[] = $form->id;
         }
         $selections = FormMultiSelect::select('form_multi_selects.form_id', 'multi_selects.id', 'multi_selects.option')->join('multi_selects', 'multi_selects.id', '=', 'form_multi_selects.multi_select_id')->whereIn('form_multi_selects.form_id', $form_ids)->orderBy('form_multi_selects.form_id')->get();
         $writer = WriterFactory::create(Type::CSV);
         $writer->openToBrowser('multi_selects.txt');
         $writer->addRow(['form_id', 'id', 'option']);
         foreach ($selections as $selection) {
             $data[0] = $selection->form_id;
             $data[1] = $selection->id;
             $data[2] = $selection->option;
             $writer->addRow($data);
         }
         $writer->close();
     }
     // get formulas
     if ($type == "formulas") {
         $forms = Form::whereIn('forms.audit_template_id', $list)->where('form_type_id', 11)->get();
         $form_ids = array();
         foreach ($forms as $form) {
             $form_ids[] = $form->id;
         }
         $formulas = FormFormula::select('form_formulas.form_id', 'formula')->get();
         $writer = WriterFactory::create(Type::CSV);
         $writer->openToBrowser('formula.txt');
         $writer->addRow(['form_id', 'formula']);
         foreach ($formulas as $formula) {
             $data[0] = $formula->form_id;
             $data[1] = $formula->formula;
             $writer->addRow($data);
         }
         $writer->close();
     }
     // get conditions
     if ($type == "conditions") {
         $forms = Form::whereIn('forms.audit_template_id', $list)->where('form_type_id', 12)->get();
         $form_ids = array();
         foreach ($forms as $form) {
             $form_ids[] = $form->id;
         }
         $conditions = FormCondition::select('form_conditions.form_id', 'option', 'condition', 'id')->get();
         $writer = WriterFactory::create(Type::CSV);
         $writer->openToBrowser('conditions.txt');
         $writer->addRow(['form_id', 'option', 'condition']);
         foreach ($conditions as $condition) {
             $data[0] = $condition->form_id;
             $data[1] = $condition->option;
             $data[2] = $condition->condition;
             $data[3] = $condition->id;
             $writer->addRow($data);
         }
         $writer->close();
     }
     // get secondary display lookup
     if ($type == "secondary_lookups") {
         $store_ids = array();
         foreach ($storelist as $store) {
             $store_ids[] = $store->id;
         }
         $secondarydisplay = SecondaryDisplayLookup::select('store_id', 'category_id', 'brand')->whereIn('store_id', $store_ids)->join('secondary_displays', 'secondary_displays.id', '=', 'secondary_display_lookups.secondary_display_id')->orderBy('store_id')->orderBy('category_id')->get();
         $writer = WriterFactory::create(Type::CSV);
         $writer->openToBrowser('secondarydisplay.txt');
         $writer->addRow(['store_id', 'category_id', 'brand']);
         foreach ($secondarydisplay as $category) {
             $data[0] = $category->store_id;
             $data[1] = $category->category_id;
             $data[2] = strtoupper($category->brand);
             $writer->addRow($data);
         }
         $writer->close();
     }
     // get secondary key list
     if ($type == "secondary_lists") {
         $keylist = FormGroup::where('secondary_display', 1)->get();
         $writer = WriterFactory::create(Type::CSV);
         $writer->openToBrowser('secondary_keylist.txt');
         $writer->addRow(['id']);
         foreach ($keylist as $list) {
             $data[0] = $list->id;
             $writer->addRow($data);
         }
         $writer->close();
     }
     // get osa key list
     if ($type == "osa_lists") {
         $keylist = FormGroup::where('osa', 1)->get();
         $writer = WriterFactory::create(Type::CSV);
         $writer->openToBrowser('osa_keylist.txt');
         $writer->addRow(['id']);
         foreach ($keylist as $list) {
             $data[0] = $list->id;
             $writer->addRow($data);
         }
         $writer->close();
     }
     if ($type == "osa_lookups") {
         $writer = WriterFactory::create(Type::CSV);
         $writer->openToBrowser('osa_lookups.txt');
         $writer->addRow(['id', 'category_id', 'target', 'total', 'lookup_id']);
         foreach ($storelist as $store) {
             $lookup = OsaLookup::getOsaCategory($store->id);
             foreach ($lookup->categories as $category) {
                 $data[0] = $store->id;
                 $data[1] = $category->category_id;
                 $data[2] = $category->target;
                 $data[3] = $category->total;
                 $data[4] = $lookup->id;
                 $writer->addRow($data);
             }
         }
         $writer->close();
     }
     // sos lookup
     if ($type == "sos_lists") {
         $keylist = FormGroup::where('sos', 1)->get();
         $writer = WriterFactory::create(Type::CSV);
         $writer->openToBrowser('sos_keylist.txt');
         $writer->addRow(['id']);
         foreach ($keylist as $list) {
             $data[0] = $list->id;
             $writer->addRow($data);
         }
         $writer->close();
     }
     if ($type == "sos_lookups") {
         $writer = WriterFactory::create(Type::CSV);
         $writer->openToBrowser('sos_lookups.txt');
         $writer->addRow(['store_id', 'category_id', 'sos_id', 'less', 'value', 'sos_lookup_id']);
         foreach ($storelist as $store) {
             $lookup = SosLookup::getSosCategory($store->id);
             $results = DB::select(DB::raw("select store_id, category_id, sos_id,less,  value,sos_lookup_id from store_sos_tags\n                    join sos_lookup_percentages on sos_lookup_percentages.category_id = store_sos_tags.`form_category_id`\n                    where store_id = :store_id\n                    and sos_lookup_id = :lookup_id\n                    and store_sos_tags.`sos_tag_id` = sos_lookup_percentages.sos_id"), array('store_id' => $store->id, 'lookup_id' => $lookup->id));
             // dd($results);
             foreach ($results as $result) {
                 $data[0] = $result->store_id;
                 $data[1] = $result->category_id;
                 $data[2] = $result->sos_id;
                 $data[3] = $result->less;
                 $data[4] = $result->value;
                 $data[5] = $result->sos_lookup_id;
                 $writer->addRow($data);
             }
         }
         $writer->close();
     }
     if ($type == "form_types") {
         $form_types = FormType::all();
         $writer = WriterFactory::create(Type::CSV);
         $writer->openToBrowser('form_types.txt');
         $writer->addRow(['id', 'form_type']);
         foreach ($form_types as $type) {
             $data[0] = $type->id;
             $data[1] = $type->form_type;
             $writer->addRow($data);
         }
         $writer->close();
     }
     if ($type == "image_lists") {
         $writer = WriterFactory::create(Type::CSV);
         $writer->openToBrowser('image_lists.txt');
         $writer->addRow(['image_name']);
         $results = SurveyImage::all();
         // dd($results);
         foreach ($results as $result) {
             $data[0] = $result->images;
             $writer->addRow($data);
         }
         $writer->close();
     }
 }