Inheritance: extends Illuminate\Database\Eloquent\Model
コード例 #1
1
 /**
  * Execute the command.
  *
  * @return void
  */
 public function handle()
 {
     $documents = Config::get('documents');
     $whereAreClientDocuments = $documents['documents_folder'];
     //client_{id}
     if (!Storage::disk('local')->exists($whereAreClientDocuments . '/client_' . $this->firm->user->id)) {
         Storage::makeDirectory($whereAreClientDocuments . '/client_' . $this->firm->user->id);
     }
     //agreement
     if (!Storage::disk('local')->exists($whereAreClientDocuments . '/client_' . $this->firm->user->id . '/service_agreement')) {
         Storage::makeDirectory($whereAreClientDocuments . '/client_' . $this->firm->user->id . '/service_agreement');
     }
     //очищаем папку от всех файлов
     $files = Storage::files($whereAreClientDocuments . '/client_' . $this->firm->user->id . '/service_agreement');
     if (!empty($files)) {
         $agreementDocIds = Document::select('id')->where('type', Order::CONTRACT_TYPE)->where('user_id', $this->firm->user->id)->get();
         $agreementDocIdsArr = [];
         foreach ($agreementDocIds as $agreementDocId) {
             $agreementDocIdsArr[] = $agreementDocId->id;
         }
         Document::destroy($agreementDocIdsArr);
     }
     Storage::delete($files);
     //создаем новый файл
     $clientFolder = storage_path() . '/app' . $whereAreClientDocuments . '/client_' . $this->firm->user->id . '/service_agreement';
     //{docType}_contragent_{clientId}_date_{currentDate}.pdf
     $fileNameTemplate = $documents['client_service_agreement_template'];
     $fileNameTemplate = Utils::mb_str_replace('{docType}', Order::getDocTypeName(Order::CONTRACT_TYPE), $fileNameTemplate);
     $fileNameTemplate = Utils::mb_str_replace('{clientId}', $this->firm->user->id, $fileNameTemplate);
     $fileNameTemplate = Utils::mb_str_replace('{currentDate}', time(), $fileNameTemplate);
     //		$pdf->save($clientFolder.'/'.$fileNameTemplate);
     //********************************************************
     /*
     * Номер текущей страницы
     * если требуется сгенерировать несколько документов
     */
     //  $current_page = 1;
     //****************************************************
     //+++++++++++++++++++++++++++++++++++++++++++++++++++++
     $pdf = App::make('dompdf.wrapper');
     $pdf->loadView('documents.serviceAgreementTemplate', ['fullFirmName' => $this->firm->full_organisation_name, 'shortFirmName' => $this->firm->organisation_name, 'position' => $this->firm->rp_face_position, 'fio' => $this->firm->rp_face_fio, 'baseDocument' => $this->firm->rp_base_document, 'inn' => $this->firm->inn, 'kpp' => $this->firm->kpp, 'address' => $this->firm->place_address, 'rs' => $this->firm->rs, 'bank' => $this->firm->bank, 'ks' => $this->firm->ks, 'bik' => $this->firm->bik, 'phone' => $this->firm->phone, 'email' => $this->firm->user->email]);
     //+++++++++++++++++++++++++++++++++++++++++++++++
     //        $dom_pdf = $pdf->getDomPDF();
     //        $canvas = $dom_pdf->get_canvas();
     //        dd($canvas);
     //        $canvas->page_text(0, 0, "Page {PAGE_NUM} of {PAGE_COUNT}", null, 10, array(0, 0, 0));
     //--------------------------------------------
     $m = new Merger();
     $m->addRaw($pdf->output());
     //****************************************************
     //        $signs = array (
     //            'start-page' => $current_page);
     //
     //        // Замена меток в шаблоне их значениями
     //        foreach ($signs as $key => $value) {
     //            $template = str_replace('{' . $key . '}', $value, $template);
     //        }
     /*
      * Увеличили счетчик числа сгенерированных страниц
      * на число страниц текущего документа
      */
     //        $current_page = $current_page + $dom_pdf->get_canvas()->get_page_count();
     //********************************************************
     unset($pdf);
     $pdf = App::make('dompdf.wrapper');
     $pdf->setPaper('a4', 'landscape')->loadView('documents.serviceAgreementTemplate2');
     $m->addRaw($pdf->output());
     file_put_contents($clientFolder . '/' . $fileNameTemplate, $m->merge());
     $docs = new Document();
     $docs->type = Order::CONTRACT_TYPE;
     $docs->user_id = $this->firm->user->id;
     $docs->file_name = $clientFolder . '/' . $fileNameTemplate;
     $docs->sended = 1;
     $docs->save();
     $user = User::find($this->firm->user->id);
     $emailContent['userName'] = $user->name;
     $emailContent['email'] = $user->email;
     Bus::dispatch(new SendEmailWithServiceAgreement($emailContent, $clientFolder . '/' . $fileNameTemplate));
 }
コード例 #2
0
ファイル: Document.php プロジェクト: khakanali/OpenMAll
 public function store(Request $request, $user_as_merchant_model)
 {
     $merchant_id = $user_as_merchant_model['id'];
     /*
      * Get product last id from document table
      */
     $Document_id = Document::orderBy('id', 'desc')->take(1)->get();
     foreach ($Document_id as $DI) {
         $Did = $DI->id;
     }
     if (!isset($Did)) {
         $Did = 0;
     }
     $Did = $Did + 1;
     $documents = $request;
     // every key has an arr except merchant_id
     $files = $request->file('upload_attachment');
     for ($i = 0; $i < count($files); $i++) {
         $files_name = $files[$i]->getClientOriginalName();
         $destination = 'public/images/document/' . $Did . '/';
         if ($files[$i]->move($destination, $files_name)) {
             $doc = new Document();
             $doc->path = $destination . $files_name;
             $doc->save();
             $Merdoc = new merchantdocument();
             $Merdoc->merchant_id = $merchant_id;
             $Merdoc->document_id = $Did;
             $Merdoc->save();
             $Did = $Did + 1;
         }
     }
 }
コード例 #3
0
ファイル: Document.php プロジェクト: playatech/weightlifter
 public static function createDocument($application, $upload, $answer = null)
 {
     $document = new Document();
     $document->name = $upload['name'];
     $document->file = $upload['file'];
     $document->application_id = $application->id;
     $document->user_id = Auth::user()->id;
     if ($answer) {
         $document->answer_id = $answer->id;
     }
     $document->save();
     return $document;
 }
コード例 #4
0
 /**
  * Execute the command.
  *
  * @return void
  */
 public function handle()
 {
     $selfFirmUser = User::with('firm')->where('role_id', User::ADMIN)->first();
     $clientCompany = User::with('firm')->where('id', $this->order->user_id)->first();
     $products = $this->order->products_in_order;
     $firm = $clientCompany->firm;
     $productsArr = [];
     foreach ($products as $product) {
         $productsArr[] = ['product_name' => $product->product_name, 'product_amount' => $product->product_amount, 'product_price' => $product->product_price];
     }
     $date = DateTime::createFromFormat('Y-m-d H:i:s', $this->order->created_at);
     $date = strtotime($date->format('d F Y'));
     $pdf = App::make('dompdf.wrapper');
     $viewType = null;
     if ($this->isTorg) {
         $viewType = 'documents.torg_12';
     } else {
         $viewType = 'documents.schet_factura';
     }
     $pdf->loadView($viewType, ['orderNumber' => $this->order->id, 'orderDate' => date('d.m.Y', $date), 'firm' => $firm, 'selfFirm' => $selfFirmUser->firm, 'products' => $productsArr]);
     //$pdf->setOrientation('landscape');
     $pdf->setPaper('A4', 'landscape');
     $documents = Config::get('documents');
     $whereAreClientDocuments = $documents['documents_folder'];
     //client_{id}
     if (!Storage::disk('local')->exists($whereAreClientDocuments . DIRECTORY_SEPARATOR . 'client_' . $this->order->user_id)) {
         Storage::makeDirectory($whereAreClientDocuments . DIRECTORY_SEPARATOR . 'client_' . $this->order->user_id);
     }
     //paymentDocs
     if (!Storage::disk('local')->exists($whereAreClientDocuments . DIRECTORY_SEPARATOR . 'client_' . $this->order->user_id . DIRECTORY_SEPARATOR . 'paymentDocs')) {
         Storage::makeDirectory($whereAreClientDocuments . DIRECTORY_SEPARATOR . 'client_' . $this->order->user_id . DIRECTORY_SEPARATOR . 'paymentDocs');
     }
     $clientFolder = storage_path() . DIRECTORY_SEPARATOR . 'app' . $whereAreClientDocuments . DIRECTORY_SEPARATOR . 'client_' . $this->order->user_id . DIRECTORY_SEPARATOR . 'paymentDocs';
     //(torg12/schetfactura)_{orderID}_{depoName}_date_{currentDate}
     $fileNameTemplate = $documents['client_invoice_template'];
     $fileNameTemplate = Utils::mb_str_replace('{docType}', Order::getDocTypeName($this->isTorg ? Order::AUCTION_12_TYPE : Order::INVOICE_ACCT_TYPE), $fileNameTemplate);
     $fileNameTemplate = Utils::mb_str_replace('{orderID}', $this->order->id, $fileNameTemplate);
     $depo = Stantion::find($this->order->products_in_order[0]->stantion_id);
     $depoName = Utils::mb_str_replace(' ', '', $depo->stantion_name);
     $depoName = Utils::translit($depoName);
     $fileNameTemplate = Utils::mb_str_replace('{depoName}', $depoName, $fileNameTemplate);
     $fileNameTemplate = Utils::mb_str_replace('{currentDate}', time(), $fileNameTemplate);
     $pdf->save($clientFolder . DIRECTORY_SEPARATOR . $fileNameTemplate);
     $docs = new Document();
     $docs->type = $this->isTorg ? Order::AUCTION_12_TYPE : Order::INVOICE_ACCT_TYPE;
     $docs->user_id = $this->order->user_id;
     $docs->order_id = $this->order->id;
     $docs->file_name = $clientFolder . DIRECTORY_SEPARATOR . $fileNameTemplate;
     $docs->save();
     Bus::dispatch(new SendEmailWithPaymentDocs($docs->file_name, $this->isTorg, $this->order));
 }
コード例 #5
0
 /**
 * Execute the command.
 *
 	//	 * @return void
 */
 public function handle()
 {
     $documents = Config::get('documents');
     $whereAreClientDocuments = $documents['documents_folder'];
     //client_{id}
     if (!Storage::disk('local')->exists($whereAreClientDocuments . '/client_' . $this->firm->user->id)) {
         Storage::makeDirectory($whereAreClientDocuments . '/client_' . $this->firm->user->id);
     }
     //agreement
     if (!Storage::disk('local')->exists($whereAreClientDocuments . '/client_' . $this->firm->user->id . '/service_agreement')) {
         Storage::makeDirectory($whereAreClientDocuments . '/client_' . $this->firm->user->id . '/service_agreement');
     }
     $clientFilePath = $whereAreClientDocuments . '/client_' . $this->firm->user->id . '/service_agreement';
     $extension = $this->file->getClientOriginalExtension();
     //get all files from folder end delete them
     $files = Storage::files($clientFilePath);
     if (!empty($files)) {
         $agreementDocIds = Document::select('id')->where('type', Order::CONTRACT_TYPE)->where('user_id', $this->firm->user->id)->get();
         $agreementDocIdsArr = [];
         foreach ($agreementDocIds as $agreementDocId) {
             $agreementDocIdsArr[] = $agreementDocId->id;
         }
         Document::destroy($agreementDocIdsArr);
     }
     Storage::delete($files);
     $file = array_shift($files);
     $filePathBySlash = explode(DIRECTORY_SEPARATOR, $file);
     $fileName = end($filePathBySlash);
     $fileNameBy_ = explode('_', $fileName);
     $fileDateWithExtension = time() . '.' . $extension;
     array_pop($fileNameBy_);
     $fileNameBy_[] = $fileDateWithExtension;
     $fileName = implode('_', $fileNameBy_);
     array_pop($filePathBySlash);
     $filePathBySlash[] = $fileName;
     $file = implode(DIRECTORY_SEPARATOR, $filePathBySlash);
     try {
         Storage::disk('local')->put($file, File::get($this->file));
     } catch (Exception $e) {
         Log::error('Ошибка загрузки файла с договором оферты' . ' message - ' . $e->getMessage());
         return false;
     }
     $docs = new Document();
     $docs->type = Order::CONTRACT_TYPE;
     $docs->user_id = $this->firm->user->id;
     $docs->file_name = storage_path() . DIRECTORY_SEPARATOR . 'app' . DIRECTORY_SEPARATOR . $file;
     $docs->sended = 1;
     $docs->save();
     return storage_path() . DIRECTORY_SEPARATOR . 'app' . DIRECTORY_SEPARATOR . $file;
 }
コード例 #6
0
 /**
  * Finds the Document model based on its primary key value.
  * If the model is not found, a 404 HTTP exception will be thrown.
  * @param integer $id
  * @return Document the loaded model
  * @throws NotFoundHttpException if the model cannot be found
  */
 protected function findModel($id)
 {
     if (($model = Document::findOne($id)) !== null) {
         return $model;
     } else {
         throw new NotFoundHttpException('The requested page does not exist.');
     }
 }
コード例 #7
0
ファイル: DocumentsController.php プロジェクト: 2377635/test
 /**
  * Загрузка документа
  * @param integer $id
  * @return app\models\Document
  * @throws NotFoundHttpException
  */
 public function loadDocument($id)
 {
     if (($document = Document::findOne($id)) !== null) {
         return $document;
     } else {
         throw new NotFoundHttpException('The requested page does not exist.');
     }
 }
コード例 #8
0
 /**
  * Display a listing of the resource.
  *
  * @return Response
  */
 public function index()
 {
     $user = Auth::user();
     $firmName = $user->firm->organisation_name;
     $countOfOrders = Order::where('user_id', Auth::user()->id)->count();
     $countOfDocuments = Document::where('user_id', Auth::user()->id)->count();
     return view('cabinet.index', ['p' => 'cabinet', 'userId' => $user->id, 'firmName' => $firmName, 'countOfOrders' => $countOfOrders, 'countOfDocuments' => $countOfDocuments]);
 }
コード例 #9
0
 public function fire()
 {
     $this->info(date('Y-m-d') . ' Running RemoveOrphanedDocuments...');
     $documents = Document::whereRaw('invoice_id IS NULL AND expense_id IS NULL AND updated_at <= ?', array(new DateTime('-1 hour')))->get();
     $this->info(count($documents) . ' orphaned document(s) found');
     foreach ($documents as $document) {
         $document->delete();
     }
     $this->info('Done');
 }
コード例 #10
0
 public function save($input, $expense = null)
 {
     $publicId = isset($input['public_id']) ? $input['public_id'] : false;
     if ($expense) {
         // do nothing
     } elseif ($publicId) {
         $expense = Expense::scope($publicId)->firstOrFail();
         \Log::warning('Entity not set in expense repo save');
     } else {
         $expense = Expense::createNew();
     }
     // First auto fill
     $expense->fill($input);
     $expense->expense_date = Utils::toSqlDate($input['expense_date']);
     if (isset($input['private_notes'])) {
         $expense->private_notes = trim($input['private_notes']);
     }
     $expense->public_notes = trim($input['public_notes']);
     $expense->should_be_invoiced = isset($input['should_be_invoiced']) && floatval($input['should_be_invoiced']) || $expense->client_id ? true : false;
     if (!$expense->expense_currency_id) {
         $expense->expense_currency_id = \Auth::user()->account->getCurrencyId();
     }
     if (!$expense->invoice_currency_id) {
         $expense->invoice_currency_id = \Auth::user()->account->getCurrencyId();
     }
     $rate = isset($input['exchange_rate']) ? Utils::parseFloat($input['exchange_rate']) : 1;
     $expense->exchange_rate = round($rate, 4);
     $expense->amount = round(Utils::parseFloat($input['amount']), 2);
     $expense->save();
     // Documents
     $document_ids = !empty($input['document_ids']) ? array_map('intval', $input['document_ids']) : [];
     foreach ($document_ids as $document_id) {
         // check document completed upload before user submitted form
         if ($document_id) {
             $document = Document::scope($document_id)->first();
             if ($document && Auth::user()->can('edit', $document)) {
                 $document->invoice_id = null;
                 $document->expense_id = $expense->id;
                 $document->save();
             }
         }
     }
     // prevent loading all of the documents if we don't have to
     if (!$expense->wasRecentlyCreated) {
         foreach ($expense->documents as $document) {
             if (!in_array($document->public_id, $document_ids)) {
                 // Not checking permissions; deleting a document is just editing the invoice
                 $document->delete();
             }
         }
     }
     return $expense;
 }
コード例 #11
0
 public function addDocument(Application $application, Request $request)
 {
     if ($application->user->id != Auth::user()->id && !Auth::user()->can('add-files')) {
         $request->session()->flash('error', 'Only the person who created an application may answer questions for it.');
         return redirect('/login');
     }
     // Save uploaded file
     $upload = Document::handleUpload($request);
     // Save new document
     Document::createDocument($application, $upload, null);
     $request->session()->flash('success', 'Your file has been added.');
     return redirect()->back();
 }
コード例 #12
0
 /**
  * Creates data provider instance with search query applied
  *
  * @param array $params
  *
  * @return ActiveDataProvider
  */
 public function search($params)
 {
     $query = Document::find();
     $dataProvider = new ActiveDataProvider(['query' => $query]);
     $this->load($params);
     if (!$this->validate()) {
         // uncomment the following line if you do not want to return any records when validation fails
         // $query->where('0=1');
         return $dataProvider;
     }
     $query->andFilterWhere(['id' => $this->id]);
     $query->andFilterWhere(['like', 'name', $this->name])->andFilterWhere(['like', 'content', $this->content]);
     return $dataProvider;
 }
コード例 #13
0
 public function add()
 {
     if (Request::isMethod('get')) {
         // tampilkan form
         $members = Member::get();
         return view('document.add', compact('members'));
     } else {
         // simpan document baru
         $document = Document::create(Input::only('name', 'url', 'member_id'));
         // $member_id = Input::get('member_id');
         // $member    = Member::find($member_id);
         // $document->member()->associate($member)->save();
         return redirect('document');
     }
 }
コード例 #14
0
 public function show($id)
 {
     if ($id) {
         if ($id == "photos") {
             $datas = Photo::get();
         } elseif ($id == "videos") {
             $datas = Video::get();
         } elseif ($id == "documents") {
             $datas = Document::get();
         } elseif ($id == "audios") {
             $datas = Audio::get();
         } elseif ($id == "uploadedfiles") {
             $datas = UploadedFile::get();
         }
         return view("Modvel::admin." . $this->theme . ".files.show")->with('datas', $datas)->with('headName', $this->headName);
     }
 }
コード例 #15
0
 /**
  * Retrieve Collection
  *
  * @param String $name
  * @param Request $request
  * @return Response
  */
 public function getCollection($name, Request $request)
 {
     if (!$this->appKeyAvailable($request)) {
         return $this->notAuthorized($request);
     }
     $collection = $this->readCollection($name);
     if (!$collection) {
         $this->setResultError("Collection '{$name}' doesn't exist", 404);
     } elseif (!$this->setSessionUser($request)) {
         $this->setResultError("Not logged in", 401);
     } elseif (!$this->isModerator()) {
         $this->setResultError("Unauthorized action", 403);
     } else {
         $count = Document::whereCollectionId($collection->id)->count();
         $this->setResultOk(['count' => $count, 'name' => $collection->name]);
     }
     return $this->setResponse();
 }
コード例 #16
0
 public function uploads()
 {
     if (isset($_FILES['upl']) && $_FILES['upl']['error'] == 0) {
         $extension = pathinfo($_FILES['upl']['name'], PATHINFO_EXTENSION);
         $_FILES['upl']['name'] = uniqid() . '.' . $extension;
         $document = array('name' => $_FILES['upl']['name'], 'path' => $_FILES['upl']['name'], 'thumb' => $_FILES['upl']['name'], 'user_id' => Auth::user()->id, 'status_id' => 1);
         //var_dump($document);die;
         $new = Document::create($document);
         $new->save();
         //	if(!in_array(strtolower($extension), $allowed)){
         //		echo '{"status":"error"}';
         //		exit;
         //	}
         $this->createThumb();
         if (move_uploaded_file($_FILES['upl']['tmp_name'], 'uploads/' . $_FILES['upl']['name'])) {
             return Response::json($_FILES['upl']['name']);
         }
     }
 }
コード例 #17
0
ファイル: FilesController.php プロジェクト: Baasify/Baasify
 /**
  * Upload New File and attach it to a document
  *
  * @param Int $document
  * @param Request $request
  * @return Response
  */
 public function postFileToDocument($document, Request $request)
 {
     if (!$this->appKeyAvailable($request)) {
         return $this->notAuthorized($request);
     }
     $upload = array('file' => $request->file('file'));
     $rules = array('file' => 'required');
     $validator = Validator::make($upload, $rules);
     if (!empty($document) && !$this->isDocument($document)) {
         $this->setResultError("Document not found", 404);
     } elseif ($validator->fails()) {
         $this->setResultError($validator->messages(), 400);
     } elseif (!$this->setSessionUser($request)) {
         $this->setResultError("Not logged in", 401);
     } elseif ($document !== null && Document::find($document)->user_id != $this->user->id && !$this->isModerator()) {
         $this->setResultError("Unauthorized action", 403);
     } else {
         if ($request->file('file')->isValid()) {
             $destinationPath = '../uploads';
             $extension = Input::file('file')->getClientOriginalExtension();
             $fileName = uniqid() . '.' . $extension;
             $file = new File();
             $file->user_id = $this->user->id;
             $file->document_id = $document;
             $file->name = Input::file('file')->getClientOriginalName();
             $file->mime = Input::file('file')->getMimeType();
             $file->size = Input::file('file')->getSize();
             $file->path = $destinationPath . '/' . $fileName;
             Input::file('file')->move($destinationPath, $fileName);
             $file->save();
             $this->setAllowed(null, $file->id, $this->user->id, null, 'all');
             $this->setResultOk();
             $this->setFileData($file);
         } else {
             $this->setResultError('File is not valid', 400);
         }
     }
     return $this->setResponse();
 }
コード例 #18
0
 public function updateAnswer(AnswerRequest $request, Answer $answer)
 {
     $input = $request->all();
     $application = Application::find($input['application_id']);
     if ($answer->user->id != Auth::user()->id) {
         $request->session()->flash('error', 'Only the person who created an application may answer questions for it.');
         return redirect('/login');
     }
     if ($answer->application->status != 'new') {
         $request->session()->flash('error', 'Your application has been submitted, you may no longer make changes.');
         return redirect('/applications/' . $application->id . '/review');
     }
     $answer->update($input);
     // Check if a file needs to be uploaded
     if ($answer->question->type == 'file') {
         // Save uploaded file
         $upload = Document::handleUpload($request);
         // Save new document
         Document::createDocument($application, $upload, $answer);
     }
     $request->session()->flash('success', 'Your answer has been saved.');
     return redirect('/applications/' . $answer->application->id);
 }
コード例 #19
0
 public function upload(Request $request, $id)
 {
     $settings = Settings::findOrFail(1);
     $companyname = $settings->company;
     if (!is_dir(public_path() . '/files/' . $companyname)) {
         mkdir(public_path() . '/files/' . $companyname, 0777, true);
     }
     $file = $request->file('file');
     $destinationPath = public_path() . '/files/' . $companyname;
     $filename = str_random(8) . '_' . $file->getClientOriginalName();
     $fileOrginal = $file->getClientOriginalName();
     $file->move($destinationPath, $filename);
     $size = $file->getClientSize();
     $mbsize = $size / 1048576;
     $totaltsize = substr($mbsize, 0, 4);
     if ($totaltsize > 15) {
         Session::flash('flash_message', 'File Size can not be bigger then 15MB');
         return redirect()->back();
     }
     $input = array_replace($request->all(), ['path' => "{$filename}", 'size' => "{$totaltsize}", 'file_display' => "{$fileOrginal}", 'fk_client_id' => $id]);
     $document = Document::create($input);
     Session::flash('flash_message', 'File successfully uploaded');
 }
コード例 #20
0
 public function getDocument($invitationKey, $publicId)
 {
     if (!($invitation = $this->invoiceRepo->findInvoiceByInvitation($invitationKey))) {
         return $this->returnError();
     }
     Session::put('contact_key', $invitation->contact->contact_key);
     // track current contact
     $clientId = $invitation->invoice->client_id;
     $document = Document::scope($publicId, $invitation->account_id)->firstOrFail();
     $authorized = false;
     if ($document->expense && $document->expense->client_id == $invitation->invoice->client_id) {
         $authorized = true;
     } else {
         if ($document->invoice && $document->invoice->client_id == $invitation->invoice->client_id) {
             $authorized = true;
         }
     }
     if (!$authorized) {
         return Response::view('error', ['error' => 'Not authorized'], 403);
     }
     return DocumentController::getDownloadResponse($document);
 }
コード例 #21
0
 /**
  * @param array $data
  * @param Invoice|null $invoice
  * @return Invoice|mixed
  */
 public function save(array $data, Invoice $invoice = null)
 {
     /** @var Account $account */
     $account = \Auth::user()->account;
     $publicId = isset($data['public_id']) ? $data['public_id'] : false;
     $isNew = !$publicId || $publicId == '-1';
     if ($invoice) {
         // do nothing
         $entityType = $invoice->getEntityType();
     } elseif ($isNew) {
         $entityType = ENTITY_INVOICE;
         if (isset($data['is_recurring']) && filter_var($data['is_recurring'], FILTER_VALIDATE_BOOLEAN)) {
             $entityType = ENTITY_RECURRING_INVOICE;
         } elseif (isset($data['is_quote']) && filter_var($data['is_quote'], FILTER_VALIDATE_BOOLEAN)) {
             $entityType = ENTITY_QUOTE;
         }
         $invoice = $account->createInvoice($entityType, $data['client_id']);
         $invoice->invoice_date = date_create()->format('Y-m-d');
         if (isset($data['has_tasks']) && filter_var($data['has_tasks'], FILTER_VALIDATE_BOOLEAN)) {
             $invoice->has_tasks = true;
         }
         if (isset($data['has_expenses']) && filter_var($data['has_expenses'], FILTER_VALIDATE_BOOLEAN)) {
             $invoice->has_expenses = true;
         }
     } else {
         $invoice = Invoice::scope($publicId)->firstOrFail();
         \Log::warning('Entity not set in invoice repo save');
     }
     $invoice->fill($data);
     if (isset($data['set_default_terms']) && $data['set_default_terms'] || isset($data['set_default_footer']) && $data['set_default_footer']) {
         if (isset($data['set_default_terms']) && $data['set_default_terms']) {
             $account->{"{$invoice->getEntityType()}_terms"} = trim($data['terms']);
         }
         if (isset($data['set_default_footer']) && $data['set_default_footer']) {
             $account->invoice_footer = trim($data['invoice_footer']);
         }
         $account->save();
     }
     if (isset($data['invoice_number']) && !$invoice->is_recurring) {
         $invoice->invoice_number = trim($data['invoice_number']);
     }
     if (isset($data['discount'])) {
         $invoice->discount = round(Utils::parseFloat($data['discount']), 2);
     }
     if (isset($data['is_amount_discount'])) {
         $invoice->is_amount_discount = $data['is_amount_discount'] ? true : false;
     }
     if (isset($data['partial'])) {
         $invoice->partial = round(Utils::parseFloat($data['partial']), 2);
     }
     if (isset($data['invoice_date_sql'])) {
         $invoice->invoice_date = $data['invoice_date_sql'];
     } elseif (isset($data['invoice_date'])) {
         $invoice->invoice_date = Utils::toSqlDate($data['invoice_date']);
     }
     if (isset($data['invoice_status_id'])) {
         if ($data['invoice_status_id'] == 0) {
             $data['invoice_status_id'] = INVOICE_STATUS_DRAFT;
         }
         $invoice->invoice_status_id = $data['invoice_status_id'];
     }
     if ($invoice->is_recurring) {
         if ($invoice->start_date && $invoice->start_date != Utils::toSqlDate($data['start_date'])) {
             $invoice->last_sent_date = null;
         }
         $invoice->frequency_id = $data['frequency_id'] ? $data['frequency_id'] : 0;
         $invoice->start_date = Utils::toSqlDate($data['start_date']);
         $invoice->end_date = Utils::toSqlDate($data['end_date']);
         $invoice->client_enable_auto_bill = isset($data['client_enable_auto_bill']) && $data['client_enable_auto_bill'] ? true : false;
         $invoice->auto_bill = isset($data['auto_bill']) ? intval($data['auto_bill']) : AUTO_BILL_OFF;
         if ($invoice->auto_bill < AUTO_BILL_OFF || $invoice->auto_bill > AUTO_BILL_ALWAYS) {
             $invoice->auto_bill = AUTO_BILL_OFF;
         }
         if (isset($data['recurring_due_date'])) {
             $invoice->due_date = $data['recurring_due_date'];
         } elseif (isset($data['due_date'])) {
             $invoice->due_date = $data['due_date'];
         }
     } else {
         if (isset($data['due_date']) || isset($data['due_date_sql'])) {
             $invoice->due_date = isset($data['due_date_sql']) ? $data['due_date_sql'] : Utils::toSqlDate($data['due_date']);
         }
         $invoice->frequency_id = 0;
         $invoice->start_date = null;
         $invoice->end_date = null;
     }
     if (isset($data['terms']) && trim($data['terms'])) {
         $invoice->terms = trim($data['terms']);
     } elseif ($isNew && $account->{"{$entityType}_terms"}) {
         $invoice->terms = $account->{"{$entityType}_terms"};
     } else {
         $invoice->terms = '';
     }
     $invoice->invoice_footer = isset($data['invoice_footer']) && trim($data['invoice_footer']) ? trim($data['invoice_footer']) : (!$publicId && $account->invoice_footer ? $account->invoice_footer : '');
     $invoice->public_notes = isset($data['public_notes']) ? trim($data['public_notes']) : null;
     // process date variables if not recurring
     if (!$invoice->is_recurring) {
         $invoice->terms = Utils::processVariables($invoice->terms);
         $invoice->invoice_footer = Utils::processVariables($invoice->invoice_footer);
         $invoice->public_notes = Utils::processVariables($invoice->public_notes);
     }
     if (isset($data['po_number'])) {
         $invoice->po_number = trim($data['po_number']);
     }
     $invoice->invoice_design_id = isset($data['invoice_design_id']) ? $data['invoice_design_id'] : $account->invoice_design_id;
     // provide backwards compatability
     if (isset($data['tax_name']) && isset($data['tax_rate'])) {
         $data['tax_name1'] = $data['tax_name'];
         $data['tax_rate1'] = $data['tax_rate'];
     }
     $total = 0;
     $itemTax = 0;
     foreach ($data['invoice_items'] as $item) {
         $item = (array) $item;
         if (!$item['cost'] && !$item['product_key'] && !$item['notes']) {
             continue;
         }
         $invoiceItemCost = round(Utils::parseFloat($item['cost']), 2);
         $invoiceItemQty = round(Utils::parseFloat($item['qty']), 2);
         $lineTotal = $invoiceItemCost * $invoiceItemQty;
         $total += round($lineTotal, 2);
     }
     foreach ($data['invoice_items'] as $item) {
         $item = (array) $item;
         $invoiceItemCost = round(Utils::parseFloat($item['cost']), 2);
         $invoiceItemQty = round(Utils::parseFloat($item['qty']), 2);
         $lineTotal = $invoiceItemCost * $invoiceItemQty;
         if ($invoice->discount > 0) {
             if ($invoice->is_amount_discount) {
                 $lineTotal -= round($lineTotal / $total * $invoice->discount, 2);
             } else {
                 $lineTotal -= round($lineTotal * ($invoice->discount / 100), 2);
             }
         }
         if (isset($item['tax_rate1']) && Utils::parseFloat($item['tax_rate1']) > 0) {
             $invoiceItemTaxRate = Utils::parseFloat($item['tax_rate1']);
             $itemTax += round($lineTotal * $invoiceItemTaxRate / 100, 2);
         }
         if (isset($item['tax_rate2']) && Utils::parseFloat($item['tax_rate2']) > 0) {
             $invoiceItemTaxRate = Utils::parseFloat($item['tax_rate2']);
             $itemTax += round($lineTotal * $invoiceItemTaxRate / 100, 2);
         }
     }
     if ($invoice->discount > 0) {
         if ($invoice->is_amount_discount) {
             $total -= $invoice->discount;
         } else {
             $total *= (100 - $invoice->discount) / 100;
             $total = round($total, 2);
         }
     }
     if (isset($data['custom_value1'])) {
         $invoice->custom_value1 = round($data['custom_value1'], 2);
         if ($isNew) {
             $invoice->custom_taxes1 = $account->custom_invoice_taxes1 ?: false;
         }
     }
     if (isset($data['custom_value2'])) {
         $invoice->custom_value2 = round($data['custom_value2'], 2);
         if ($isNew) {
             $invoice->custom_taxes2 = $account->custom_invoice_taxes2 ?: false;
         }
     }
     if (isset($data['custom_text_value1'])) {
         $invoice->custom_text_value1 = trim($data['custom_text_value1']);
     }
     if (isset($data['custom_text_value2'])) {
         $invoice->custom_text_value2 = trim($data['custom_text_value2']);
     }
     // custom fields charged taxes
     if ($invoice->custom_value1 && $invoice->custom_taxes1) {
         $total += $invoice->custom_value1;
     }
     if ($invoice->custom_value2 && $invoice->custom_taxes2) {
         $total += $invoice->custom_value2;
     }
     $taxAmount1 = round($total * $invoice->tax_rate1 / 100, 2);
     $taxAmount2 = round($total * $invoice->tax_rate2 / 100, 2);
     $total = round($total + $taxAmount1 + $taxAmount2, 2);
     $total += $itemTax;
     // custom fields not charged taxes
     if ($invoice->custom_value1 && !$invoice->custom_taxes1) {
         $total += $invoice->custom_value1;
     }
     if ($invoice->custom_value2 && !$invoice->custom_taxes2) {
         $total += $invoice->custom_value2;
     }
     if ($publicId) {
         $invoice->balance = $total - ($invoice->amount - $invoice->balance);
     } else {
         $invoice->balance = $total;
     }
     $invoice->amount = $total;
     $invoice->save();
     if ($publicId) {
         $invoice->invoice_items()->forceDelete();
     }
     $document_ids = !empty($data['document_ids']) ? array_map('intval', $data['document_ids']) : [];
     foreach ($document_ids as $document_id) {
         $document = Document::scope($document_id)->first();
         if ($document && Auth::user()->can('edit', $document)) {
             if ($document->invoice_id && $document->invoice_id != $invoice->id) {
                 // From a clone
                 $document = $document->cloneDocument();
                 $document_ids[] = $document->public_id;
                 // Don't remove this document
             }
             $document->invoice_id = $invoice->id;
             $document->expense_id = null;
             $document->save();
         }
     }
     if (!$invoice->wasRecentlyCreated) {
         foreach ($invoice->documents as $document) {
             if (!in_array($document->public_id, $document_ids)) {
                 // Removed
                 // Not checking permissions; deleting a document is just editing the invoice
                 if ($document->invoice_id == $invoice->id) {
                     // Make sure the document isn't on a clone
                     $document->delete();
                 }
             }
         }
     }
     foreach ($data['invoice_items'] as $item) {
         $item = (array) $item;
         if (empty($item['cost']) && empty($item['product_key']) && empty($item['notes']) && empty($item['custom_value1']) && empty($item['custom_value2'])) {
             continue;
         }
         $task = false;
         if (isset($item['task_public_id']) && $item['task_public_id']) {
             $task = Task::scope($item['task_public_id'])->where('invoice_id', '=', null)->firstOrFail();
             if (Auth::user()->can('edit', $task)) {
                 $task->invoice_id = $invoice->id;
                 $task->client_id = $invoice->client_id;
                 $task->save();
             }
         }
         $expense = false;
         if (isset($item['expense_public_id']) && $item['expense_public_id']) {
             $expense = Expense::scope($item['expense_public_id'])->where('invoice_id', '=', null)->firstOrFail();
             if (Auth::user()->can('edit', $expense)) {
                 $expense->invoice_id = $invoice->id;
                 $expense->client_id = $invoice->client_id;
                 $expense->save();
             }
         }
         if ($productKey = trim($item['product_key'])) {
             if (\Auth::user()->account->update_products && !$invoice->has_tasks && !$invoice->has_expenses) {
                 $product = Product::findProductByKey($productKey);
                 if (!$product) {
                     if (Auth::user()->can('create', ENTITY_PRODUCT)) {
                         $product = Product::createNew();
                         $product->product_key = trim($item['product_key']);
                     } else {
                         $product = null;
                     }
                 }
                 if ($product && Auth::user()->can('edit', $product)) {
                     $product->notes = $task || $expense ? '' : $item['notes'];
                     $product->cost = $expense ? 0 : $item['cost'];
                     $product->save();
                 }
             }
         }
         $invoiceItem = InvoiceItem::createNew();
         $invoiceItem->product_id = isset($product) ? $product->id : null;
         $invoiceItem->product_key = isset($item['product_key']) ? trim($invoice->is_recurring ? $item['product_key'] : Utils::processVariables($item['product_key'])) : '';
         $invoiceItem->notes = trim($invoice->is_recurring ? $item['notes'] : Utils::processVariables($item['notes']));
         $invoiceItem->cost = Utils::parseFloat($item['cost']);
         $invoiceItem->qty = Utils::parseFloat($item['qty']);
         if (isset($item['custom_value1'])) {
             $invoiceItem->custom_value1 = $item['custom_value1'];
         }
         if (isset($item['custom_value2'])) {
             $invoiceItem->custom_value2 = $item['custom_value2'];
         }
         // provide backwards compatability
         if (isset($item['tax_name']) && isset($item['tax_rate'])) {
             $item['tax_name1'] = $item['tax_name'];
             $item['tax_rate1'] = $item['tax_rate'];
         }
         $invoiceItem->fill($item);
         $invoice->invoice_items()->save($invoiceItem);
     }
     return $invoice;
 }
コード例 #22
0
 /**
  * Revoke Permission on a Document for a Group
  *
  * @param String $name
  * @param Int $id
  * @param String $access
  * @param Int $group
  * @param Request $request
  * @return Response
  */
 public function deleteGroupPermission($name, $id, $access, $group, Request $request)
 {
     if (!$this->appKeyAvailable($request)) {
         return $this->notAuthorized($request);
     }
     if (!$this->setSessionUser($request)) {
         $this->setResultError("Not logged in", 401);
     } elseif (!$this->isCollection($name)) {
         $this->setResultError("Collection '{$name}' doesn't exist", 401);
     } elseif (!in_array($access, ['read', 'update', 'delete', 'all'])) {
         $this->setResultError("Unknown permission '{$access}'", 400);
     } else {
         $document = Document::find($id);
         if (!$document) {
             $this->setResultError("Document is not found", 404);
         } elseif (!$this->isAllowed($request, 'document', $id, 'update') && !$this->isModerator()) {
             $this->setResultError("Unauthorized action", 403);
         } else {
             $this->setUnAllowed($id, null, null, $group, $access);
             $this->setResultOk();
         }
     }
     return $this->setResponse();
 }
コード例 #23
0
ファイル: BaseHelpers.php プロジェクト: furkankadioglu/modvel
 public static function addDocument($data, $relationshipId = null, $categoryName = null, $displayName = null)
 {
     if (!is_null($data)) {
         $time = Carbon\Carbon::now()->timestamp;
         $extension = $data->getClientOriginalExtension();
         $mediaName = $time . rand(5, 200000);
         $fileName = $mediaName . "." . $extension;
         $data->move(public_path() . '/uploads/documents/', $fileName);
         if (is_null($displayName)) {
             $displayName = $mediaName;
         }
         if (is_null($relationshipId)) {
             $relationshipId = 0;
         }
         $mediaCreate = Document::create(['displayName' => $displayName, 'fileName' => $fileName, 'categoryName' => $categoryName, 'relId' => $relationshipId]);
         return $mediaCreate;
     }
 }
コード例 #24
0
 /**
  * @return mixed
  */
 public function cloneDocument()
 {
     $document = Document::createNew($this);
     $document->path = $this->path;
     $document->preview = $this->preview;
     $document->name = $this->name;
     $document->type = $this->type;
     $document->disk = $this->disk;
     $document->hash = $this->hash;
     $document->size = $this->size;
     $document->width = $this->width;
     $document->height = $this->height;
     return $document;
 }
コード例 #25
0
 /**
  * Show the form for editing the specified resource.
  *
  * @param  int  $id
  * @return \Illuminate\Http\Response
  */
 public function edit($id)
 {
     $item = \App\Models\Item::find($id);
     $document = \App\Models\Document::find($item->document_id);
     $type = $document->os_type;
     switch ($type) {
         case 'movables' || 'value_movables':
             $variable = \App\Models\Item::find($id)->variable();
             return View::make('item.edit', array('item' => $item, 'document' => $document, 'variable' => $variable));
             break;
         case 'car':
             $variable = \App\Models\Item::find($id)->variable();
             $car = \App\Models\Car::find($id)->car();
             return View::make('item.edit', array('item' => $item, 'document' => $document, 'variable' => $variable, 'car' => $car));
             break;
         case 'buildings':
             $variable = \App\Models\Item::find($id)->variable();
             $building = \App\Models\Item::find($id)->building();
             $address = \App\Models\Address::find($id)->address();
             return View::make('item.edit', array('item' => $item, 'document' => $document, 'building' => $building, 'variable' => $variable, 'address' => $address));
             break;
         case 'parcels':
             $parcel = \App\Models\Item::find($id)->parcel();
             $address = \App\Models\Address::find($id)->address();
             return View::make('item.edit', array('item' => $item, 'document' => $document, 'parcel' => $parcel, 'address' => $address));
             break;
     }
 }
コード例 #26
0
 public function sendCheckedDocuments(Request $request)
 {
     $documentIds = json_decode($request->value);
     $documents = Document::whereIn('id', $documentIds)->get();
     $fileNames = [];
     $orderId = 0;
     $userId = 0;
     foreach ($documents as $document) {
         $fileNames[] = ['type' => $document->type, 'fName' => $document->file_name];
     }
     $orderId = $document->order_id ? $document->order_id : $document->service_order_id;
     $userId = $document->user_id;
     $resOfSend = Bus::dispatch(new SendEmailWithCheckedDocs($fileNames, $orderId, $userId));
     if ($resOfSend == Utils::STR_SUCCESS) {
         foreach ($documents as $document) {
             $document->sended = 1;
             $document->save();
         }
         //return redirect()->back()->with('alert-success','Документы отправлены заказчику.');
         echo 'success';
     } else {
         //return redirect()->back()->with('alert-danger','Ошибка отправки документов.');
         echo 'danger';
     }
 }
コード例 #27
0
 public function upload($uploaded, &$doc_array = null)
 {
     $extension = strtolower($uploaded->getClientOriginalExtension());
     if (empty(Document::$types[$extension]) && !empty(Document::$extraExtensions[$extension])) {
         $documentType = Document::$extraExtensions[$extension];
     } else {
         $documentType = $extension;
     }
     if (empty(Document::$types[$documentType])) {
         return 'Unsupported file type';
     }
     $documentTypeData = Document::$types[$documentType];
     $filePath = $uploaded->path();
     $name = $uploaded->getClientOriginalName();
     $size = filesize($filePath);
     if ($size / 1000 > MAX_DOCUMENT_SIZE) {
         return 'File too large';
     }
     $hash = sha1_file($filePath);
     $filename = \Auth::user()->account->account_key . '/' . $hash . '.' . $documentType;
     $document = Document::createNew();
     $disk = $document->getDisk();
     if (!$disk->exists($filename)) {
         // Have we already stored the same file
         $stream = fopen($filePath, 'r');
         $disk->getDriver()->putStream($filename, $stream, ['mimetype' => $documentTypeData['mime']]);
         fclose($stream);
     }
     // This is an image; check if we need to create a preview
     if (in_array($documentType, array('jpeg', 'png', 'gif', 'bmp', 'tiff', 'psd'))) {
         $makePreview = false;
         $imageSize = getimagesize($filePath);
         $width = $imageSize[0];
         $height = $imageSize[1];
         $imgManagerConfig = array();
         if (in_array($documentType, array('gif', 'bmp', 'tiff', 'psd'))) {
             // Needs to be converted
             $makePreview = true;
         } else {
             if ($width > DOCUMENT_PREVIEW_SIZE || $height > DOCUMENT_PREVIEW_SIZE) {
                 $makePreview = true;
             }
         }
         if (in_array($documentType, array('bmp', 'tiff', 'psd'))) {
             if (!class_exists('Imagick')) {
                 // Cant't read this
                 $makePreview = false;
             } else {
                 $imgManagerConfig['driver'] = 'imagick';
             }
         }
         if ($makePreview) {
             $previewType = 'jpeg';
             if (in_array($documentType, array('png', 'gif', 'tiff', 'psd'))) {
                 // Has transparency
                 $previewType = 'png';
             }
             $document->preview = \Auth::user()->account->account_key . '/' . $hash . '.' . $documentType . '.x' . DOCUMENT_PREVIEW_SIZE . '.' . $previewType;
             if (!$disk->exists($document->preview)) {
                 // We haven't created a preview yet
                 $imgManager = new ImageManager($imgManagerConfig);
                 $img = $imgManager->make($filePath);
                 if ($width <= DOCUMENT_PREVIEW_SIZE && $height <= DOCUMENT_PREVIEW_SIZE) {
                     $previewWidth = $width;
                     $previewHeight = $height;
                 } else {
                     if ($width > $height) {
                         $previewWidth = DOCUMENT_PREVIEW_SIZE;
                         $previewHeight = $height * DOCUMENT_PREVIEW_SIZE / $width;
                     } else {
                         $previewHeight = DOCUMENT_PREVIEW_SIZE;
                         $previewWidth = $width * DOCUMENT_PREVIEW_SIZE / $height;
                     }
                 }
                 $img->resize($previewWidth, $previewHeight);
                 $previewContent = (string) $img->encode($previewType);
                 $disk->put($document->preview, $previewContent);
                 $base64 = base64_encode($previewContent);
             } else {
                 $base64 = base64_encode($disk->get($document->preview));
             }
         } else {
             $base64 = base64_encode(file_get_contents($filePath));
         }
     }
     $document->path = $filename;
     $document->type = $documentType;
     $document->size = $size;
     $document->hash = $hash;
     $document->name = substr($name, -255);
     if (!empty($imageSize)) {
         $document->width = $imageSize[0];
         $document->height = $imageSize[1];
     }
     $document->save();
     $doc_array = $document->toArray();
     if (!empty($base64)) {
         $mime = Document::$types[!empty($previewType) ? $previewType : $documentType]['mime'];
         $doc_array['base64'] = 'data:' . $mime . ';base64,' . $base64;
     }
     return $document;
 }
コード例 #28
0
 /**
  * Execute the command.
  *
  * @return void
  */
 public function handle()
 {
     $selfFirmUser = User::with('firm')->where('role_id', User::ADMIN)->first();
     $userCompany = User::with('firm')->where('id', $this->order->user_id)->first();
     $products = $this->order->products_in_order;
     $firm = $userCompany->firm;
     $productsArr = [];
     foreach ($products as $product) {
         $productsArr[$this->depo->id][] = ['product_name' => $product->product_name, 'product_amount' => $product->product_amount, 'product_price' => $product->product_price, 'product_nds' => Product::getVAT_calculationByKey($product->nds), 'product_nds_as_str' => Product::getAllVAT_rateByKey($product->nds)];
     }
     $date = DateTime::createFromFormat('Y-m-d H:i:s', $this->order->created_at);
     $date = strtotime($date->format('d F Y'));
     if (!$firm->rp_face_fio) {
         $faceFioArr = explode(' ', $firm->face_fio);
         $lastName = isset($faceFioArr[0]) ? $faceFioArr[0] : '';
         $name = isset($faceFioArr[1]) ? $faceFioArr[1] : '';
         $secondName = isset($faceFioArr[2]) ? $faceFioArr[2] : '';
         $petrovich = new Petrovich();
         $petrovich->gender = $petrovich->detectGender($secondName);
         if ($petrovich->gender == Petrovich::FAIL_MIDDLEWARE) {
             $fio = $firm->face_fio;
         } else {
             $fio = $petrovich->lastname($lastName, Petrovich::CASE_GENITIVE) . ' ' . $petrovich->firstname($name, Petrovich::CASE_GENITIVE) . ' ' . $petrovich->middlename($secondName, Petrovich::CASE_GENITIVE);
             $firm->rp_face_fio = $fio;
             $firm->save();
         }
     } else {
         $fio = $firm->rp_face_fio;
     }
     if (!$firm->rp_face_position) {
         $facePosition = Utils::getGenitiveCase($firm->face_position);
         if ($facePosition != $firm->face_position) {
             $firm->rp_face_position = $facePosition;
             $firm->save();
         }
     } else {
         $facePosition = $firm->rp_face_position;
     }
     if (!$firm->rp_base_document) {
         $baseDocument = Utils::getGenitiveCase($firm->base_document);
         if ($baseDocument != $firm->base_document) {
             $firm->rp_base_document = $baseDocument;
             $firm->save();
         }
     } else {
         $baseDocument = $firm->rp_base_document;
     }
     $pdf = App::make('dompdf.wrapper');
     $pdf->loadView('documents.invoice', ['orderNumber' => $this->order->id, 'orderDate' => date('d.m.Y', $date), 'firm' => $firm, 'firmRpFio' => $fio, 'firmFacePosition' => $facePosition, 'firmBaseDocument' => $baseDocument, 'selfFirm' => $selfFirmUser->firm, 'products' => $productsArr, 'depoId' => $this->depo->id, 'depoName' => $this->depo->stantion_name]);
     //$whereAreClientDocuments = storage_path().'/app'.Config::get('documents')['documents_folder'];
     $documents = Config::get('documents');
     $whereAreClientDocuments = $documents['documents_folder'];
     //client_{id}
     if (!Storage::disk('local')->exists($whereAreClientDocuments . '/client_' . Auth::user()->id)) {
         Storage::makeDirectory($whereAreClientDocuments . '/client_' . Auth::user()->id);
     }
     //invoices
     if (!Storage::disk('local')->exists($whereAreClientDocuments . '/client_' . Auth::user()->id . '/invoices')) {
         Storage::makeDirectory($whereAreClientDocuments . '/client_' . Auth::user()->id . '/invoices');
     }
     $clientFolder = storage_path() . '/app' . $whereAreClientDocuments . '/client_' . Auth::user()->id . '/invoices';
     //invoice_{orderID}_{depoName}_date_{currentDate}
     $fileNameTemplate = $documents['client_invoice_template'];
     $fileNameTemplate = Utils::mb_str_replace('{docType}', Order::getDocTypeName(Order::INVOICE_TYPE), $fileNameTemplate);
     $fileNameTemplate = Utils::mb_str_replace('{orderID}', $this->order->id, $fileNameTemplate);
     $depoName = Utils::mb_str_replace(' ', '', $this->depo->stantion_name);
     $depoName = Utils::translit($depoName);
     $fileNameTemplate = Utils::mb_str_replace('{depoName}', $depoName, $fileNameTemplate);
     $fileNameTemplate = Utils::mb_str_replace('{currentDate}', time(), $fileNameTemplate);
     $pdf->save($clientFolder . '/' . $fileNameTemplate);
     $docs = new Document();
     $docs->type = Order::INVOICE_TYPE;
     $docs->user_id = Auth::user()->id;
     $docs->order_id = $this->order->id;
     $docs->file_name = $clientFolder . '/' . $fileNameTemplate;
     $docs->sended = 1;
     $docs->save();
 }
コード例 #29
0
 /**
  * @return \Illuminate\Http\RedirectResponse
  */
 public function cancelAccount()
 {
     if ($reason = trim(Input::get('reason'))) {
         $email = Auth::user()->email;
         $name = Auth::user()->getDisplayName();
         $data = ['text' => $reason];
         $subject = 'Invoice Ninja - Canceled Account';
         $this->userMailer->sendTo(CONTACT_EMAIL, $email, $name, $subject, 'contact', $data);
     }
     $user = Auth::user();
     $account = Auth::user()->account;
     \Log::info("Canceled Account: {$account->name} - {$user->email}");
     Document::scope()->each(function ($item, $key) {
         $item->delete();
     });
     $this->accountRepo->unlinkAccount($account);
     if ($account->company->accounts->count() == 1) {
         $account->company->forceDelete();
     } else {
         $account->forceDelete();
     }
     Auth::logout();
     Session::flush();
     return Redirect::to('/')->with('clearGuestKey', true);
 }
コード例 #30
0
ファイル: UserController.php プロジェクト: khakanali/OpenMAll
 /**
  * Store a newly created resource in storage.
  *
  * @param  \Illuminate\Http\Request  $request
  * @return \Illuminate\Http\Response
  */
 public function store(Request $request)
 {
     /*
             $brand_name_array = $request->get('brand_name');
             Models used fo registering a merchant
             User, Bank, Buyer, Address, Merchant, Brand, Website and Director
     */
     $user = new User();
     $user_model = $user->store($request);
     //return new user record in db
     $bank = new Bank();
     $bank_model = $bank->store($request);
     if ($request['indication'] == 'buyer') {
         return "no functionality implemented";
         $buyer = new Buyer();
         $buyer_model = $buyer->store($request, $user_model);
     }
     if ($request['indication'] == 'merchant') {
         //TODO: for adding address first create address then add address id to merchant table
         //country_id   => working
         $address = new Address();
         $address_model = $address->store($request);
         // user_id, country_id, address_id, bank_id => working
         $user_as_merchant = new Merchant();
         $user_as_merchant_model = $user_as_merchant->store($request, $user_model, $bank_model, $address_model);
         /*
          * Document table
          */
         $documents = new Document();
         $documents_model = $documents->store($request, $user_as_merchant_model);
         //todo: add brand
         //1)create merchant and get model
         //2)create all brand and get all models
         //3)sync merchant model with brand models in merchantbrand table
         $brand = new Brand();
         $brand_models = $brand->store($request, $user_as_merchant_model, $address_model);
         //now syncing
         $user_as_merchant_model->attachBrands($user_as_merchant_model, $brand_models);
         //http://laravel.com/docs/5.1/eloquent-relationships#inserting-many-to-many-relationships
         //for storing web sites in "merchantwebsite" table
         //first create merchant and get id
         //then create websites and get website model array like director
         //then attach merchant with each website id
         $website = new Website();
         $website_models = $website->store($request);
         //attachment with merchant in "merchantwebsite" table
         $user_as_merchant->attachWebsites($website_models, $user_as_merchant_model);
         $director = new Director();
         $director_model = $director->store($request, $user_as_merchant_model);
         /*save all FKs of directors & merchants to merchantdirectos tables */
         $user_as_merchant_model->attachDirectors($director_model, $user_as_merchant_model);
         \Session::flash(Config::get('messages.key.name'), $this->messageHandler->success('merchantRegistered', null, null, true, true, true));
     }
     return redirect()->back();
 }