From 374e34e733272c4ba5a911c249110322ad9c6bb6 Mon Sep 17 00:00:00 2001 From: Hillel Coren Date: Sun, 15 Dec 2013 14:55:50 +0200 Subject: [PATCH] Starting to work on reports --- README.md | 3 +- app/controllers/AccountController.php | 17 +- app/controllers/ClientController.php | 15 +- app/controllers/CreditController.php | 15 +- app/controllers/InvoiceController.php | 38 +- app/controllers/PaymentController.php | 15 +- app/controllers/ReportController.php | 46 + app/controllers/UserController.php | 6 +- ...11_05_180133_confide_setup_users_table.php | 42 +- app/database/seeds/ConstantsSeeder.php | 7 + app/handlers/UserEventHandler.php | 36 + app/libraries/utils.php | 29 +- app/models/Account.php | 11 + app/models/Client.php | 10 + app/models/DateFormat.php | 7 + app/models/DatetimeFormat.php | 7 + app/models/Gateway.php | 2 +- app/routes.php | 16 +- app/start/global.php | 6 + app/views/accounts/details.blade.php | 2 - app/views/accounts/settings.blade.php | 11 +- app/views/clients/edit.blade.php | 1 + app/views/clients/show.blade.php | 1 + app/views/header.blade.php | 2 +- app/views/invoices/deleted.blade.php | 7 + app/views/invoices/edit.blade.php | 77 +- app/views/reports/monthly.blade.php | 39 + public/js/Chart.js | 1426 +++++++++++++++++ public/js/script.js | 62 +- 29 files changed, 1827 insertions(+), 129 deletions(-) create mode 100755 app/controllers/ReportController.php create mode 100755 app/handlers/UserEventHandler.php create mode 100755 app/models/DateFormat.php create mode 100755 app/models/DatetimeFormat.php create mode 100755 app/views/invoices/deleted.blade.php create mode 100755 app/views/reports/monthly.blade.php create mode 100755 public/js/Chart.js diff --git a/README.md b/README.md index 8543564af897..27e2abf1b5d0 100644 --- a/README.md +++ b/README.md @@ -56,4 +56,5 @@ Configure config/database.php and then initialize the database * [webpatser/laravel-countries](https://github.com/webpatser/laravel-countries) - Almost ISO 3166_2, 3166_3, currency, Capital and more for all countries * [briannesbitt/Carbon](https://github.com/briannesbitt/Carbon) - A simple API extension for DateTime with PHP 5.3+ * [thomaspark/bootswatch](https://github.com/thomaspark/bootswatch) - Themes for Bootstrap -* [mozilla/pdf.js)](https://github.com/mozilla/pdf.js) - PDF Reader in JavaScript \ No newline at end of file +* [mozilla/pdf.js)](https://github.com/mozilla/pdf.js) - PDF Reader in JavaScript +* [nnnick/Chart.js](https://github.com/nnnick/Chart.js) - Simple HTML5 Charts using the tag \ No newline at end of file diff --git a/app/controllers/AccountController.php b/app/controllers/AccountController.php index ba3006cc5a0b..a590cce95a9e 100755 --- a/app/controllers/AccountController.php +++ b/app/controllers/AccountController.php @@ -40,7 +40,7 @@ class AccountController extends \BaseController { } Auth::login($user, true); - Session::put('tz', 'US/Eastern'); + Event::fire('user.login'); return Redirect::to('invoices/create'); } @@ -51,9 +51,8 @@ class AccountController extends \BaseController { { $account = Account::with('users')->findOrFail(Auth::user()->account_id); $countries = Country::orderBy('name')->get(); - $timezones = Timezone::orderBy('location')->get(); - return View::make('accounts.details', array('account'=>$account, 'countries'=>$countries, 'timezones'=>$timezones)); + return View::make('accounts.details', array('account'=>$account, 'countries'=>$countries)); } else if ($section == ACCOUNT_SETTINGS) { @@ -71,7 +70,10 @@ class AccountController extends \BaseController { 'account' => $account, 'accountGateway' => $accountGateway, 'config' => json_decode($config), - 'gateways' => Gateway::all() + 'gateways' => Gateway::all(), + 'timezones' => Timezone::orderBy('location')->get(), + 'dateFormats' => DateFormat::all(), + 'datetimeFormats' => DatetimeFormat::all(), ]; foreach ($data['gateways'] as $gateway) @@ -383,6 +385,12 @@ class AccountController extends \BaseController { $account = Account::findOrFail(Auth::user()->account_id); $account->account_gateways()->forceDelete(); + $account->timezone_id = Input::get('timezone_id') ? Input::get('timezone_id') : null; + $account->date_format_id = Input::get('date_format_id') ? Input::get('date_format_id') : null; + $account->datetime_format_id = Input::get('datetime_format_id') ? Input::get('datetime_format_id') : null; + + Event::fire('user.refresh'); + $account->invoice_terms = Input::get('invoice_terms'); $account->save(); @@ -431,7 +439,6 @@ class AccountController extends \BaseController { $account->state = trim(Input::get('state')); $account->postal_code = trim(Input::get('postal_code')); $account->country_id = Input::get('country_id') ? Input::get('country_id') : null; - $account->timezone_id = Input::get('timezone_id') ? Input::get('timezone_id') : null; $account->save(); $user = $account->users()->first(); diff --git a/app/controllers/ClientController.php b/app/controllers/ClientController.php index f3bd68a4019d..4c1909075590 100755 --- a/app/controllers/ClientController.php +++ b/app/controllers/ClientController.php @@ -179,11 +179,12 @@ class ClientController extends \BaseController { $client->address2 = trim(Input::get('address2')); $client->city = trim(Input::get('city')); $client->state = trim(Input::get('state')); - $client->notes = trim(Input::get('notes')); $client->postal_code = trim(Input::get('postal_code')); $client->country_id = Input::get('country_id') ? Input::get('country_id') : null; + $client->notes = trim(Input::get('notes')); $client->client_size_id = Input::get('client_size_id') ? Input::get('client_size_id') : null; $client->client_industry_id = Input::get('client_industry_id') ? Input::get('client_industry_id') : null; + $client->website = trim(Input::get('website')); $client->save(); @@ -238,15 +239,15 @@ class ClientController extends \BaseController { $ids = Input::get('id') ? Input::get('id') : Input::get('ids'); $clients = Client::scope($ids)->get(); - foreach ($clients as $client) { - if ($action == 'archive') { - $client->delete(); - } else if ($action == 'delete') { - $client->forceDelete(); + foreach ($clients as $client) { + if ($action == 'delete') { + $client->is_deleted = true; + $client->save(); } + $client->delete(); } - $message = Utils::pluralize('Successfully '.$action.'d ? client', count($ids)); + $message = Utils::pluralize('Successfully '.$action.'d ? client', count($clients)); Session::flash('message', $message); return Redirect::to('clients'); diff --git a/app/controllers/CreditController.php b/app/controllers/CreditController.php index 1cf908dffa39..9c363b1af0ce 100755 --- a/app/controllers/CreditController.php +++ b/app/controllers/CreditController.php @@ -22,6 +22,7 @@ class CreditController extends \BaseController { ->join('clients', 'clients.id', '=','credits.client_id') ->where('clients.account_id', '=', Auth::user()->account_id) ->where('clients.deleted_at', '=', null) + ->where('credits.deleted_at', '=', null) ->select('credits.public_id', 'clients.name as client_name', 'clients.public_id as client_public_id', 'credits.amount', 'credits.credit_date'); if ($clientPublicId) { @@ -55,7 +56,7 @@ class CreditController extends \BaseController { '; @@ -65,7 +66,7 @@ class CreditController extends \BaseController { } - public function create($clientPublicId) + public function create($clientPublicId = null) { $client = null; if ($clientPublicId) { @@ -144,14 +145,14 @@ class CreditController extends \BaseController { $credits = Credit::scope($ids)->get(); foreach ($credits as $credit) { - if ($action == 'archive') { - $credit->delete(); - } else if ($action == 'delete') { - $credit->forceDelete(); + if ($action == 'delete') { + $credit->is_deleted = true; + $credit->save(); } + $credit->delete(); } - $message = Utils::pluralize('Successfully '.$action.'d ? credit', count($ids)); + $message = Utils::pluralize('Successfully '.$action.'d ? credit', count($credits)); Session::flash('message', $message); return Redirect::to('credits'); diff --git a/app/controllers/InvoiceController.php b/app/controllers/InvoiceController.php index 24003038afe5..1395a1036720 100755 --- a/app/controllers/InvoiceController.php +++ b/app/controllers/InvoiceController.php @@ -37,6 +37,7 @@ class InvoiceController extends \BaseController { ->join('invoice_statuses', 'invoice_statuses.id', '=', 'invoices.invoice_status_id') ->where('invoices.account_id', '=', Auth::user()->account_id) ->where('invoices.deleted_at', '=', null) + ->where('clients.deleted_at', '=', null) ->where('invoices.is_recurring', '=', false) ->select('clients.public_id as client_public_id', 'invoice_number', 'clients.name as client_name', 'invoices.public_id', 'total', 'invoices.balance', 'invoice_date', 'due_date', 'invoice_statuses.name as invoice_status_name'); @@ -81,7 +82,7 @@ class InvoiceController extends \BaseController { '; @@ -138,7 +139,7 @@ class InvoiceController extends \BaseController { '; @@ -150,12 +151,22 @@ class InvoiceController extends \BaseController { public function view($invitationKey) { - $invitation = Invitation::with('user', 'invoice.account', 'invoice.invoice_items', 'invoice.client.account.account_gateways') + $invitation = Invitation::with('user', 'invoice.account', 'invoice.client', 'invoice.invoice_items', 'invoice.client.account.account_gateways') ->where('invitation_key', '=', $invitationKey)->firstOrFail(); $user = $invitation->user; $invoice = $invitation->invoice; + if (!$invoice || $invoice->is_deleted) { + return View::make('invoices.deleted'); + } + + $client = $invoice->client; + + if (!$client || $client->is_deleted) { + return View::make('invoices.deleted'); + } + if ($invoice->invoice_status_id < INVOICE_STATUS_VIEWED) { $invoice->invoice_status_id = INVOICE_STATUS_VIEWED; $invoice->save(); @@ -438,6 +449,10 @@ class InvoiceController extends \BaseController { $client->state = trim($inputClient->state); $client->postal_code = trim($inputClient->postal_code); $client->country_id = $inputClient->country_id ? $inputClient->country_id : null; + $client->notes = trim($inputClient->notes); + $client->client_size_id = $inputClient->client_size_id ? $inputClient->client_size_id : null; + $client->client_industry_id = $inputClient->client_industry_id ? $inputClient->client_industry_id : null; + $client->website = trim($inputClient->website); $client->save(); $isPrimary = true; @@ -498,7 +513,7 @@ class InvoiceController extends \BaseController { $invoice->frequency_id = $input->frequency_id ? $input->frequency_id : 0; $invoice->start_date = Utils::toSqlDate($input->start_date); $invoice->end_date = Utils::toSqlDate($input->end_date); - $invoice->notes = $input->notes; + $invoice->terms = $input->terms; $invoice->po_number = $input->po_number; @@ -587,6 +602,7 @@ class InvoiceController extends \BaseController { /* */ + $message = $clientPublicId == "-1" ? ' and created client' : ''; if ($action == 'clone') { return InvoiceController::cloneInvoice($publicId); @@ -595,9 +611,9 @@ class InvoiceController extends \BaseController { { $this->mailer->sendInvoice($invoice); - Session::flash('message', 'Successfully emailed invoice'); + Session::flash('message', 'Successfully emailed invoice'.$message); } else { - Session::flash('message', 'Successfully saved invoice'); + Session::flash('message', 'Successfully saved invoice'.$message); } $url = 'invoices/' . $invoice->public_id . '/edit'; @@ -640,14 +656,14 @@ class InvoiceController extends \BaseController { $invoices = Invoice::scope($ids)->get(); foreach ($invoices as $invoice) { - if ($action == 'archive') { - $invoice->delete(); - } else if ($action == 'delete') { - $invoice->forceDelete(); + if ($action == 'delete') { + $invoice->is_deleted = true; + $invoice->save(); } + $invoice->delete(); } - $message = Utils::pluralize('Successfully '.$action.'d ? invoice', count($ids)); + $message = Utils::pluralize('Successfully '.$action.'d ? invoice', count($invoices)); Session::flash('message', $message); return Redirect::to('invoices'); diff --git a/app/controllers/PaymentController.php b/app/controllers/PaymentController.php index 3d12fab5d538..c63955c07594 100755 --- a/app/controllers/PaymentController.php +++ b/app/controllers/PaymentController.php @@ -18,6 +18,7 @@ class PaymentController extends \BaseController ->leftJoin('invoices', 'invoices.id', '=','payments.invoice_id') ->where('payments.account_id', '=', Auth::user()->account_id) ->where('payments.deleted_at', '=', null) + ->where('clients.deleted_at', '=', null) ->select('payments.public_id', 'payments.transaction_reference', 'clients.name as client_name', 'clients.public_id as client_public_id', 'payments.amount', 'payments.payment_date', 'invoices.public_id as invoice_public_id', 'invoices.invoice_number'); if ($clientPublicId) { @@ -57,7 +58,7 @@ class PaymentController extends \BaseController '; @@ -152,15 +153,15 @@ class PaymentController extends \BaseController $ids = Input::get('id') ? Input::get('id') : Input::get('ids'); $payments = Payment::scope($ids)->get(); - foreach ($payments as $payment) { - if ($action == 'archive') { - $payment->delete(); - } else if ($action == 'delete') { - $payment->forceDelete(); + foreach ($payments as $payment) { + if ($action == 'delete') { + $payment->is_deleted = true; + $payment->save(); } + $payment->delete(); } - $message = Utils::pluralize('Successfully '.$action.'d ? payment', count($ids)); + $message = Utils::pluralize('Successfully '.$action.'d ? payment', count($payments)); Session::flash('message', $message); return Redirect::to('payments'); diff --git a/app/controllers/ReportController.php b/app/controllers/ReportController.php new file mode 100755 index 000000000000..c9cbc3ce5154 --- /dev/null +++ b/app/controllers/ReportController.php @@ -0,0 +1,46 @@ +select(DB::raw('sum(total) as total, month(invoice_date) as month')) + ->where('invoices.deleted_at', '=', null) + ->where('invoices.invoice_date', '>', 0) + ->groupBy('month'); + + $totals = $records->lists('total'); + $dates = $records->lists('month'); + $data = array_combine($dates, $totals); + + $startDate = date_create('2013-06-30'); + $endDate = date_create('2013-12-30'); + $endDate = $endDate->modify('+1 month'); + $interval = new DateInterval('P1M'); + $period = new DatePeriod($startDate, $interval, $endDate); + + $totals = []; + $dates = []; + + foreach ($period as $d) + { + $date = $d->format('Y-m-d'); + $month = $d->format('n'); + + $dates[] = $date; + $totals[] = isset($data[$month]) ? $data[$month] : 0; + } + + $width = (ceil( max($totals) / 100 ) * 100) / 10; + + $params = [ + 'dates' => $dates, + 'totals' => $totals, + 'scaleStepWidth' => $width, + ]; + + return View::make('reports.monthly', $params); + } + +} \ No newline at end of file diff --git a/app/controllers/UserController.php b/app/controllers/UserController.php index 8a01ce33f52c..978a99273476 100755 --- a/app/controllers/UserController.php +++ b/app/controllers/UserController.php @@ -74,6 +74,7 @@ class UserController extends BaseController { { if( Confide::user() ) { + Event::fire('user.login'); return Redirect::to('/clients'); } else @@ -101,10 +102,7 @@ class UserController extends BaseController { // Get the value from the config file instead of changing the controller if ( Confide::logAttempt( $input, Config::get('confide::signup_confirm') ) ) { - $account = Account::findOrFail(Auth::user()->account_id); - $account->last_login = Carbon::now()->toDateTimeString(); - $account->save(); - + Event::fire('user.login'); // Redirect the user to the URL they were trying to access before // caught by the authentication filter IE Redirect::guest('user/login'). // Otherwise fallback to '/' diff --git a/app/database/migrations/2013_11_05_180133_confide_setup_users_table.php b/app/database/migrations/2013_11_05_180133_confide_setup_users_table.php index 0a855849db23..4c6354bf0015 100755 --- a/app/database/migrations/2013_11_05_180133_confide_setup_users_table.php +++ b/app/database/migrations/2013_11_05_180133_confide_setup_users_table.php @@ -31,6 +31,8 @@ class ConfideSetupUsersTable extends Migration { Schema::dropIfExists('countries'); Schema::dropIfExists('timezones'); Schema::dropIfExists('frequencies'); + Schema::dropIfExists('date_formats'); + Schema::dropIfExists('datetime_formats'); Schema::create('countries', function($table) { @@ -63,10 +65,26 @@ class ConfideSetupUsersTable extends Migration { $t->string('location'); }); + Schema::create('date_formats', function($t) + { + $t->increments('id'); + $t->string('format'); + $t->string('label'); + }); + + Schema::create('datetime_formats', function($t) + { + $t->increments('id'); + $t->string('format'); + $t->string('label'); + }); + Schema::create('accounts', function($t) { $t->increments('id'); $t->unsignedInteger('timezone_id')->nullable(); + $t->unsignedInteger('date_format_id')->nullable(); + $t->unsignedInteger('datetime_format_id')->nullable(); $t->timestamps(); $t->softDeletes(); @@ -85,19 +103,20 @@ class ConfideSetupUsersTable extends Migration { $t->text('invoice_terms'); $t->foreign('timezone_id')->references('id')->on('timezones'); + $t->foreign('date_format_id')->references('id')->on('date_formats'); + $t->foreign('datetime_format_id')->references('id')->on('datetime_formats'); $t->foreign('country_id')->references('id')->on('countries'); }); Schema::create('gateways', function($t) { $t->increments('id'); - $t->timestamps(); - $t->softDeletes(); + $t->timestamps(); $t->string('name'); $t->string('provider'); $t->boolean('visible')->default(true); - }); + }); Schema::create('account_gateways', function($t) { @@ -105,8 +124,7 @@ class ConfideSetupUsersTable extends Migration { $t->unsignedInteger('account_id'); $t->unsignedInteger('gateway_id'); $t->timestamps(); - $t->softDeletes(); - + $t->text('config'); $t->foreign('account_id')->references('id')->on('accounts')->onDelete('cascade'); @@ -175,10 +193,12 @@ class ConfideSetupUsersTable extends Migration { $t->string('work_phone'); $t->text('notes'); $t->decimal('balance', 10, 2); + $t->decimal('paid_to_date', 10, 2); $t->timestamp('last_login'); $t->string('website'); $t->unsignedInteger('client_industry_id')->nullable(); $t->unsignedInteger('client_size_id')->nullable(); + $t->boolean('is_deleted'); $t->foreign('account_id')->references('id')->on('accounts')->onDelete('cascade'); $t->foreign('user_id')->references('id')->on('users'); @@ -240,8 +260,8 @@ class ConfideSetupUsersTable extends Migration { $t->string('po_number'); $t->date('invoice_date')->nullable(); $t->date('due_date')->nullable(); - $t->text('notes'); - + $t->text('terms'); + $t->boolean('is_deleted'); $t->boolean('is_recurring'); $t->unsignedInteger('frequency_id'); $t->date('start_date')->nullable(); @@ -341,7 +361,8 @@ class ConfideSetupUsersTable extends Migration { $t->unsignedInteger('user_id')->nullable(); $t->timestamps(); $t->softDeletes(); - + + $t->boolean('is_deleted'); $t->decimal('amount', 10, 2); $t->date('payment_date'); $t->string('transaction_reference'); @@ -367,8 +388,9 @@ class ConfideSetupUsersTable extends Migration { $t->timestamps(); $t->softDeletes(); + $t->boolean('is_deleted'); $t->decimal('amount', 10, 2); - $t->date('credit_date'); + $t->date('credit_date')->nullable(); $t->string('credit_number'); $t->foreign('account_id')->references('id')->on('accounts'); @@ -432,5 +454,7 @@ class ConfideSetupUsersTable extends Migration { Schema::dropIfExists('countries'); Schema::dropIfExists('timezones'); Schema::dropIfExists('frequencies'); + Schema::dropIfExists('date_formats'); + Schema::dropIfExists('datetime_formats'); } } diff --git a/app/database/seeds/ConstantsSeeder.php b/app/database/seeds/ConstantsSeeder.php index 171badd4db65..5b3a678f3764 100755 --- a/app/database/seeds/ConstantsSeeder.php +++ b/app/database/seeds/ConstantsSeeder.php @@ -69,6 +69,13 @@ class ConstantsSeeder extends Seeder ClientSize::create(array('name' => '101 - 500')); ClientSize::create(array('name' => '500+')); + DatetimeFormat::create(array('format' => 'F j, Y, g:i a', 'label' => 'March 10, 2013, 6:15 pm')); + DatetimeFormat::create(array('format' => 'D M jS, Y g:ia', 'label' => 'Mon March 10th, 2013, 6:15 pm')); + + DateFormat::create(array('format' => 'F j, Y', 'label' => 'March 10, 2013')); + DateFormat::create(array('format' => 'D M jS', 'label' => 'Mon March 10th, 2013')); + + $gateways = [ array('name'=>'Authorize.Net AIM', 'provider'=>'AuthorizeNet_AIM'), array('name'=>'Authorize.Net SIM', 'provider'=>'AuthorizeNet_SIM'), diff --git a/app/handlers/UserEventHandler.php b/app/handlers/UserEventHandler.php new file mode 100755 index 000000000000..af8095341121 --- /dev/null +++ b/app/handlers/UserEventHandler.php @@ -0,0 +1,36 @@ +listen('user.signup', 'UserEventHandler@onSignup'); + $events->listen('user.login', 'UserEventHandler@onLogin'); + + $events->listen('user.refresh', 'UserEventHandler@onRefresh'); + } + + public function onSignup() + { + dd('user signed up'); + } + + public function onLogin() + { + $account = Account::findOrFail(Auth::user()->account_id); + $account->last_login = Carbon::now()->toDateTimeString(); + $account->save(); + + Event::fire('user.refresh'); + } + + public function onRefresh() + { + $user = User::whereId(Auth::user()->id)->with('account', 'account.date_format', 'account.datetime_format', 'account.timezone')->firstOrFail(); + $account = $user->account; + + Session::put(SESSION_TIMEZONE, $account->timezone ? $account->timezone->name : DEFAULT_TIMEZONE); + Session::put(SESSION_DATE_FORMAT, $account->date_format ? $account->date_format->format : DEFAULT_DATE_FORMAT); + Session::put(SESSION_DATETIME_FORMAT, $account->datetime_format ? $account->datetime_format->format : DEFAULT_DATETIME_FORMAT); + } +} \ No newline at end of file diff --git a/app/libraries/utils.php b/app/libraries/utils.php index c97b079eb05b..60d15448299a 100755 --- a/app/libraries/utils.php +++ b/app/libraries/utils.php @@ -52,30 +52,25 @@ class Utils } public static function timestampToDateTimeString($timestamp) { - $tz = Session::get('tz'); - if (!$tz) { - $tz = 'US/Eastern'; - } - $date = new Carbon($timestamp); - $date->tz = $tz; - if ($date->year < 1900) { - return ''; - } - - return $date->format('D M jS, Y g:ia'); + $timezone = Session::get(SESSION_TIMEZONE, DEFAULT_TIMEZONE); + $format = Session::get(SESSION_DATETIME_FORMAT, DEFAULT_DATETIME_FORMAT); + return Utils::timestampToString($timestamp, $timezone, $format); } public static function timestampToDateString($timestamp) { - $tz = Session::get('tz'); - if (!$tz) { - $tz = 'US/Eastern'; - } + $timezone = Session::get(SESSION_TIMEZONE, DEFAULT_TIMEZONE); + $format = Session::get(SESSION_DATE_FORMAT, DEFAULT_DATE_FORMAT); + return Utils::timestampToString($timestamp, $timezone, $format); + } + + public static function timestampToString($timestamp, $timzone, $format) + { $date = new Carbon($timestamp); - $date->tz = $tz; + $date->tz = $timzone; if ($date->year < 1900) { return ''; } - return $date->toFormattedDateString(); + return $date->format($format); } public static function toSqlDate($date) diff --git a/app/models/Account.php b/app/models/Account.php index 5278d32555a0..1a0c90e8b4a4 100755 --- a/app/models/Account.php +++ b/app/models/Account.php @@ -35,6 +35,17 @@ class Account extends Eloquent return $this->belongsTo('Timezone'); } + public function date_format() + { + return $this->belongsTo('DateFormat'); + } + + public function datetime_format() + { + return $this->belongsTo('DatetimeFormat'); + } + + public function isGatewayConfigured($gatewayId = 0) { if ($gatewayId) diff --git a/app/models/Client.php b/app/models/Client.php index 7908831fce58..c1f308a92ca1 100755 --- a/app/models/Client.php +++ b/app/models/Client.php @@ -131,6 +131,16 @@ class Client extends EntityModel return $str; } + public function getWebsite() + { + if (!$this->website) + { + return ''; + } + + return link_to($this->website, $this->website); + } + public function getDateCreated() { if ($this->created_at == '0000-00-00 00:00:00') diff --git a/app/models/DateFormat.php b/app/models/DateFormat.php new file mode 100755 index 000000000000..4036532d3f91 --- /dev/null +++ b/app/models/DateFormat.php @@ -0,0 +1,7 @@ + 'auth'), function() Route::resource('credits', 'CreditController'); Route::get('credits/create/{client_id?}', 'CreditController@create'); Route::get('api/credits/{client_id?}', array('as'=>'api.credits', 'uses'=>'CreditController@getDatatable')); - Route::post('credits/bulk', 'PaymentController@bulk'); + Route::post('credits/bulk', 'CreditController@bulk'); - Route::get('reports', function() { return View::make('header'); }); + Route::get('reports', 'ReportController@monthly'); }); @@ -160,4 +160,12 @@ define('FREQUENCY_FOUR_WEEKS', 3); define('FREQUENCY_MONTHLY', 4); define('FREQUENCY_THREE_MONTHS', 5); define('FREQUENCY_SIX_MONTHS', 6); -define('FREQUENCY_ANNUALLY', 7); \ No newline at end of file +define('FREQUENCY_ANNUALLY', 7); + +define('SESSION_TIMEZONE', 'timezone'); +define('SESSION_DATE_FORMAT', 'dateFormat'); +define('SESSION_DATETIME_FORMAT', 'datetimeFormat'); + +define('DEFAULT_TIMEZONE', 'US/Eastern'); +define('DEFAULT_DATE_FORMAT', 'F j, Y'); +define('DEFAULT_DATETIME_FORMAT', 'F j, Y, g:i a'); diff --git a/app/start/global.php b/app/start/global.php index 05f422745ba4..1f377f021b6e 100755 --- a/app/start/global.php +++ b/app/start/global.php @@ -18,6 +18,7 @@ ClassLoader::addDirectories(array( app_path().'/models', app_path().'/database/seeds', app_path().'/libraries', + app_path().'/handlers', )); @@ -70,6 +71,11 @@ App::down(function() return Response::make("Be right back!", 503); }); + + +Event::subscribe('UserEventHandler'); + + /* |-------------------------------------------------------------------------- | Require The Filters File diff --git a/app/views/accounts/details.blade.php b/app/views/accounts/details.blade.php index 1cdc1fd11343..3efda2841cb1 100755 --- a/app/views/accounts/details.blade.php +++ b/app/views/accounts/details.blade.php @@ -27,8 +27,6 @@ {{ Former::legend('Account') }} {{ Former::text('name') }} - {{ Former::select('timezone_id')->addOption('','')->label('Timezone') - ->fromQuery($timezones, 'location', 'id')->select($account->timezone_id) }} {{ Former::file('logo')->max(2, 'MB')->accept('image')->wrap('test') }} @if (file_exists($account->getLogoPath())) diff --git a/app/views/accounts/settings.blade.php b/app/views/accounts/settings.blade.php index 83d9e5fd5897..fafe8f75558c 100755 --- a/app/views/accounts/settings.blade.php +++ b/app/views/accounts/settings.blade.php @@ -3,7 +3,7 @@ @section('content') @parent - {{ Former::open()->addClass('col-md-10 col-md-offset-1') }} + {{ Former::open()->addClass('col-md-8 col-md-offset-2') }} {{ Former::populate($account) }} {{ Former::legend('Payment Gateway') }} @@ -36,6 +36,15 @@ @endforeach + {{ Former::legend('Date and Time') }} + {{ Former::select('timezone_id')->addOption('','')->label('Timezone') + ->fromQuery($timezones, 'location', 'id')->select($account->timezone_id) }} + {{ Former::select('date_format_id')->addOption('','')->label('Date Format') + ->fromQuery($dateFormats, 'label', 'id')->select($account->date_format_id) }} + {{ Former::select('datetime_format_id')->addOption('','')->label('Date/Time Format') + ->fromQuery($datetimeFormats, 'label', 'id')->select($account->datetime_format_id) }} + + {{ Former::legend('Invoices') }} {{ Former::textarea('invoice_terms') }} diff --git a/app/views/clients/edit.blade.php b/app/views/clients/edit.blade.php index 875cc7ed3a3d..9c85e599c78f 100755 --- a/app/views/clients/edit.blade.php +++ b/app/views/clients/edit.blade.php @@ -24,6 +24,7 @@ {{ Former::legend('Organization') }} {{ Former::text('name') }} + {{ Former::text('website') }} {{ Former::text('work_phone')->label('Phone') }} diff --git a/app/views/clients/show.blade.php b/app/views/clients/show.blade.php index 1c35e43729fc..bd9ce41c0625 100755 --- a/app/views/clients/show.blade.php +++ b/app/views/clients/show.blade.php @@ -50,6 +50,7 @@

{{ $client->getPhone() }}

{{ $client->getNotes() }}

{{ $client->getIndustry() }}

+

{{ $client->getWebsite() }}

diff --git a/app/views/header.blade.php b/app/views/header.blade.php index ecae9e300b2e..196d1672fe14 100755 --- a/app/views/header.blade.php +++ b/app/views/header.blade.php @@ -273,7 +273,7 @@ {{ HTML::menu_link('invoice') }} {{ HTML::menu_link('payment') }} {{ HTML::menu_link('credit') }} - {{-- HTML::nav_link('reports', 'Reports') --}} + {{ HTML::nav_link('reports', 'Reports') }}
{{ Former::text('discount')->data_bind("value: discount, valueUpdate: 'afterkeydown'") }} - {{ Former::textarea('notes')->data_bind("value: notes, valueUpdate: 'afterkeydown'") }} + {{ Former::textarea('terms')->data_bind("value: wrapped_terms, valueUpdate: 'afterkeydown'") }}
@@ -94,7 +94,7 @@ ->raw()->data_bind("value: product_key, valueUpdate: 'afterkeydown'")->addClass('datalist') }} - + @@ -195,6 +195,7 @@ {{ Former::legend('Organization') }} {{ Former::text('name')->data_bind("value: name, valueUpdate: 'afterkeydown'") }} + {{ Former::text('website')->data_bind("value: website, valueUpdate: 'afterkeydown'") }} {{ Former::text('work_phone')->data_bind("value: work_phone, valueUpdate: 'afterkeydown'")->label('Phone') }} @@ -437,9 +438,10 @@ this.client = new ClientModel(); self.discount = ko.observable(''); self.frequency_id = ko.observable(''); - self.notes = ko.observable(''); + self.terms = ko.observable(''); self.po_number = ko.observable(''); self.invoice_date = ko.observable(''); + self.invoice_number = ko.observable(''); self.due_date = ko.observable(''); self.start_date = ko.observable(''); self.end_date = ko.observable(''); @@ -455,11 +457,22 @@ } } + self.wrapped_terms = ko.computed({ + read: function() { + return this.terms(); + }, + write: function(value) { + value = wordWrapText(value, 250); + self.terms(value); + $('#terms').height(value.split('\n').length * 22); + }, + owner: this + }); + self.showClientText = ko.computed(function() { return self.client.public_id() ? 'Edit client details' : 'Create new client'; }); - self.showClientForm = function() { if (self.client.public_id() == 0) { $('#myModal input').val(''); @@ -552,6 +565,7 @@ self.country_id = ko.observable(''); self.client_size_id = ko.observable(''); self.client_industry_id = ko.observable(''); + self.website = ko.observable(''); self.contacts = ko.observableArray(); self.mapping = { @@ -617,6 +631,18 @@ ko.mapping.fromJS(data, {}, this); } + self.wrapped_notes = ko.computed({ + read: function() { + return this.notes(); + }, + write: function(value) { + value = wordWrapText(value); + self.notes(value); + onChange(); + }, + owner: this + }); + this.rawTotal = ko.computed(function() { var cost = parseFloat(self.cost()); var qty = parseFloat(self.qty()); @@ -646,36 +672,6 @@ } } - function checkWordWrap(event) - { - var doc = new jsPDF('p', 'pt'); - doc.setFont('Helvetica',''); - doc.setFontSize(10); - - var $textarea = $(event.target || event.srcElement); - var lines = $textarea.val().split("\n"); - for (var i = 0; i < lines.length; i++) { - var numLines = doc.splitTextToSize(lines[i], 200).length; - if (numLines <= 1) continue; - var j = 0; space = lines[i].length; - while (j++ < lines[i].length) { - if (lines[i].charAt(j) === " ") space = j; - } - lines[i + 1] = lines[i].substring(space + 1) + (lines[i + 1] || ""); - lines[i] = lines[i].substring(0, space); - } - - var val = lines.slice(0, 6).join("\n"); - if (val != $textarea.val()) - { - var model = ko.dataFor($textarea[0]); - model.notes(val); - refreshPDF(); - } - $textarea.height(val.split('\n').length * 22); - onChange(); - } - function onChange() { var hasEmpty = false; @@ -688,6 +684,10 @@ if (!hasEmpty) { model.addItem(); } + + $('.word-wrap').each(function(index, input) { + $(input).height($(input).val().split('\n').length * 22); + }); } var products = {{ $products }}; @@ -696,8 +696,8 @@ for (var i=0; i= 0; } @else - model.invoice_number = '{{ $invoiceNumber }}'; + model.invoice_number('{{ $invoiceNumber }}'); + model.terms(wordWrapText('{{ $account->invoice_terms }}', 250)); @endif model.invoice_items.push(new ItemModel()); ko.applyBindings(model); diff --git a/app/views/reports/monthly.blade.php b/app/views/reports/monthly.blade.php new file mode 100755 index 000000000000..fdb6948da642 --- /dev/null +++ b/app/views/reports/monthly.blade.php @@ -0,0 +1,39 @@ +@extends('header') + +@section('head') + @parent + + +@stop + +@section('content') + +
+ +
+ + + +@stop \ No newline at end of file diff --git a/public/js/Chart.js b/public/js/Chart.js new file mode 100755 index 000000000000..ffbe16f37113 --- /dev/null +++ b/public/js/Chart.js @@ -0,0 +1,1426 @@ +/*! + * Chart.js + * http://chartjs.org/ + * + * Copyright 2013 Nick Downie + * Released under the MIT license + * https://github.com/nnnick/Chart.js/blob/master/LICENSE.md + */ + +//Define the global Chart Variable as a class. +window.Chart = function(context){ + + var chart = this; + + + //Easing functions adapted from Robert Penner's easing equations + //http://www.robertpenner.com/easing/ + + var animationOptions = { + linear : function (t){ + return t; + }, + easeInQuad: function (t) { + return t*t; + }, + easeOutQuad: function (t) { + return -1 *t*(t-2); + }, + easeInOutQuad: function (t) { + if ((t/=1/2) < 1) return 1/2*t*t; + return -1/2 * ((--t)*(t-2) - 1); + }, + easeInCubic: function (t) { + return t*t*t; + }, + easeOutCubic: function (t) { + return 1*((t=t/1-1)*t*t + 1); + }, + easeInOutCubic: function (t) { + if ((t/=1/2) < 1) return 1/2*t*t*t; + return 1/2*((t-=2)*t*t + 2); + }, + easeInQuart: function (t) { + return t*t*t*t; + }, + easeOutQuart: function (t) { + return -1 * ((t=t/1-1)*t*t*t - 1); + }, + easeInOutQuart: function (t) { + if ((t/=1/2) < 1) return 1/2*t*t*t*t; + return -1/2 * ((t-=2)*t*t*t - 2); + }, + easeInQuint: function (t) { + return 1*(t/=1)*t*t*t*t; + }, + easeOutQuint: function (t) { + return 1*((t=t/1-1)*t*t*t*t + 1); + }, + easeInOutQuint: function (t) { + if ((t/=1/2) < 1) return 1/2*t*t*t*t*t; + return 1/2*((t-=2)*t*t*t*t + 2); + }, + easeInSine: function (t) { + return -1 * Math.cos(t/1 * (Math.PI/2)) + 1; + }, + easeOutSine: function (t) { + return 1 * Math.sin(t/1 * (Math.PI/2)); + }, + easeInOutSine: function (t) { + return -1/2 * (Math.cos(Math.PI*t/1) - 1); + }, + easeInExpo: function (t) { + return (t==0) ? 1 : 1 * Math.pow(2, 10 * (t/1 - 1)); + }, + easeOutExpo: function (t) { + return (t==1) ? 1 : 1 * (-Math.pow(2, -10 * t/1) + 1); + }, + easeInOutExpo: function (t) { + if (t==0) return 0; + if (t==1) return 1; + if ((t/=1/2) < 1) return 1/2 * Math.pow(2, 10 * (t - 1)); + return 1/2 * (-Math.pow(2, -10 * --t) + 2); + }, + easeInCirc: function (t) { + if (t>=1) return t; + return -1 * (Math.sqrt(1 - (t/=1)*t) - 1); + }, + easeOutCirc: function (t) { + return 1 * Math.sqrt(1 - (t=t/1-1)*t); + }, + easeInOutCirc: function (t) { + if ((t/=1/2) < 1) return -1/2 * (Math.sqrt(1 - t*t) - 1); + return 1/2 * (Math.sqrt(1 - (t-=2)*t) + 1); + }, + easeInElastic: function (t) { + var s=1.70158;var p=0;var a=1; + if (t==0) return 0; if ((t/=1)==1) return 1; if (!p) p=1*.3; + if (a < Math.abs(1)) { a=1; var s=p/4; } + else var s = p/(2*Math.PI) * Math.asin (1/a); + return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*1-s)*(2*Math.PI)/p )); + }, + easeOutElastic: function (t) { + var s=1.70158;var p=0;var a=1; + if (t==0) return 0; if ((t/=1)==1) return 1; if (!p) p=1*.3; + if (a < Math.abs(1)) { a=1; var s=p/4; } + else var s = p/(2*Math.PI) * Math.asin (1/a); + return a*Math.pow(2,-10*t) * Math.sin( (t*1-s)*(2*Math.PI)/p ) + 1; + }, + easeInOutElastic: function (t) { + var s=1.70158;var p=0;var a=1; + if (t==0) return 0; if ((t/=1/2)==2) return 1; if (!p) p=1*(.3*1.5); + if (a < Math.abs(1)) { a=1; var s=p/4; } + else var s = p/(2*Math.PI) * Math.asin (1/a); + if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*1-s)*(2*Math.PI)/p )); + return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*1-s)*(2*Math.PI)/p )*.5 + 1; + }, + easeInBack: function (t) { + var s = 1.70158; + return 1*(t/=1)*t*((s+1)*t - s); + }, + easeOutBack: function (t) { + var s = 1.70158; + return 1*((t=t/1-1)*t*((s+1)*t + s) + 1); + }, + easeInOutBack: function (t) { + var s = 1.70158; + if ((t/=1/2) < 1) return 1/2*(t*t*(((s*=(1.525))+1)*t - s)); + return 1/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2); + }, + easeInBounce: function (t) { + return 1 - animationOptions.easeOutBounce (1-t); + }, + easeOutBounce: function (t) { + if ((t/=1) < (1/2.75)) { + return 1*(7.5625*t*t); + } else if (t < (2/2.75)) { + return 1*(7.5625*(t-=(1.5/2.75))*t + .75); + } else if (t < (2.5/2.75)) { + return 1*(7.5625*(t-=(2.25/2.75))*t + .9375); + } else { + return 1*(7.5625*(t-=(2.625/2.75))*t + .984375); + } + }, + easeInOutBounce: function (t) { + if (t < 1/2) return animationOptions.easeInBounce (t*2) * .5; + return animationOptions.easeOutBounce (t*2-1) * .5 + 1*.5; + } + }; + + //Variables global to the chart + var width = context.canvas.width; + var height = context.canvas.height; + + + //High pixel density displays - multiply the size of the canvas height/width by the device pixel ratio, then scale. + if (window.devicePixelRatio) { + context.canvas.style.width = width + "px"; + context.canvas.style.height = height + "px"; + context.canvas.height = height * window.devicePixelRatio; + context.canvas.width = width * window.devicePixelRatio; + context.scale(window.devicePixelRatio, window.devicePixelRatio); + } + + this.PolarArea = function(data,options){ + + chart.PolarArea.defaults = { + scaleOverlay : true, + scaleOverride : false, + scaleSteps : null, + scaleStepWidth : null, + scaleStartValue : null, + scaleShowLine : true, + scaleLineColor : "rgba(0,0,0,.1)", + scaleLineWidth : 1, + scaleShowLabels : true, + scaleLabel : "<%=value%>", + scaleFontFamily : "'Arial'", + scaleFontSize : 12, + scaleFontStyle : "normal", + scaleFontColor : "#666", + scaleShowLabelBackdrop : true, + scaleBackdropColor : "rgba(255,255,255,0.75)", + scaleBackdropPaddingY : 2, + scaleBackdropPaddingX : 2, + segmentShowStroke : true, + segmentStrokeColor : "#fff", + segmentStrokeWidth : 2, + animation : true, + animationSteps : 100, + animationEasing : "easeOutBounce", + animateRotate : true, + animateScale : false, + onAnimationComplete : null + }; + + var config = (options)? mergeChartConfig(chart.PolarArea.defaults,options) : chart.PolarArea.defaults; + + return new PolarArea(data,config,context); + }; + + this.Radar = function(data,options){ + + chart.Radar.defaults = { + scaleOverlay : false, + scaleOverride : false, + scaleSteps : null, + scaleStepWidth : null, + scaleStartValue : null, + scaleShowLine : true, + scaleLineColor : "rgba(0,0,0,.1)", + scaleLineWidth : 1, + scaleShowLabels : false, + scaleLabel : "<%=value%>", + scaleFontFamily : "'Arial'", + scaleFontSize : 12, + scaleFontStyle : "normal", + scaleFontColor : "#666", + scaleShowLabelBackdrop : true, + scaleBackdropColor : "rgba(255,255,255,0.75)", + scaleBackdropPaddingY : 2, + scaleBackdropPaddingX : 2, + angleShowLineOut : true, + angleLineColor : "rgba(0,0,0,.1)", + angleLineWidth : 1, + pointLabelFontFamily : "'Arial'", + pointLabelFontStyle : "normal", + pointLabelFontSize : 12, + pointLabelFontColor : "#666", + pointDot : true, + pointDotRadius : 3, + pointDotStrokeWidth : 1, + datasetStroke : true, + datasetStrokeWidth : 2, + datasetFill : true, + animation : true, + animationSteps : 60, + animationEasing : "easeOutQuart", + onAnimationComplete : null + }; + + var config = (options)? mergeChartConfig(chart.Radar.defaults,options) : chart.Radar.defaults; + + return new Radar(data,config,context); + }; + + this.Pie = function(data,options){ + chart.Pie.defaults = { + segmentShowStroke : true, + segmentStrokeColor : "#fff", + segmentStrokeWidth : 2, + animation : true, + animationSteps : 100, + animationEasing : "easeOutBounce", + animateRotate : true, + animateScale : false, + onAnimationComplete : null + }; + + var config = (options)? mergeChartConfig(chart.Pie.defaults,options) : chart.Pie.defaults; + + return new Pie(data,config,context); + }; + + this.Doughnut = function(data,options){ + + chart.Doughnut.defaults = { + segmentShowStroke : true, + segmentStrokeColor : "#fff", + segmentStrokeWidth : 2, + percentageInnerCutout : 50, + animation : true, + animationSteps : 100, + animationEasing : "easeOutBounce", + animateRotate : true, + animateScale : false, + onAnimationComplete : null + }; + + var config = (options)? mergeChartConfig(chart.Doughnut.defaults,options) : chart.Doughnut.defaults; + + return new Doughnut(data,config,context); + + }; + + this.Line = function(data,options){ + + chart.Line.defaults = { + scaleOverlay : false, + scaleOverride : false, + scaleSteps : null, + scaleStepWidth : null, + scaleStartValue : null, + scaleLineColor : "rgba(0,0,0,.1)", + scaleLineWidth : 1, + scaleShowLabels : true, + scaleLabel : "<%=value%>", + scaleFontFamily : "'Arial'", + scaleFontSize : 12, + scaleFontStyle : "normal", + scaleFontColor : "#666", + scaleShowGridLines : true, + scaleGridLineColor : "rgba(0,0,0,.05)", + scaleGridLineWidth : 1, + bezierCurve : true, + pointDot : true, + pointDotRadius : 4, + pointDotStrokeWidth : 2, + datasetStroke : true, + datasetStrokeWidth : 2, + datasetFill : true, + animation : true, + animationSteps : 60, + animationEasing : "easeOutQuart", + onAnimationComplete : null + }; + var config = (options) ? mergeChartConfig(chart.Line.defaults,options) : chart.Line.defaults; + + return new Line(data,config,context); + } + + this.Bar = function(data,options){ + chart.Bar.defaults = { + scaleOverlay : false, + scaleOverride : false, + scaleSteps : null, + scaleStepWidth : null, + scaleStartValue : null, + scaleLineColor : "rgba(0,0,0,.1)", + scaleLineWidth : 1, + scaleShowLabels : true, + scaleLabel : "<%=value%>", + scaleFontFamily : "'Arial'", + scaleFontSize : 12, + scaleFontStyle : "normal", + scaleFontColor : "#666", + scaleShowGridLines : true, + scaleGridLineColor : "rgba(0,0,0,.05)", + scaleGridLineWidth : 1, + barShowStroke : true, + barStrokeWidth : 2, + barValueSpacing : 5, + barDatasetSpacing : 1, + animation : true, + animationSteps : 60, + animationEasing : "easeOutQuart", + onAnimationComplete : null + }; + var config = (options) ? mergeChartConfig(chart.Bar.defaults,options) : chart.Bar.defaults; + + return new Bar(data,config,context); + } + + var clear = function(c){ + c.clearRect(0, 0, width, height); + }; + + var PolarArea = function(data,config,ctx){ + var maxSize, scaleHop, calculatedScale, labelHeight, scaleHeight, valueBounds, labelTemplateString; + + + calculateDrawingSizes(); + + valueBounds = getValueBounds(); + + labelTemplateString = (config.scaleShowLabels)? config.scaleLabel : null; + + //Check and set the scale + if (!config.scaleOverride){ + + calculatedScale = calculateScale(scaleHeight,valueBounds.maxSteps,valueBounds.minSteps,valueBounds.maxValue,valueBounds.minValue,labelTemplateString); + } + else { + calculatedScale = { + steps : config.scaleSteps, + stepValue : config.scaleStepWidth, + graphMin : config.scaleStartValue, + labels : [] + } + populateLabels(labelTemplateString, calculatedScale.labels,calculatedScale.steps,config.scaleStartValue,config.scaleStepWidth); + } + + scaleHop = maxSize/(calculatedScale.steps); + + //Wrap in an animation loop wrapper + animationLoop(config,drawScale,drawAllSegments,ctx); + + function calculateDrawingSizes(){ + maxSize = (Min([width,height])/2); + //Remove whatever is larger - the font size or line width. + + maxSize -= Max([config.scaleFontSize*0.5,config.scaleLineWidth*0.5]); + + labelHeight = config.scaleFontSize*2; + //If we're drawing the backdrop - add the Y padding to the label height and remove from drawing region. + if (config.scaleShowLabelBackdrop){ + labelHeight += (2 * config.scaleBackdropPaddingY); + maxSize -= config.scaleBackdropPaddingY*1.5; + } + + scaleHeight = maxSize; + //If the label height is less than 5, set it to 5 so we don't have lines on top of each other. + labelHeight = Default(labelHeight,5); + } + function drawScale(){ + for (var i=0; i upperValue) {upperValue = data[i].value;} + if (data[i].value < lowerValue) {lowerValue = data[i].value;} + }; + + var maxSteps = Math.floor((scaleHeight / (labelHeight*0.66))); + var minSteps = Math.floor((scaleHeight / labelHeight*0.5)); + + return { + maxValue : upperValue, + minValue : lowerValue, + maxSteps : maxSteps, + minSteps : minSteps + }; + + + } + } + + var Radar = function (data,config,ctx) { + var maxSize, scaleHop, calculatedScale, labelHeight, scaleHeight, valueBounds, labelTemplateString; + + //If no labels are defined set to an empty array, so referencing length for looping doesn't blow up. + if (!data.labels) data.labels = []; + + calculateDrawingSizes(); + + var valueBounds = getValueBounds(); + + labelTemplateString = (config.scaleShowLabels)? config.scaleLabel : null; + + //Check and set the scale + if (!config.scaleOverride){ + + calculatedScale = calculateScale(scaleHeight,valueBounds.maxSteps,valueBounds.minSteps,valueBounds.maxValue,valueBounds.minValue,labelTemplateString); + } + else { + calculatedScale = { + steps : config.scaleSteps, + stepValue : config.scaleStepWidth, + graphMin : config.scaleStartValue, + labels : [] + } + populateLabels(labelTemplateString, calculatedScale.labels,calculatedScale.steps,config.scaleStartValue,config.scaleStepWidth); + } + + scaleHop = maxSize/(calculatedScale.steps); + + animationLoop(config,drawScale,drawAllDataPoints,ctx); + + //Radar specific functions. + function drawAllDataPoints(animationDecimal){ + var rotationDegree = (2*Math.PI)/data.datasets[0].data.length; + + ctx.save(); + //translate to the centre of the canvas. + ctx.translate(width/2,height/2); + + //We accept multiple data sets for radar charts, so show loop through each set + for (var i=0; i Math.PI){ + ctx.textAlign = "right"; + } + else{ + ctx.textAlign = "left"; + } + + ctx.textBaseline = "middle"; + + ctx.fillText(data.labels[k],opposite,-adjacent); + + } + ctx.restore(); + }; + function calculateDrawingSizes(){ + maxSize = (Min([width,height])/2); + + labelHeight = config.scaleFontSize*2; + + var labelLength = 0; + for (var i=0; ilabelLength) labelLength = textMeasurement; + } + + //Figure out whats the largest - the height of the text or the width of what's there, and minus it from the maximum usable size. + maxSize -= Max([labelLength,((config.pointLabelFontSize/2)*1.5)]); + + maxSize -= config.pointLabelFontSize; + maxSize = CapValue(maxSize, null, 0); + scaleHeight = maxSize; + //If the label height is less than 5, set it to 5 so we don't have lines on top of each other. + labelHeight = Default(labelHeight,5); + }; + function getValueBounds() { + var upperValue = Number.MIN_VALUE; + var lowerValue = Number.MAX_VALUE; + + for (var i=0; i upperValue){upperValue = data.datasets[i].data[j]} + if (data.datasets[i].data[j] < lowerValue){lowerValue = data.datasets[i].data[j]} + } + } + + var maxSteps = Math.floor((scaleHeight / (labelHeight*0.66))); + var minSteps = Math.floor((scaleHeight / labelHeight*0.5)); + + return { + maxValue : upperValue, + minValue : lowerValue, + maxSteps : maxSteps, + minSteps : minSteps + }; + + + } + } + + var Pie = function(data,config,ctx){ + var segmentTotal = 0; + + //In case we have a canvas that is not a square. Minus 5 pixels as padding round the edge. + var pieRadius = Min([height/2,width/2]) - 5; + + for (var i=0; i 0){ + ctx.save(); + ctx.textAlign = "right"; + } + else{ + ctx.textAlign = "center"; + } + ctx.fillStyle = config.scaleFontColor; + for (var i=0; i 0){ + ctx.translate(yAxisPosX + i*valueHop,xAxisPosY + config.scaleFontSize); + ctx.rotate(-(rotateLabels * (Math.PI/180))); + ctx.fillText(data.labels[i], 0,0); + ctx.restore(); + } + + else{ + ctx.fillText(data.labels[i], yAxisPosX + i*valueHop,xAxisPosY + config.scaleFontSize+3); + } + + ctx.beginPath(); + ctx.moveTo(yAxisPosX + i * valueHop, xAxisPosY+3); + + //Check i isnt 0, so we dont go over the Y axis twice. + if(config.scaleShowGridLines && i>0){ + ctx.lineWidth = config.scaleGridLineWidth; + ctx.strokeStyle = config.scaleGridLineColor; + ctx.lineTo(yAxisPosX + i * valueHop, 5); + } + else{ + ctx.lineTo(yAxisPosX + i * valueHop, xAxisPosY+3); + } + ctx.stroke(); + } + + //Y axis + ctx.lineWidth = config.scaleLineWidth; + ctx.strokeStyle = config.scaleLineColor; + ctx.beginPath(); + ctx.moveTo(yAxisPosX,xAxisPosY+5); + ctx.lineTo(yAxisPosX,5); + ctx.stroke(); + + ctx.textAlign = "right"; + ctx.textBaseline = "middle"; + for (var j=0; j longestText)? measuredText : longestText; + } + //Add a little extra padding from the y axis + longestText +=10; + } + xAxisLength = width - longestText - widestXLabel; + valueHop = Math.floor(xAxisLength/(data.labels.length-1)); + + yAxisPosX = width-widestXLabel/2-xAxisLength; + xAxisPosY = scaleHeight + config.scaleFontSize/2; + } + function calculateDrawingSizes(){ + maxSize = height; + + //Need to check the X axis first - measure the length of each text metric, and figure out if we need to rotate by 45 degrees. + ctx.font = config.scaleFontStyle + " " + config.scaleFontSize+"px " + config.scaleFontFamily; + widestXLabel = 1; + for (var i=0; i widestXLabel)? textLength : widestXLabel; + } + if (width/data.labels.length < widestXLabel){ + rotateLabels = 45; + if (width/data.labels.length < Math.cos(rotateLabels) * widestXLabel){ + rotateLabels = 90; + maxSize -= widestXLabel; + } + else{ + maxSize -= Math.sin(rotateLabels) * widestXLabel; + } + } + else{ + maxSize -= config.scaleFontSize; + } + + //Add a little padding between the x line and the text + maxSize -= 5; + + + labelHeight = config.scaleFontSize; + + maxSize -= labelHeight; + //Set 5 pixels greater than the font size to allow for a little padding from the X axis. + + scaleHeight = maxSize; + + //Then get the area above we can safely draw on. + + } + function getValueBounds() { + var upperValue = Number.MIN_VALUE; + var lowerValue = Number.MAX_VALUE; + for (var i=0; i upperValue) { upperValue = data.datasets[i].data[j] }; + if ( data.datasets[i].data[j] < lowerValue) { lowerValue = data.datasets[i].data[j] }; + } + }; + + var maxSteps = Math.floor((scaleHeight / (labelHeight*0.66))); + var minSteps = Math.floor((scaleHeight / labelHeight*0.5)); + + return { + maxValue : upperValue, + minValue : lowerValue, + maxSteps : maxSteps, + minSteps : minSteps + }; + + + } + + + } + + var Bar = function(data,config,ctx){ + var maxSize, scaleHop, calculatedScale, labelHeight, scaleHeight, valueBounds, labelTemplateString, valueHop,widestXLabel, xAxisLength,yAxisPosX,xAxisPosY,barWidth, rotateLabels = 0; + + calculateDrawingSizes(); + + valueBounds = getValueBounds(); + //Check and set the scale + labelTemplateString = (config.scaleShowLabels)? config.scaleLabel : ""; + if (!config.scaleOverride){ + + calculatedScale = calculateScale(scaleHeight,valueBounds.maxSteps,valueBounds.minSteps,valueBounds.maxValue,valueBounds.minValue,labelTemplateString); + } + else { + calculatedScale = { + steps : config.scaleSteps, + stepValue : config.scaleStepWidth, + graphMin : config.scaleStartValue, + labels : [] + } + populateLabels(labelTemplateString, calculatedScale.labels,calculatedScale.steps,config.scaleStartValue,config.scaleStepWidth); + } + + scaleHop = Math.floor(scaleHeight/calculatedScale.steps); + calculateXAxisSize(); + animationLoop(config,drawScale,drawBars,ctx); + + function drawBars(animPc){ + ctx.lineWidth = config.barStrokeWidth; + for (var i=0; i 0){ + ctx.save(); + ctx.textAlign = "right"; + } + else{ + ctx.textAlign = "center"; + } + ctx.fillStyle = config.scaleFontColor; + for (var i=0; i 0){ + ctx.translate(yAxisPosX + i*valueHop,xAxisPosY + config.scaleFontSize); + ctx.rotate(-(rotateLabels * (Math.PI/180))); + ctx.fillText(data.labels[i], 0,0); + ctx.restore(); + } + + else{ + ctx.fillText(data.labels[i], yAxisPosX + i*valueHop + valueHop/2,xAxisPosY + config.scaleFontSize+3); + } + + ctx.beginPath(); + ctx.moveTo(yAxisPosX + (i+1) * valueHop, xAxisPosY+3); + + //Check i isnt 0, so we dont go over the Y axis twice. + ctx.lineWidth = config.scaleGridLineWidth; + ctx.strokeStyle = config.scaleGridLineColor; + ctx.lineTo(yAxisPosX + (i+1) * valueHop, 5); + ctx.stroke(); + } + + //Y axis + ctx.lineWidth = config.scaleLineWidth; + ctx.strokeStyle = config.scaleLineColor; + ctx.beginPath(); + ctx.moveTo(yAxisPosX,xAxisPosY+5); + ctx.lineTo(yAxisPosX,5); + ctx.stroke(); + + ctx.textAlign = "right"; + ctx.textBaseline = "middle"; + for (var j=0; j longestText)? measuredText : longestText; + } + //Add a little extra padding from the y axis + longestText +=10; + } + xAxisLength = width - longestText - widestXLabel; + valueHop = Math.floor(xAxisLength/(data.labels.length)); + + barWidth = (valueHop - config.scaleGridLineWidth*2 - (config.barValueSpacing*2) - (config.barDatasetSpacing*data.datasets.length-1) - ((config.barStrokeWidth/2)*data.datasets.length-1))/data.datasets.length; + + yAxisPosX = width-widestXLabel/2-xAxisLength; + xAxisPosY = scaleHeight + config.scaleFontSize/2; + } + function calculateDrawingSizes(){ + maxSize = height; + + //Need to check the X axis first - measure the length of each text metric, and figure out if we need to rotate by 45 degrees. + ctx.font = config.scaleFontStyle + " " + config.scaleFontSize+"px " + config.scaleFontFamily; + widestXLabel = 1; + for (var i=0; i widestXLabel)? textLength : widestXLabel; + } + if (width/data.labels.length < widestXLabel){ + rotateLabels = 45; + if (width/data.labels.length < Math.cos(rotateLabels) * widestXLabel){ + rotateLabels = 90; + maxSize -= widestXLabel; + } + else{ + maxSize -= Math.sin(rotateLabels) * widestXLabel; + } + } + else{ + maxSize -= config.scaleFontSize; + } + + //Add a little padding between the x line and the text + maxSize -= 5; + + + labelHeight = config.scaleFontSize; + + maxSize -= labelHeight; + //Set 5 pixels greater than the font size to allow for a little padding from the X axis. + + scaleHeight = maxSize; + + //Then get the area above we can safely draw on. + + } + function getValueBounds() { + var upperValue = Number.MIN_VALUE; + var lowerValue = Number.MAX_VALUE; + for (var i=0; i upperValue) { upperValue = data.datasets[i].data[j] }; + if ( data.datasets[i].data[j] < lowerValue) { lowerValue = data.datasets[i].data[j] }; + } + }; + + var maxSteps = Math.floor((scaleHeight / (labelHeight*0.66))); + var minSteps = Math.floor((scaleHeight / labelHeight*0.5)); + + return { + maxValue : upperValue, + minValue : lowerValue, + maxSteps : maxSteps, + minSteps : minSteps + }; + + + } + } + + function calculateOffset(val,calculatedScale,scaleHop){ + var outerValue = calculatedScale.steps * calculatedScale.stepValue; + var adjustedValue = val - calculatedScale.graphMin; + var scalingFactor = CapValue(adjustedValue/outerValue,1,0); + return (scaleHop*calculatedScale.steps) * scalingFactor; + } + + function animationLoop(config,drawScale,drawData,ctx){ + var animFrameAmount = (config.animation)? 1/CapValue(config.animationSteps,Number.MAX_VALUE,1) : 1, + easingFunction = animationOptions[config.animationEasing], + percentAnimComplete =(config.animation)? 0 : 1; + + + + if (typeof drawScale !== "function") drawScale = function(){}; + + requestAnimFrame(animLoop); + + function animateFrame(){ + var easeAdjustedAnimationPercent =(config.animation)? CapValue(easingFunction(percentAnimComplete),null,0) : 1; + clear(ctx); + if(config.scaleOverlay){ + drawData(easeAdjustedAnimationPercent); + drawScale(); + } else { + drawScale(); + drawData(easeAdjustedAnimationPercent); + } + } + function animLoop(){ + //We need to check if the animation is incomplete (less than 1), or complete (1). + percentAnimComplete += animFrameAmount; + animateFrame(); + //Stop the loop continuing forever + if (percentAnimComplete <= 1){ + requestAnimFrame(animLoop); + } + else{ + if (typeof config.onAnimationComplete == "function") config.onAnimationComplete(); + } + + } + + } + + //Declare global functions to be called within this namespace here. + + + // shim layer with setTimeout fallback + var requestAnimFrame = (function(){ + return window.requestAnimationFrame || + window.webkitRequestAnimationFrame || + window.mozRequestAnimationFrame || + window.oRequestAnimationFrame || + window.msRequestAnimationFrame || + function(callback) { + window.setTimeout(callback, 1000 / 60); + }; + })(); + + function calculateScale(drawingHeight,maxSteps,minSteps,maxValue,minValue,labelTemplateString){ + var graphMin,graphMax,graphRange,stepValue,numberOfSteps,valueRange,rangeOrderOfMagnitude,decimalNum; + + valueRange = maxValue - minValue; + + rangeOrderOfMagnitude = calculateOrderOfMagnitude(valueRange); + + graphMin = Math.floor(minValue / (1 * Math.pow(10, rangeOrderOfMagnitude))) * Math.pow(10, rangeOrderOfMagnitude); + + graphMax = Math.ceil(maxValue / (1 * Math.pow(10, rangeOrderOfMagnitude))) * Math.pow(10, rangeOrderOfMagnitude); + + graphRange = graphMax - graphMin; + + stepValue = Math.pow(10, rangeOrderOfMagnitude); + + numberOfSteps = Math.round(graphRange / stepValue); + + //Compare number of steps to the max and min for that size graph, and add in half steps if need be. + while(numberOfSteps < minSteps || numberOfSteps > maxSteps) { + if (numberOfSteps < minSteps){ + stepValue /= 2; + numberOfSteps = Math.round(graphRange/stepValue); + } + else{ + stepValue *=2; + numberOfSteps = Math.round(graphRange/stepValue); + } + }; + + var labels = []; + populateLabels(labelTemplateString, labels, numberOfSteps, graphMin, stepValue); + + return { + steps : numberOfSteps, + stepValue : stepValue, + graphMin : graphMin, + labels : labels + + } + + function calculateOrderOfMagnitude(val){ + return Math.floor(Math.log(val) / Math.LN10); + } + + + } + + //Populate an array of all the labels by interpolating the string. + function populateLabels(labelTemplateString, labels, numberOfSteps, graphMin, stepValue) { + if (labelTemplateString) { + //Fix floating point errors by setting to fixed the on the same decimal as the stepValue. + for (var i = 1; i < numberOfSteps + 1; i++) { + labels.push(tmpl(labelTemplateString, {value: (graphMin + (stepValue * i)).toFixed(getDecimalPlaces(stepValue))})); + } + } + } + + //Max value from array + function Max( array ){ + return Math.max.apply( Math, array ); + }; + //Min value from array + function Min( array ){ + return Math.min.apply( Math, array ); + }; + //Default if undefined + function Default(userDeclared,valueIfFalse){ + if(!userDeclared){ + return valueIfFalse; + } else { + return userDeclared; + } + }; + //Is a number function + function isNumber(n) { + return !isNaN(parseFloat(n)) && isFinite(n); + } + //Apply cap a value at a high or low number + function CapValue(valueToCap, maxValue, minValue){ + if(isNumber(maxValue)) { + if( valueToCap > maxValue ) { + return maxValue; + } + } + if(isNumber(minValue)){ + if ( valueToCap < minValue ){ + return minValue; + } + } + return valueToCap; + } + function getDecimalPlaces (num){ + var numberOfDecimalPlaces; + if (num%1!=0){ + return num.toString().split(".")[1].length + } + else{ + return 0; + } + + } + + function mergeChartConfig(defaults,userDefined){ + var returnObj = {}; + for (var attrname in defaults) { returnObj[attrname] = defaults[attrname]; } + for (var attrname in userDefined) { returnObj[attrname] = userDefined[attrname]; } + return returnObj; + } + + //Javascript micro templating by John Resig - source at http://ejohn.org/blog/javascript-micro-templating/ + var cache = {}; + + function tmpl(str, data){ + // Figure out if we're getting a template, or if we need to + // load the template - and be sure to cache the result. + var fn = !/\W/.test(str) ? + cache[str] = cache[str] || + tmpl(document.getElementById(str).innerHTML) : + + // Generate a reusable function that will serve as a template + // generator (and which will be cached). + new Function("obj", + "var p=[],print=function(){p.push.apply(p,arguments);};" + + + // Introduce the data as local variables using with(){} + "with(obj){p.push('" + + + // Convert the template into pure JavaScript + str + .replace(/[\r\t\n]/g, " ") + .split("<%").join("\t") + .replace(/((^|%>)[^\t]*)'/g, "$1\r") + .replace(/\t=(.*?)%>/g, "',$1,'") + .split("\t").join("');") + .split("%>").join("p.push('") + .split("\r").join("\\'") + + "');}return p.join('');"); + + // Provide some basic currying to the user + return data ? fn( data ) : fn; + }; +} + + diff --git a/public/js/script.js b/public/js/script.js index d9635634119a..7ddbfed622fc 100755 --- a/public/js/script.js +++ b/public/js/script.js @@ -139,12 +139,16 @@ function generatePDF(invoice) { var x = tableTop + (line * rowHeight); doc.lines([[0,0],[headerRight-tableLeft+5,0]],tableLeft - 8, x); + + doc.text(tableLeft, x+16, invoice.terms); + + x += 16; + doc.text(footerLeft, x, 'Subtotal'); + var total = formatNumber(total); + var totalX = headerRight - (doc.getStringUnitWidth(total) * doc.internal.getFontSize()); + doc.text(totalX, x, total); + if (invoice.discount > 0) { - x += 16; - doc.text(footerLeft, x, 'Subtotal'); - var total = formatNumber(total); - var totalX = headerRight - (doc.getStringUnitWidth(total) * doc.internal.getFontSize()); - doc.text(totalX, x, total); x += 16; doc.text(footerLeft, x, 'Discount'); @@ -154,6 +158,13 @@ function generatePDF(invoice) { doc.text(discountX, x, discount); } + x += 16; + doc.text(footerLeft, x, 'Paid to Date'); + var paid = formatNumber(0); + var paidX = headerRight - (doc.getStringUnitWidth(paid) * doc.internal.getFontSize()); + doc.text(paidX, x, paid); + + x += 16; doc.setFontType("bold"); doc.text(footerLeft, x, 'Total'); @@ -229,15 +240,6 @@ function generatePDF(invoice) { return doc; } -function formatNumber(num) { - num = parseFloat(num); - if (!num) return ''; - var p = num.toFixed(2).split("."); - return p[0].split("").reverse().reduce(function(acc, num, i, orig) { - return num + (i && !(i % 3) ? "," : "") + acc; - }, "") + "." + p[1]; -} - /* Handle converting variables in the invoices (ie, MONTH+1) */ function processVariables(str) { @@ -316,6 +318,16 @@ function formatMoney(num) { } +function formatNumber(num) { + num = parseFloat(num); + if (!num) num = 0; + var p = num.toFixed(2).split("."); + return p[0].split("").reverse().reduce(function(acc, num, i, orig) { + return num + (i && !(i % 3) ? "," : "") + acc; + }, "") + "." + p[1]; +} + + /* Set the defaults for DataTables initialisation */ $.extend( true, $.fn.dataTable.defaults, { "sDom": "t<'row-fluid'<'span6'i><'span6'p>>", @@ -590,6 +602,28 @@ ko.bindingHandlers.dropdown = { } }; +function wordWrapText(value, width) +{ + if (!width) width = 200; + var doc = new jsPDF('p', 'pt'); + doc.setFont('Helvetica',''); + doc.setFontSize(10); + + var lines = value.split("\n"); + for (var i = 0; i < lines.length; i++) { + var numLines = doc.splitTextToSize(lines[i], width).length; + if (numLines <= 1) continue; + var j = 0; space = lines[i].length; + while (j++ < lines[i].length) { + if (lines[i].charAt(j) === " ") space = j; + } + lines[i + 1] = lines[i].substring(space + 1) + (lines[i + 1] || ""); + lines[i] = lines[i].substring(0, space); + } + + return lines.slice(0, 6).join("\n"); +} + var CONSTS = {}; CONSTS.INVOICE_STATUS_DRAFT = 1;