public function save($publicId, $data)
 {
     if ($publicId) {
         $task = Task::scope($publicId)->firstOrFail();
     } else {
         $task = Task::createNew();
     }
     if (isset($data['client']) && $data['client']) {
         $task->client_id = Client::getPrivateId($data['client']);
     }
     if (isset($data['description'])) {
         $task->description = trim($data['description']);
     }
     //$timeLog = $task->time_log ? json_decode($task->time_log, true) : [];
     $timeLog = isset($data['time_log']) ? json_decode($data['time_log']) : [];
     if ($data['action'] == 'start') {
         $task->is_running = true;
         $timeLog[] = [strtotime('now'), false];
     } else {
         if ($data['action'] == 'resume') {
             $task->is_running = true;
             $timeLog[] = [strtotime('now'), false];
         } else {
             if ($data['action'] == 'stop' && $task->is_running) {
                 $timeLog[count($timeLog) - 1][1] = time();
                 $task->is_running = false;
             }
         }
     }
     $task->time_log = json_encode($timeLog);
     $task->save();
     return $task;
 }
Example #2
0
 /**
  * Display the specified resource.
  *
  * @param  int      $id
  * @return Response
  */
 public function show($publicId)
 {
     $client = Client::withTrashed()->scope($publicId)->with('contacts', 'size', 'industry')->firstOrFail();
     Utils::trackViewed($client->getDisplayName(), ENTITY_CLIENT);
     $actionLinks = [['label' => trans('texts.new_task'), 'url' => '/tasks/create/' . $client->public_id]];
     if (Utils::isPro()) {
         array_push($actionLinks, ['label' => trans('texts.new_quote'), 'url' => '/quotes/create/' . $client->public_id]);
     }
     array_push($actionLinks, ['label' => trans('texts.enter_payment'), 'url' => '/payments/create/' . $client->public_id], ['label' => trans('texts.enter_credit'), 'url' => '/credits/create/' . $client->public_id]);
     $data = array('actionLinks' => $actionLinks, 'showBreadcrumbs' => false, 'client' => $client, 'credit' => $client->getTotalCredit(), 'title' => trans('texts.view_client'), 'hasRecurringInvoices' => Invoice::scope()->where('is_recurring', '=', true)->whereClientId($client->id)->count() > 0, 'hasQuotes' => Invoice::scope()->where('is_quote', '=', true)->whereClientId($client->id)->count() > 0, 'hasTasks' => Task::scope()->whereClientId($client->id)->count() > 0, 'gatewayLink' => $client->getGatewayLink());
     return View::make('clients.show', $data);
 }
 /**
  * @SWG\Post(
  *   path="/tasks",
  *   tags={"task"},
  *   summary="Create a task",
  *   @SWG\Parameter(
  *     in="body",
  *     name="body",
  *     @SWG\Schema(ref="#/definitions/Task")
  *   ),
  *   @SWG\Response(
  *     response=200,
  *     description="New task",
  *      @SWG\Schema(type="object", @SWG\Items(ref="#/definitions/Task"))
  *   ),
  *   @SWG\Response(
  *     response="default",
  *     description="an ""unexpected"" error"
  *   )
  * )
  */
 public function store()
 {
     $data = Input::all();
     $taskId = isset($data['id']) ? $data['id'] : false;
     if (isset($data['client_id']) && $data['client_id']) {
         $data['client'] = $data['client_id'];
     }
     $task = $this->taskRepo->save($taskId, $data);
     $task = Task::scope($task->public_id)->with('client')->first();
     $transformer = new TaskTransformer(Auth::user()->account, Input::get('serializer'));
     $data = $this->createItem($task, $transformer, 'task');
     return $this->response($data);
 }
 public function store()
 {
     $data = Input::all();
     $taskId = isset($data['id']) ? $data['id'] : false;
     if (isset($data['client_id']) && $data['client_id']) {
         $data['client'] = $data['client_id'];
     }
     $task = $this->taskRepo->save($taskId, $data);
     $task = Task::scope($task->public_id)->with('client')->first();
     $task = Utils::remapPublicIds([$task]);
     $response = json_encode($task, JSON_PRETTY_PRINT);
     $headers = Utils::getApiHeaders();
     return Response::make($response, 200, $headers);
 }
Example #5
0
 public function save($publicId, $data)
 {
     if ($publicId) {
         $task = Task::scope($publicId)->firstOrFail();
     } else {
         $task = Task::createNew();
     }
     if (isset($data['client']) && $data['client']) {
         $task->client_id = Client::getPrivateId($data['client']);
     }
     if (isset($data['description'])) {
         $task->description = trim($data['description']);
     }
     $timeLog = $task->time_log ? json_decode($task->time_log, true) : [];
     if ($data['action'] == 'start') {
         $task->start_time = Carbon::now()->toDateTimeString();
         $task->is_running = true;
         $timeLog[] = [strtotime('now'), false];
     } else {
         if ($data['action'] == 'resume') {
             $task->break_duration = strtotime('now') - strtotime($task->start_time) + $task->duration;
             $task->resume_time = Carbon::now()->toDateTimeString();
             $task->is_running = true;
             $timeLog[] = [strtotime('now'), false];
         } else {
             if ($data['action'] == 'stop' && $task->is_running) {
                 if ($task->resume_time) {
                     $task->duration = $task->duration + strtotime('now') - strtotime($task->resume_time);
                     $task->resume_time = null;
                 } else {
                     $task->duration = strtotime('now') - strtotime($task->start_time);
                 }
                 $timeLog[count($timeLog) - 1][1] = strtotime('now');
                 $task->is_running = false;
             } else {
                 if ($data['action'] == 'save' && !$task->is_running) {
                     $task->start_time = $data['start_time'];
                     $task->duration = $data['duration'];
                     $task->break_duration = $data['break_duration'];
                 }
             }
         }
     }
     $task->duration = max($task->duration, 0);
     $task->break_duration = max($task->break_duration, 0);
     $task->time_log = json_encode($timeLog);
     $task->save();
     return $task;
 }
 public function save($publicId, $data, $task = null)
 {
     if ($task) {
         // do nothing
     } elseif ($publicId) {
         $task = Task::scope($publicId)->withTrashed()->firstOrFail();
     } else {
         $task = Task::createNew();
     }
     if ($task->is_deleted) {
         return $task;
     }
     if (isset($data['client']) && $data['client']) {
         $task->client_id = Client::getPrivateId($data['client']);
     }
     if (isset($data['description'])) {
         $task->description = trim($data['description']);
     }
     if (isset($data['time_log'])) {
         $timeLog = json_decode($data['time_log']);
     } elseif ($task->time_log) {
         $timeLog = json_decode($task->time_log);
     } else {
         $timeLog = [];
     }
     array_multisort($timeLog);
     if (isset($data['action'])) {
         if ($data['action'] == 'start') {
             $task->is_running = true;
             $timeLog[] = [strtotime('now'), false];
         } else {
             if ($data['action'] == 'resume') {
                 $task->is_running = true;
                 $timeLog[] = [strtotime('now'), false];
             } else {
                 if ($data['action'] == 'stop' && $task->is_running) {
                     $timeLog[count($timeLog) - 1][1] = time();
                     $task->is_running = false;
                 }
             }
         }
     }
     $task->time_log = json_encode($timeLog);
     $task->save();
     return $task;
 }
 private function getData($request)
 {
     $account = Auth::user()->account;
     $data = ['account' => $account, 'title' => 'Invoice Ninja v' . NINJA_VERSION . ' - ' . $account->formatDateTime($account->getDateTime()), 'multiUser' => $account->users->count() > 1];
     if ($request->input(ENTITY_CLIENT)) {
         $data['clients'] = Client::scope()->with('user', 'contacts', 'country')->get();
         $data['contacts'] = Contact::scope()->with('user', 'client.contacts')->get();
         $data['credits'] = Credit::scope()->with('user', 'client.contacts')->get();
     }
     if ($request->input(ENTITY_TASK)) {
         $data['tasks'] = Task::scope()->with('user', 'client.contacts')->get();
     }
     if ($request->input(ENTITY_INVOICE)) {
         $data['invoices'] = Invoice::scope()->with('user', 'client.contacts', 'invoice_status')->where('is_quote', '=', false)->where('is_recurring', '=', false)->get();
         $data['quotes'] = Invoice::scope()->with('user', 'client.contacts', 'invoice_status')->where('is_quote', '=', true)->where('is_recurring', '=', false)->get();
     }
     if ($request->input(ENTITY_PAYMENT)) {
         $data['payments'] = Payment::scope()->with('user', 'client.contacts', 'payment_type', 'invoice', 'account_gateway.gateway')->get();
     }
     return $data;
 }
 public function save($publicId, $data, $entityType)
 {
     if ($publicId) {
         $invoice = Invoice::scope($publicId)->firstOrFail();
     } else {
         $invoice = Invoice::createNew();
         if ($entityType == ENTITY_QUOTE) {
             $invoice->is_quote = true;
         }
     }
     $account = \Auth::user()->account;
     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_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->invoice_number = trim($data['invoice_number']);
     }
     $invoice->discount = round(Utils::parseFloat($data['discount']), 2);
     $invoice->is_amount_discount = $data['is_amount_discount'] ? true : false;
     $invoice->partial = round(Utils::parseFloat($data['partial']), 2);
     $invoice->invoice_date = isset($data['invoice_date_sql']) ? $data['invoice_date_sql'] : Utils::toSqlDate($data['invoice_date']);
     $invoice->has_tasks = isset($data['has_tasks']) ? $data['has_tasks'] : false;
     if (!$publicId) {
         $invoice->client_id = $data['client_id'];
         $invoice->is_recurring = $data['is_recurring'] && !Utils::isDemo() ? true : false;
     }
     if ($invoice->is_recurring) {
         $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->due_date = null;
     } else {
         $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;
     }
     $invoice->terms = trim($data['terms']) ? trim($data['terms']) : (!$publicId && $account->invoice_terms ? $account->invoice_terms : '');
     $invoice->invoice_footer = trim($data['invoice_footer']) ? trim($data['invoice_footer']) : (!$publicId && $account->invoice_footer ? $account->invoice_footer : '');
     $invoice->public_notes = trim($data['public_notes']);
     // process date variables
     $invoice->terms = Utils::processVariables($invoice->terms);
     $invoice->invoice_footer = Utils::processVariables($invoice->invoice_footer);
     $invoice->public_notes = Utils::processVariables($invoice->public_notes);
     $invoice->po_number = trim($data['po_number']);
     $invoice->invoice_design_id = $data['invoice_design_id'];
     if (isset($data['tax_name']) && isset($data['tax_rate']) && $data['tax_name']) {
         $invoice->tax_rate = Utils::parseFloat($data['tax_rate']);
         $invoice->tax_name = trim($data['tax_name']);
     } else {
         $invoice->tax_rate = 0;
         $invoice->tax_name = '';
     }
     $total = 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);
         $invoiceItemTaxRate = 0;
         if (isset($item['tax_rate']) && Utils::parseFloat($item['tax_rate']) > 0) {
             $invoiceItemTaxRate = Utils::parseFloat($item['tax_rate']);
         }
         $lineTotal = $invoiceItemCost * $invoiceItemQty;
         $total += round($lineTotal + $lineTotal * $invoiceItemTaxRate / 100, 2);
     }
     if ($invoice->discount > 0) {
         if ($invoice->is_amount_discount) {
             $total -= $invoice->discount;
         } else {
             $total *= (100 - $invoice->discount) / 100;
         }
     }
     $invoice->custom_value1 = round($data['custom_value1'], 2);
     $invoice->custom_value2 = round($data['custom_value2'], 2);
     $invoice->custom_taxes1 = $data['custom_taxes1'] ? true : false;
     $invoice->custom_taxes2 = $data['custom_taxes2'] ? true : false;
     // 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;
     }
     $total += $total * $invoice->tax_rate / 100;
     $total = round($total, 2);
     // 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();
     }
     foreach ($data['invoice_items'] as $item) {
         $item = (array) $item;
         if (!$item['cost'] && !$item['product_key'] && !$item['notes']) {
             continue;
         }
         if (isset($item['task_public_id']) && $item['task_public_id']) {
             $task = Task::scope($item['task_public_id'])->where('invoice_id', '=', null)->firstOrFail();
             $task->invoice_id = $invoice->id;
             $task->client_id = $invoice->client_id;
             $task->save();
         } else {
             if ($item['product_key'] && !$invoice->has_tasks) {
                 $product = Product::findProductByKey(trim($item['product_key']));
                 if (!$product) {
                     $product = Product::createNew();
                     $product->product_key = trim($item['product_key']);
                 }
                 if (\Auth::user()->account->update_products) {
                     $product->notes = $item['notes'];
                     $product->cost = $item['cost'];
                 }
                 $product->save();
             }
         }
         $invoiceItem = InvoiceItem::createNew();
         $invoiceItem->product_id = isset($product) ? $product->id : null;
         $invoiceItem->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']);
         $invoiceItem->tax_rate = 0;
         if (isset($item['tax_rate']) && isset($item['tax_name']) && $item['tax_name']) {
             $invoiceItem['tax_rate'] = Utils::parseFloat($item['tax_rate']);
             $invoiceItem['tax_name'] = trim($item['tax_name']);
         }
         $invoice->invoice_items()->save($invoiceItem);
     }
     return $invoice;
 }
 /**
  * @return \Illuminate\Http\RedirectResponse
  */
 public function bulk()
 {
     $action = Input::get('action');
     $ids = Input::get('public_id') ?: (Input::get('id') ?: Input::get('ids'));
     if ($action == 'stop') {
         $this->taskRepo->save($ids, ['action' => $action]);
         Session::flash('message', trans('texts.stopped_task'));
         return Redirect::to('tasks');
     } else {
         if ($action == 'invoice' || $action == 'add_to_invoice') {
             $tasks = Task::scope($ids)->with('client')->get();
             $clientPublicId = false;
             $data = [];
             foreach ($tasks as $task) {
                 if ($task->client) {
                     if (!$clientPublicId) {
                         $clientPublicId = $task->client->public_id;
                     } else {
                         if ($clientPublicId != $task->client->public_id) {
                             Session::flash('error', trans('texts.task_error_multiple_clients'));
                             return Redirect::to('tasks');
                         }
                     }
                 }
                 if ($task->is_running) {
                     Session::flash('error', trans('texts.task_error_running'));
                     return Redirect::to('tasks');
                 } else {
                     if ($task->invoice_id) {
                         Session::flash('error', trans('texts.task_error_invoiced'));
                         return Redirect::to('tasks');
                     }
                 }
                 $account = Auth::user()->account;
                 $data[] = ['publicId' => $task->public_id, 'description' => $task->description . "\n\n" . $task->present()->times($account), 'duration' => $task->getHours()];
             }
             if ($action == 'invoice') {
                 return Redirect::to("invoices/create/{$clientPublicId}")->with('tasks', $data);
             } else {
                 $invoiceId = Input::get('invoice_id');
                 return Redirect::to("invoices/{$invoiceId}/edit")->with('tasks', $data);
             }
         } else {
             $count = $this->taskService->bulk($ids, $action);
             $message = Utils::pluralize($action . 'd_task', $count);
             Session::flash('message', $message);
             return $this->returnBulk($this->entityType, $action, $ids);
         }
     }
 }
 public function save($data)
 {
     $account = \Auth::user()->account;
     $publicId = isset($data['public_id']) ? $data['public_id'] : false;
     $isNew = !$publicId || $publicId == '-1';
     if ($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']);
         if (isset($data['has_tasks']) && filter_var($data['has_tasks'], FILTER_VALIDATE_BOOLEAN)) {
             $invoice->has_tasks = true;
         }
     } else {
         $invoice = Invoice::scope($publicId)->firstOrFail();
     }
     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);
     }
     $invoice->invoice_date = isset($data['invoice_date_sql']) ? $data['invoice_date_sql'] : Utils::toSqlDate($data['invoice_date']);
     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->due_date = null;
         $invoice->auto_bill = isset($data['auto_bill']) && $data['auto_bill'] ? true : false;
     } 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;
     }
     $invoice->terms = trim($data['terms']) ? trim($data['terms']) : (!$publicId && $account->invoice_terms ? $account->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 = trim($data['public_notes']);
     // process date variables
     $invoice->terms = Utils::processVariables($invoice->terms);
     $invoice->invoice_footer = Utils::processVariables($invoice->invoice_footer);
     $invoice->public_notes = Utils::processVariables($invoice->public_notes);
     $invoice->po_number = trim($data['po_number']);
     $invoice->invoice_design_id = isset($data['invoice_design_id']) ? $data['invoice_design_id'] : $account->invoice_design_id;
     if (isset($data['tax_name']) && isset($data['tax_rate']) && $data['tax_name']) {
         $invoice->tax_rate = Utils::parseFloat($data['tax_rate']);
         $invoice->tax_name = trim($data['tax_name']);
     } else {
         $invoice->tax_rate = 0;
         $invoice->tax_name = '';
     }
     $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;
         if (isset($item['tax_rate']) && Utils::parseFloat($item['tax_rate']) > 0) {
             $invoiceItemCost = round(Utils::parseFloat($item['cost']), 2);
             $invoiceItemQty = round(Utils::parseFloat($item['qty']), 2);
             $invoiceItemTaxRate = Utils::parseFloat($item['tax_rate']);
             $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);
                 }
             }
             $itemTax += round($lineTotal * $invoiceItemTaxRate / 100, 2);
         }
     }
     if ($invoice->discount > 0) {
         if ($invoice->is_amount_discount) {
             $total -= $invoice->discount;
         } else {
             $total *= (100 - $invoice->discount) / 100;
         }
     }
     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;
     }
     $total += $total * $invoice->tax_rate / 100;
     $total = round($total, 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();
     }
     foreach ($data['invoice_items'] as $item) {
         $item = (array) $item;
         if (!$item['cost'] && !$item['product_key'] && !$item['notes']) {
             continue;
         }
         if (isset($item['task_public_id']) && $item['task_public_id']) {
             $task = Task::scope($item['task_public_id'])->where('invoice_id', '=', null)->firstOrFail();
             $task->invoice_id = $invoice->id;
             $task->client_id = $invoice->client_id;
             $task->save();
         } else {
             if (isset($item['product_key']) && $item['product_key'] && !$invoice->has_tasks) {
                 $product = Product::findProductByKey(trim($item['product_key']));
                 if (\Auth::user()->account->update_products) {
                     if (!$product) {
                         $product = Product::createNew();
                         $product->product_key = trim($item['product_key']);
                     }
                     $product->notes = $item['notes'];
                     $product->cost = $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']);
         $invoiceItem->tax_rate = 0;
         if (isset($item['tax_rate']) && isset($item['tax_name']) && $item['tax_name']) {
             $invoiceItem['tax_rate'] = Utils::parseFloat($item['tax_rate']);
             $invoiceItem['tax_name'] = trim($item['tax_name']);
         }
         $invoice->invoice_items()->save($invoiceItem);
     }
     return $invoice;
 }
Example #11
0
 public function bulk()
 {
     $action = Input::get('action');
     $ids = Input::get('id') ? Input::get('id') : Input::get('ids');
     if ($action == 'stop') {
         $this->taskRepo->save($ids, ['action' => $action]);
         Session::flash('message', trans('texts.stopped_task'));
         return Redirect::to('tasks');
     } else {
         if ($action == 'invoice' || $action == 'add_to_invoice') {
             $tasks = Task::scope($ids)->with('client')->get();
             $clientPublicId = false;
             $data = [];
             foreach ($tasks as $task) {
                 if ($task->client) {
                     if (!$clientPublicId) {
                         $clientPublicId = $task->client->public_id;
                     } else {
                         if ($clientPublicId != $task->client->public_id) {
                             Session::flash('error', trans('texts.task_error_multiple_clients'));
                             return Redirect::to('tasks');
                         }
                     }
                 }
                 if ($task->is_running) {
                     Session::flash('error', trans('texts.task_error_running'));
                     return Redirect::to('tasks');
                 } else {
                     if ($task->invoice_id) {
                         Session::flash('error', trans('texts.task_error_invoiced'));
                         return Redirect::to('tasks');
                     }
                 }
                 $data[] = ['publicId' => $task->public_id, 'description' => $task->description, 'startTime' => $task->getStartTime(), 'duration' => $task->getHours()];
             }
             if ($action == 'invoice') {
                 return Redirect::to("invoices/create/{$clientPublicId}")->with('tasks', $data);
             } else {
                 $invoiceId = Input::get('invoice_id');
                 return Redirect::to("invoices/{$invoiceId}/edit")->with('tasks', $data);
             }
         } else {
             $count = $this->taskRepo->bulk($ids, $action);
             $message = Utils::pluralize($action . 'd_task', $count);
             Session::flash('message', $message);
             if ($action == 'restore' && $count == 1) {
                 return Redirect::to('tasks/' . $ids[0] . '/edit');
             } else {
                 return Redirect::to('tasks');
             }
         }
     }
 }
 /**
  * @param $request
  *
  * @return array
  */
 private function getData($request)
 {
     $account = Auth::user()->account;
     $data = ['account' => $account, 'title' => 'Invoice Ninja v' . NINJA_VERSION . ' - ' . $account->formatDateTime($account->getDateTime()), 'multiUser' => $account->users->count() > 1];
     if ($request->input('include') === 'all' || $request->input('clients')) {
         $data['clients'] = Client::scope()->with('user', 'contacts', 'country')->withArchived()->get();
     }
     if ($request->input('include') === 'all' || $request->input('contacts')) {
         $data['contacts'] = Contact::scope()->with('user', 'client.contacts')->withTrashed()->get();
     }
     if ($request->input('include') === 'all' || $request->input('credits')) {
         $data['credits'] = Credit::scope()->with('user', 'client.contacts')->get();
     }
     if ($request->input('include') === 'all' || $request->input('tasks')) {
         $data['tasks'] = Task::scope()->with('user', 'client.contacts')->withArchived()->get();
     }
     if ($request->input('include') === 'all' || $request->input('invoices')) {
         $data['invoices'] = Invoice::scope()->invoiceType(INVOICE_TYPE_STANDARD)->with('user', 'client.contacts', 'invoice_status')->withArchived()->where('is_recurring', '=', false)->get();
     }
     if ($request->input('include') === 'all' || $request->input('quotes')) {
         $data['quotes'] = Invoice::scope()->invoiceType(INVOICE_TYPE_QUOTE)->with('user', 'client.contacts', 'invoice_status')->withArchived()->where('is_recurring', '=', false)->get();
     }
     if ($request->input('include') === 'all' || $request->input('recurring')) {
         $data['recurringInvoices'] = Invoice::scope()->invoiceType(INVOICE_TYPE_STANDARD)->with('user', 'client.contacts', 'invoice_status', 'frequency')->withArchived()->where('is_recurring', '=', true)->get();
     }
     if ($request->input('include') === 'all' || $request->input('payments')) {
         $data['payments'] = Payment::scope()->withArchived()->with('user', 'client.contacts', 'payment_type', 'invoice', 'account_gateway.gateway')->get();
     }
     if ($request->input('include') === 'all' || $request->input('vendors')) {
         $data['vendors'] = Vendor::scope()->with('user', 'vendor_contacts', 'country')->withArchived()->get();
     }
     if ($request->input('include') === 'all' || $request->input('vendor_contacts')) {
         $data['vendor_contacts'] = VendorContact::scope()->with('user', 'vendor.vendor_contacts')->withTrashed()->get();
     }
     return $data;
 }
 /**
  * Display the specified resource.
  *
  * @param  int      $id
  * @return Response
  */
 public function show(ClientRequest $request)
 {
     $client = $request->entity();
     $user = Auth::user();
     Utils::trackViewed($client->getDisplayName(), ENTITY_CLIENT);
     $actionLinks = [];
     if ($user->can('create', ENTITY_TASK)) {
         $actionLinks[] = ['label' => trans('texts.new_task'), 'url' => URL::to('/tasks/create/' . $client->public_id)];
     }
     if (Utils::hasFeature(FEATURE_QUOTES) && $user->can('create', ENTITY_INVOICE)) {
         $actionLinks[] = ['label' => trans('texts.new_quote'), 'url' => URL::to('/quotes/create/' . $client->public_id)];
     }
     if (!empty($actionLinks)) {
         $actionLinks[] = \DropdownButton::DIVIDER;
     }
     if ($user->can('create', ENTITY_PAYMENT)) {
         $actionLinks[] = ['label' => trans('texts.enter_payment'), 'url' => URL::to('/payments/create/' . $client->public_id)];
     }
     if ($user->can('create', ENTITY_CREDIT)) {
         $actionLinks[] = ['label' => trans('texts.enter_credit'), 'url' => URL::to('/credits/create/' . $client->public_id)];
     }
     if ($user->can('create', ENTITY_EXPENSE)) {
         $actionLinks[] = ['label' => trans('texts.enter_expense'), 'url' => URL::to('/expenses/create/0/' . $client->public_id)];
     }
     $data = array('actionLinks' => $actionLinks, 'showBreadcrumbs' => false, 'client' => $client, 'credit' => $client->getTotalCredit(), 'title' => trans('texts.view_client'), 'hasRecurringInvoices' => Invoice::scope()->where('is_recurring', '=', true)->whereClientId($client->id)->count() > 0, 'hasQuotes' => Invoice::scope()->where('is_quote', '=', true)->whereClientId($client->id)->count() > 0, 'hasTasks' => Task::scope()->whereClientId($client->id)->count() > 0, 'gatewayLink' => $client->getGatewayLink());
     return View::make('clients.show', $data);
 }
 public function tasks($accountId, $userId, $viewAll)
 {
     return Task::scope()->withArchived()->whereIsRunning(true)->get();
 }
 /**
  * Display the specified resource.
  *
  * @param  int      $id
  * @return Response
  */
 public function show($publicId)
 {
     $client = Client::withTrashed()->scope($publicId)->with('contacts', 'size', 'industry')->firstOrFail();
     if (!$this->checkViewPermission($client, $response)) {
         return $response;
     }
     Utils::trackViewed($client->getDisplayName(), ENTITY_CLIENT);
     $actionLinks = [];
     if (Task::canCreate()) {
         $actionLinks[] = ['label' => trans('texts.new_task'), 'url' => '/tasks/create/' . $client->public_id];
     }
     if (Utils::isPro() && Invoice::canCreate()) {
         $actionLinks[] = ['label' => trans('texts.new_quote'), 'url' => '/quotes/create/' . $client->public_id];
     }
     if (!empty($actionLinks)) {
         $actionLinks[] = \DropdownButton::DIVIDER;
     }
     if (Payment::canCreate()) {
         $actionLinks[] = ['label' => trans('texts.enter_payment'), 'url' => '/payments/create/' . $client->public_id];
     }
     if (Credit::canCreate()) {
         $actionLinks[] = ['label' => trans('texts.enter_credit'), 'url' => '/credits/create/' . $client->public_id];
     }
     if (Expense::canCreate()) {
         $actionLinks[] = ['label' => trans('texts.enter_expense'), 'url' => '/expenses/create/0/' . $client->public_id];
     }
     $data = array('actionLinks' => $actionLinks, 'showBreadcrumbs' => false, 'client' => $client, 'credit' => $client->getTotalCredit(), 'title' => trans('texts.view_client'), 'hasRecurringInvoices' => Invoice::scope()->where('is_recurring', '=', true)->whereClientId($client->id)->count() > 0, 'hasQuotes' => Invoice::scope()->where('is_quote', '=', true)->whereClientId($client->id)->count() > 0, 'hasTasks' => Task::scope()->whereClientId($client->id)->count() > 0, 'gatewayLink' => $client->getGatewayLink());
     return View::make('clients.show', $data);
 }
 /**
  * @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;
 }
 private function generateTaskReport($startDate, $endDate, $isExport)
 {
     $columns = ['client', 'date', 'description', 'duration'];
     $displayData = [];
     $tasks = Task::scope()->with('client.contacts')->withArchived()->dateRange($startDate, $endDate);
     foreach ($tasks->get() as $task) {
         $displayData[] = [$task->client ? $isExport ? $task->client->getDisplayName() : $task->client->present()->link : trans('texts.unassigned'), link_to($task->present()->url, $task->getStartTime()), $task->present()->description, Utils::formatTime($task->getDuration())];
     }
     return ['columns' => $columns, 'displayData' => $displayData, 'reportTotals' => []];
 }