1
0
mirror of https://github.com/invoiceninja/invoiceninja.git synced 2024-11-14 15:13:29 +01:00
invoiceninja/app/Http/Controllers/ReportController.php

546 lines
22 KiB
PHP
Raw Normal View History

2015-03-17 02:30:56 +01:00
<?php namespace App\Http\Controllers;
use Auth;
use Config;
2015-03-17 02:30:56 +01:00
use Input;
2015-04-01 21:57:02 +02:00
use Utils;
use DB;
use DateInterval;
use DatePeriod;
use Session;
use View;
use App\Models\Account;
2016-02-23 22:32:39 +01:00
use App\Models\Client;
use App\Models\Payment;
2016-02-24 22:54:43 +01:00
use App\Models\Expense;
2015-04-01 21:57:02 +02:00
class ReportController extends BaseController
2015-03-16 22:45:25 +01:00
{
public function d3()
{
$message = '';
2015-11-10 23:07:05 +01:00
$fileName = storage_path().'/dataviz_sample.txt';
2015-03-16 22:45:25 +01:00
if (Auth::user()->account->isPro()) {
2015-08-11 16:38:36 +02:00
$account = Account::where('id', '=', Auth::user()->account->id)
->with(['clients.invoices.invoice_items', 'clients.contacts'])
->first();
2015-03-16 22:45:25 +01:00
$account = $account->hideFieldsForViz();
$clients = $account->clients->toJson();
2015-05-19 21:14:00 +02:00
} elseif (file_exists($fileName)) {
$clients = file_get_contents($fileName);
2015-03-16 22:45:25 +01:00
$message = trans('texts.sample_data');
} else {
$clients = '[]';
}
$data = [
'clients' => $clients,
'message' => $message,
];
return View::make('reports.d3', $data);
}
2015-04-30 19:54:19 +02:00
public function showReports()
2015-03-16 22:45:25 +01:00
{
2015-04-30 19:54:19 +02:00
$action = Input::get('action');
2015-03-16 22:45:25 +01:00
if (Input::all()) {
$groupBy = Input::get('group_by');
$chartType = Input::get('chart_type');
2015-04-30 19:54:19 +02:00
$reportType = Input::get('report_type');
2016-02-24 21:58:42 +01:00
$dateField = Input::get('date_field');
2015-03-16 22:45:25 +01:00
$startDate = Utils::toSqlDate(Input::get('start_date'), false);
$endDate = Utils::toSqlDate(Input::get('end_date'), false);
2015-04-30 19:54:19 +02:00
$enableReport = Input::get('enable_report') ? true : false;
$enableChart = Input::get('enable_chart') ? true : false;
2015-03-16 22:45:25 +01:00
} else {
$groupBy = 'MONTH';
$chartType = 'Bar';
2015-11-10 23:07:05 +01:00
$reportType = ENTITY_INVOICE;
2016-02-24 21:58:42 +01:00
$dateField = FILTER_INVOICE_DATE;
2015-03-16 22:45:25 +01:00
$startDate = Utils::today(false)->modify('-3 month');
$endDate = Utils::today(false);
2015-04-30 19:54:19 +02:00
$enableReport = true;
$enableChart = true;
2015-03-16 22:45:25 +01:00
}
$dateTypes = [
'DAYOFYEAR' => 'Daily',
'WEEK' => 'Weekly',
'MONTH' => 'Monthly',
];
$chartTypes = [
'Bar' => 'Bar',
'Line' => 'Line',
];
2015-04-30 19:54:19 +02:00
$reportTypes = [
2015-11-10 23:07:05 +01:00
ENTITY_CLIENT => trans('texts.client'),
ENTITY_INVOICE => trans('texts.invoice'),
ENTITY_PAYMENT => trans('texts.payment'),
2016-02-24 22:54:43 +01:00
ENTITY_EXPENSE => trans('texts.expenses'),
2016-02-24 22:54:56 +01:00
ENTITY_TAX_RATE => trans('texts.taxes'),
2015-04-30 19:54:19 +02:00
];
2015-03-16 22:45:25 +01:00
$params = [
'dateTypes' => $dateTypes,
'chartTypes' => $chartTypes,
'chartType' => $chartType,
'startDate' => $startDate->format(Session::get(SESSION_DATE_FORMAT)),
2015-05-05 11:48:23 +02:00
'endDate' => $endDate->format(Session::get(SESSION_DATE_FORMAT)),
2015-03-16 22:45:25 +01:00
'groupBy' => $groupBy,
2015-04-30 19:54:19 +02:00
'reportTypes' => $reportTypes,
'reportType' => $reportType,
'enableChart' => $enableChart,
'enableReport' => $enableReport,
2015-07-07 22:08:16 +02:00
'title' => trans('texts.charts_and_reports'),
2015-03-16 22:45:25 +01:00
];
2015-11-10 23:07:05 +01:00
if (Auth::user()->account->isPro()) {
if ($enableReport) {
2016-02-23 22:32:39 +01:00
$isExport = $action == 'export';
2016-02-24 21:58:42 +01:00
$params = array_merge($params, self::generateReport($reportType, $startDate, $endDate, $dateField, $isExport));
2015-11-10 23:07:05 +01:00
2016-02-23 22:32:39 +01:00
if ($isExport) {
self::export($params['displayData'], $params['columns'], $params['reportTotals']);
2015-11-10 23:07:05 +01:00
}
}
if ($enableChart) {
$params = array_merge($params, self::generateChart($groupBy, $startDate, $endDate));
}
2015-11-15 10:50:21 +01:00
} else {
$params['columns'] = [];
$params['displayData'] = [];
2016-02-27 22:00:27 +01:00
$params['reportTotals'] = [];
2015-11-15 10:50:21 +01:00
$params['labels'] = [];
$params['datasets'] = [];
$params['scaleStepWidth'] = 100;
2015-11-10 23:07:05 +01:00
}
2015-04-30 19:54:19 +02:00
return View::make('reports.chart_builder', $params);
}
2015-11-10 23:07:05 +01:00
private function generateChart($groupBy, $startDate, $endDate)
{
$width = 10;
$datasets = [];
$labels = [];
$maxTotals = 0;
foreach ([ENTITY_INVOICE, ENTITY_PAYMENT, ENTITY_CREDIT] as $entityType) {
// SQLite does not support the YEAR(), MONTH(), WEEK() and similar functions.
// Let's see if SQLite is being used.
if (Config::get('database.connections.'.Config::get('database.default').'.driver') == 'sqlite') {
// Replace the unsupported function with it's date format counterpart
switch ($groupBy) {
case 'MONTH':
$dateFormat = '%m'; // returns 01-12
break;
case 'WEEK':
$dateFormat = '%W'; // returns 00-53
break;
case 'DAYOFYEAR':
$dateFormat = '%j'; // returns 001-366
break;
default:
$dateFormat = '%m'; // MONTH by default
break;
}
// Concatenate the year and the chosen timeframe (Month, Week or Day)
$timeframe = 'strftime("%Y", '.$entityType.'_date) || strftime("'.$dateFormat.'", '.$entityType.'_date)';
} else {
// Supported by Laravel's other DBMS drivers (MySQL, MSSQL and PostgreSQL)
$timeframe = 'concat(YEAR('.$entityType.'_date), '.$groupBy.'('.$entityType.'_date))';
}
$records = DB::table($entityType.'s')
2016-03-31 16:27:18 +02:00
->select(DB::raw('sum('.$entityType.'s.amount) as total, '.$timeframe.' as '.$groupBy))
->join('clients', 'clients.id', '=', $entityType.'s.client_id')
->where('clients.is_deleted', '=', false)
->where($entityType.'s.account_id', '=', Auth::user()->account_id)
2015-11-10 23:07:05 +01:00
->where($entityType.'s.is_deleted', '=', false)
->where($entityType.'s.'.$entityType.'_date', '>=', $startDate->format('Y-m-d'))
->where($entityType.'s.'.$entityType.'_date', '<=', $endDate->format('Y-m-d'))
->groupBy($groupBy);
if ($entityType == ENTITY_INVOICE) {
$records->where('is_quote', '=', false)
->where('is_recurring', '=', false);
2016-03-31 16:27:18 +02:00
} elseif ($entityType == ENTITY_PAYMENT) {
$records->join('invoices', 'invoices.id', '=', 'payments.invoice_id')
->where('invoices.is_deleted', '=', false);
2015-11-10 23:07:05 +01:00
}
$totals = $records->lists('total');
$dates = $records->lists($groupBy);
$data = array_combine($dates, $totals);
$padding = $groupBy == 'DAYOFYEAR' ? 'day' : ($groupBy == 'WEEK' ? 'week' : 'month');
$endDate->modify('+1 '.$padding);
$interval = new DateInterval('P1'.substr($groupBy, 0, 1));
$period = new DatePeriod($startDate, $interval, $endDate);
$endDate->modify('-1 '.$padding);
$totals = [];
foreach ($period as $d) {
$dateFormat = $groupBy == 'DAYOFYEAR' ? 'z' : ($groupBy == 'WEEK' ? 'W' : 'n');
// MySQL returns 1-366 for DAYOFYEAR, whereas PHP returns 0-365
$date = $groupBy == 'DAYOFYEAR' ? $d->format('Y').($d->format($dateFormat) + 1) : $d->format('Y'.$dateFormat);
$totals[] = isset($data[$date]) ? $data[$date] : 0;
if ($entityType == ENTITY_INVOICE) {
$labelFormat = $groupBy == 'DAYOFYEAR' ? 'j' : ($groupBy == 'WEEK' ? 'W' : 'F');
2015-11-15 07:39:25 +01:00
$label = $d->format($labelFormat);
2015-11-10 23:07:05 +01:00
$labels[] = $label;
}
}
$max = max($totals);
if ($max > 0) {
$datasets[] = [
'totals' => $totals,
'colors' => $entityType == ENTITY_INVOICE ? '78,205,196' : ($entityType == ENTITY_CREDIT ? '199,244,100' : '255,107,107'),
];
$maxTotals = max($max, $maxTotals);
}
}
$width = (ceil($maxTotals / 100) * 100) / 10;
$width = max($width, 10);
return [
'datasets' => $datasets,
'scaleStepWidth' => $width,
'labels' => $labels,
];
}
2016-02-24 21:58:42 +01:00
private function generateReport($reportType, $startDate, $endDate, $dateField, $isExport)
2015-11-10 23:07:05 +01:00
{
if ($reportType == ENTITY_CLIENT) {
2016-02-23 22:32:39 +01:00
return $this->generateClientReport($startDate, $endDate, $isExport);
2015-11-10 23:07:05 +01:00
} elseif ($reportType == ENTITY_INVOICE) {
2016-02-23 22:32:39 +01:00
return $this->generateInvoiceReport($startDate, $endDate, $isExport);
} elseif ($reportType == ENTITY_PAYMENT) {
return $this->generatePaymentReport($startDate, $endDate, $isExport);
} elseif ($reportType == ENTITY_TAX_RATE) {
2016-02-24 21:58:42 +01:00
return $this->generateTaxRateReport($startDate, $endDate, $dateField, $isExport);
2016-02-24 22:54:43 +01:00
} elseif ($reportType == ENTITY_EXPENSE) {
return $this->generateExpenseReport($startDate, $endDate, $isExport);
2015-11-10 23:07:05 +01:00
}
2016-02-23 22:32:39 +01:00
}
2015-11-10 23:07:05 +01:00
2016-02-24 21:58:42 +01:00
private function generateTaxRateReport($startDate, $endDate, $dateField, $isExport)
2016-02-23 22:32:39 +01:00
{
$columns = ['tax_name', 'tax_rate', 'amount', 'paid'];
2015-11-10 23:07:05 +01:00
2016-02-23 22:32:39 +01:00
$account = Auth::user()->account;
$displayData = [];
$reportTotals = [];
$clients = Client::scope()
2016-02-24 21:58:42 +01:00
->withArchived()
2016-02-23 22:32:39 +01:00
->with('contacts')
2016-02-24 21:58:42 +01:00
->with(['invoices' => function($query) use ($startDate, $endDate, $dateField) {
$query->withArchived();
if ($dateField == FILTER_PAYMENT_DATE) {
$query->where('invoice_date', '>=', $startDate)
->where('invoice_date', '<=', $endDate)
->whereHas('payments', function($query) use ($startDate, $endDate) {
$query->where('payment_date', '>=', $startDate)
->where('payment_date', '<=', $endDate)
->withArchived();
})
->with(['payments' => function($query) use ($startDate, $endDate) {
$query->where('payment_date', '>=', $startDate)
->where('payment_date', '<=', $endDate)
->withArchived()
->with('payment_type', 'account_gateway.gateway');
}, 'invoice_items']);
}
2016-02-23 22:32:39 +01:00
}]);
foreach ($clients->get() as $client) {
$currencyId = $client->currency_id ?: Auth::user()->account->getCurrencyId();
$amount = 0;
$paid = 0;
$taxTotals = [];
foreach ($client->invoices as $invoice) {
2016-02-24 21:58:42 +01:00
foreach ($invoice->getTaxes(true) as $key => $tax) {
2016-02-23 22:32:39 +01:00
if ( ! isset($taxTotals[$currencyId])) {
$taxTotals[$currencyId] = [];
}
if (isset($taxTotals[$currencyId][$key])) {
$taxTotals[$currencyId][$key]['amount'] += $tax['amount'];
$taxTotals[$currencyId][$key]['paid'] += $tax['paid'];
} else {
$taxTotals[$currencyId][$key] = $tax;
}
}
$amount += $invoice->amount;
$paid += $invoice->getAmountPaid();
}
foreach ($taxTotals as $currencyId => $taxes) {
foreach ($taxes as $tax) {
$displayData[] = [
$tax['name'],
2016-02-25 09:32:31 +01:00
$tax['rate'] . '%',
2016-02-23 22:32:39 +01:00
$account->formatMoney($tax['amount'], $client),
$account->formatMoney($tax['paid'], $client)
];
}
2016-02-24 22:54:43 +01:00
$reportTotals = $this->addToTotals($reportTotals, $client->currency_id, 'amount', $tax['amount']);
$reportTotals = $this->addToTotals($reportTotals, $client->currency_id, 'paid', $tax['paid']);
2015-11-10 23:07:05 +01:00
}
}
2016-02-23 22:32:39 +01:00
return [
'columns' => $columns,
'displayData' => $displayData,
'reportTotals' => $reportTotals,
];
}
private function generatePaymentReport($startDate, $endDate, $isExport)
{
$columns = ['client', 'invoice_number', 'invoice_date', 'amount', 'payment_date', 'paid', 'method'];
2015-11-10 23:07:05 +01:00
2016-02-23 22:32:39 +01:00
$account = Auth::user()->account;
2015-11-15 07:39:25 +01:00
$displayData = [];
2016-02-23 22:32:39 +01:00
$reportTotals = [];
$payments = Payment::scope()
->withTrashed()
->where('is_deleted', '=', false)
->whereHas('client', function($query) {
$query->where('is_deleted', '=', false);
})
->whereHas('invoice', function($query) {
$query->where('is_deleted', '=', false);
})
->with('client.contacts', 'invoice', 'payment_type', 'account_gateway.gateway')
->where('payment_date', '>=', $startDate)
->where('payment_date', '<=', $endDate);
foreach ($payments->get() as $payment) {
$invoice = $payment->invoice;
$client = $payment->client;
$displayData[] = [
$isExport ? $client->getDisplayName() : $client->present()->link,
$isExport ? $invoice->invoice_number : $invoice->present()->link,
$invoice->present()->invoice_date,
$account->formatMoney($invoice->amount, $client),
$payment->present()->payment_date,
$account->formatMoney($payment->amount, $client),
$payment->present()->method,
];
2015-11-15 07:39:25 +01:00
2016-02-24 22:54:43 +01:00
$reportTotals = $this->addToTotals($reportTotals, $client->currency_id, 'amount', $invoice->amount);
$reportTotals = $this->addToTotals($reportTotals, $client->currency_id, 'paid', $payment->amount);
2016-02-23 22:32:39 +01:00
}
2016-02-24 21:58:42 +01:00
2016-02-23 22:32:39 +01:00
return [
'columns' => $columns,
'displayData' => $displayData,
'reportTotals' => $reportTotals,
];
}
2015-11-10 23:07:05 +01:00
2016-02-23 22:32:39 +01:00
private function generateInvoiceReport($startDate, $endDate, $isExport)
{
2016-03-21 15:06:50 +01:00
$columns = ['client', 'invoice_number', 'invoice_date', 'amount', 'payment_date', 'paid', 'method'];
2016-02-23 22:32:39 +01:00
$account = Auth::user()->account;
$displayData = [];
$reportTotals = [];
$clients = Client::scope()
->withTrashed()
->with('contacts')
->where('is_deleted', '=', false)
->with(['invoices' => function($query) use ($startDate, $endDate) {
$query->where('invoice_date', '>=', $startDate)
->where('invoice_date', '<=', $endDate)
->where('is_deleted', '=', false)
2016-02-25 22:33:48 +01:00
->where('is_quote', '=', false)
->where('is_recurring', '=', false)
2016-02-23 22:32:39 +01:00
->with(['payments' => function($query) {
$query->withTrashed()
->with('payment_type', 'account_gateway.gateway')
->where('is_deleted', '=', false);
}, 'invoice_items'])
->withTrashed();
}]);
foreach ($clients->get() as $client) {
2016-03-21 15:06:50 +01:00
foreach ($client->invoices as $invoice) {
$payments = count($invoice->payments) ? $invoice->payments : [false];
foreach ($payments as $payment) {
$displayData[] = [
$isExport ? $client->getDisplayName() : $client->present()->link,
$isExport ? $invoice->invoice_number : $invoice->present()->link,
$invoice->present()->invoice_date,
$account->formatMoney($invoice->amount, $client),
$payment ? $payment->present()->payment_date : '',
$payment ? $account->formatMoney($payment->amount, $client) : '',
$payment ? $payment->present()->method : '',
];
if ($payment) {
$reportTotals = $this->addToTotals($reportTotals, $client->currency_id, 'paid', $payment->amount);
}
}
2016-02-23 22:32:39 +01:00
2016-02-24 22:54:43 +01:00
$reportTotals = $this->addToTotals($reportTotals, $client->currency_id, 'amount', $invoice->amount);
$reportTotals = $this->addToTotals($reportTotals, $client->currency_id, 'balance', $invoice->balance);
2015-11-10 23:07:05 +01:00
}
2016-02-23 22:32:39 +01:00
}
return [
'columns' => $columns,
'displayData' => $displayData,
'reportTotals' => $reportTotals,
];
}
2015-11-10 23:07:05 +01:00
2016-02-23 22:32:39 +01:00
private function generateClientReport($startDate, $endDate, $isExport)
{
$columns = ['client', 'amount', 'paid', 'balance'];
2015-11-10 23:07:05 +01:00
2016-02-23 22:32:39 +01:00
$account = Auth::user()->account;
$displayData = [];
$reportTotals = [];
$clients = Client::scope()
2016-02-24 22:54:43 +01:00
->withArchived()
2016-02-23 22:32:39 +01:00
->with('contacts')
->with(['invoices' => function($query) use ($startDate, $endDate) {
$query->where('invoice_date', '>=', $startDate)
->where('invoice_date', '<=', $endDate)
2016-02-25 22:33:48 +01:00
->where('is_quote', '=', false)
->where('is_recurring', '=', false)
2016-02-24 22:54:43 +01:00
->withArchived();
2016-02-23 22:32:39 +01:00
}]);
foreach ($clients->get() as $client) {
$amount = 0;
$paid = 0;
foreach ($client->invoices as $invoice) {
$amount += $invoice->amount;
$paid += $invoice->getAmountPaid();
2015-11-10 23:07:05 +01:00
}
2016-02-23 22:32:39 +01:00
$displayData[] = [
$isExport ? $client->getDisplayName() : $client->present()->link,
$account->formatMoney($amount, $client),
$account->formatMoney($paid, $client),
$account->formatMoney($amount - $paid, $client)
];
2016-02-24 22:54:43 +01:00
$reportTotals = $this->addToTotals($reportTotals, $client->currency_id, 'amount', $amount);
$reportTotals = $this->addToTotals($reportTotals, $client->currency_id, 'paid', $paid);
$reportTotals = $this->addToTotals($reportTotals, $client->currency_id, 'balance', $amount - $paid);
}
return [
'columns' => $columns,
'displayData' => $displayData,
'reportTotals' => $reportTotals,
];
}
private function generateExpenseReport($startDate, $endDate, $isExport)
{
$columns = ['vendor', 'client', 'date', 'expense_amount', 'invoiced_amount'];
$account = Auth::user()->account;
$displayData = [];
$reportTotals = [];
$expenses = Expense::scope()
->withTrashed()
->with('client.contacts', 'vendor')
->where('expense_date', '>=', $startDate)
->where('expense_date', '<=', $endDate);
foreach ($expenses->get() as $expense) {
$amount = $expense->amount;
$invoiced = $expense->present()->invoiced_amount;
$displayData[] = [
$expense->vendor ? ($isExport ? $expense->vendor->name : $expense->vendor->present()->link) : '',
$expense->client ? ($isExport ? $expense->client->getDisplayName() : $expense->client->present()->link) : '',
$expense->present()->expense_date,
Utils::formatMoney($amount, $expense->currency_id),
Utils::formatMoney($invoiced, $expense->invoice_currency_id),
];
$reportTotals = $this->addToTotals($reportTotals, $expense->expense_currency_id, 'amount', $amount);
$reportTotals = $this->addToTotals($reportTotals, $expense->invoice_currency_id, 'amount', 0);
$reportTotals = $this->addToTotals($reportTotals, $expense->invoice_currency_id, 'invoiced', $invoiced);
$reportTotals = $this->addToTotals($reportTotals, $expense->expense_currency_id, 'invoiced', 0);
2015-11-10 23:07:05 +01:00
}
return [
'columns' => $columns,
'displayData' => $displayData,
'reportTotals' => $reportTotals,
];
}
2016-02-24 22:54:43 +01:00
private function addToTotals($data, $currencyId, $field, $value) {
$currencyId = $currencyId ?: Auth::user()->account->getCurrencyId();
2016-02-23 22:32:39 +01:00
if (!isset($data[$currencyId][$field])) {
$data[$currencyId][$field] = 0;
}
$data[$currencyId][$field] += $value;
return $data;
}
private function export($data, $columns, $totals)
2015-04-30 19:54:19 +02:00
{
$output = fopen('php://output', 'w') or Utils::fatalError();
header('Content-Type:application/csv');
header('Content-Disposition:attachment;filename=ninja-report.csv');
2016-02-23 22:32:39 +01:00
Utils::exportData($output, $data, Utils::trans($columns));
fwrite($output, trans('texts.totals'));
foreach ($totals as $currencyId => $fields) {
foreach ($fields as $key => $value) {
fwrite($output, ',' . trans("texts.{$key}"));
}
fwrite($output, "\n");
break;
}
2015-04-30 19:54:19 +02:00
2016-02-23 22:32:39 +01:00
foreach ($totals as $currencyId => $fields) {
$csv = Utils::getFromCache($currencyId, 'currencies')->name . ',';
foreach ($fields as $key => $value) {
$csv .= '"' . Utils::formatMoney($value, $currencyId).'",';
2015-04-30 19:54:19 +02:00
}
2015-11-10 23:07:05 +01:00
fwrite($output, $csv."\n");
2015-04-30 19:54:19 +02:00
}
fclose($output);
exit;
2015-03-16 22:45:25 +01:00
}
}