public function create($clientPublicId = 0)
 {
     if (!Utils::isPro()) {
         return Redirect::to('/invoices/create');
     }
     $client = null;
     $invoiceNumber = Auth::user()->account->getNextInvoiceNumber(true);
     $account = Account::with('country')->findOrFail(Auth::user()->account_id);
     if ($clientPublicId) {
         $client = Client::scope($clientPublicId)->firstOrFail();
     }
     $data = array('account' => $account, 'invoice' => null, 'data' => Input::old('data'), 'invoiceNumber' => $invoiceNumber, 'method' => 'POST', 'url' => 'invoices', 'title' => trans('texts.new_quote'), 'client' => $client);
     $data = array_merge($data, self::getViewModel());
     return View::make('invoices.edit', $data);
 }
 /**
  * Stores new account
  *
  */
 public function save($accountGatewayPublicId = false)
 {
     $rules = array();
     $paymentType = Input::get('payment_type_id');
     $gatewayId = Input::get('gateway_id');
     if ($paymentType == PAYMENT_TYPE_PAYPAL) {
         $gatewayId = GATEWAY_PAYPAL_EXPRESS;
     } elseif ($paymentType == PAYMENT_TYPE_BITCOIN) {
         $gatewayId = GATEWAY_BITPAY;
     } elseif ($paymentType == PAYMENT_TYPE_DIRECT_DEBIT) {
         $gatewayId = GATEWAY_GOCARDLESS;
     } elseif ($paymentType == PAYMENT_TYPE_DWOLLA) {
         $gatewayId = GATEWAY_DWOLLA;
     }
     if (!$gatewayId) {
         Session::flash('error', trans('validation.required', ['attribute' => 'gateway']));
         return Redirect::to('gateways/create')->withInput();
     }
     $gateway = Gateway::findOrFail($gatewayId);
     $fields = $gateway->getFields();
     $optional = array_merge(Gateway::$hiddenFields, Gateway::$optionalFields);
     if ($gatewayId == GATEWAY_DWOLLA) {
         $optional = array_merge($optional, ['key', 'secret']);
     } elseif ($gatewayId == GATEWAY_STRIPE) {
         $rules['publishable_key'] = 'required';
     }
     foreach ($fields as $field => $details) {
         if (!in_array($field, $optional)) {
             if (strtolower($gateway->name) == 'beanstream') {
                 if (in_array($field, ['merchant_id', 'passCode'])) {
                     $rules[$gateway->id . '_' . $field] = 'required';
                 }
             } else {
                 $rules[$gateway->id . '_' . $field] = 'required';
             }
         }
     }
     $creditcards = Input::get('creditCardTypes');
     $validator = Validator::make(Input::all(), $rules);
     if ($validator->fails()) {
         return Redirect::to('gateways/create')->withErrors($validator)->withInput();
     } else {
         $account = Account::with('account_gateways')->findOrFail(Auth::user()->account_id);
         $oldConfig = null;
         if ($accountGatewayPublicId) {
             $accountGateway = AccountGateway::scope($accountGatewayPublicId)->firstOrFail();
             $oldConfig = $accountGateway->getConfig();
         } else {
             $accountGateway = AccountGateway::createNew();
             $accountGateway->gateway_id = $gatewayId;
         }
         $config = new stdClass();
         foreach ($fields as $field => $details) {
             $value = trim(Input::get($gateway->id . '_' . $field));
             // if the new value is masked use the original value
             if ($oldConfig && $value && $value === str_repeat('*', strlen($value))) {
                 $value = $oldConfig->{$field};
             }
             if (!$value && ($field == 'testMode' || $field == 'developerMode')) {
                 // do nothing
             } else {
                 $config->{$field} = $value;
             }
         }
         $publishableKey = Input::get('publishable_key');
         if ($publishableKey = str_replace('*', '', $publishableKey)) {
             $config->publishableKey = $publishableKey;
         } elseif ($oldConfig && property_exists($oldConfig, 'publishableKey')) {
             $config->publishableKey = $oldConfig->publishableKey;
         }
         $cardCount = 0;
         if ($creditcards) {
             foreach ($creditcards as $card => $value) {
                 $cardCount += intval($value);
             }
         }
         $accountGateway->accepted_credit_cards = $cardCount;
         $accountGateway->show_address = Input::get('show_address') ? true : false;
         $accountGateway->update_address = Input::get('update_address') ? true : false;
         $accountGateway->setConfig($config);
         if ($accountGatewayPublicId) {
             $accountGateway->save();
         } else {
             $account->account_gateways()->save($accountGateway);
         }
         if (Input::get('token_billing_type_id')) {
             $account->token_billing_type_id = Input::get('token_billing_type_id');
             $account->save();
         }
         if ($accountGatewayPublicId) {
             $message = trans('texts.updated_gateway');
         } else {
             $message = trans('texts.created_gateway');
         }
         Session::flash('message', $message);
         return Redirect::to("gateways/{$accountGateway->public_id}/edit");
     }
 }
 /**
  * @return \Illuminate\Contracts\View\View
  */
 private function showLocalization()
 {
     $data = ['account' => Account::with('users')->findOrFail(Auth::user()->account_id), 'timezones' => Cache::get('timezones'), 'dateFormats' => Cache::get('dateFormats'), 'datetimeFormats' => Cache::get('datetimeFormats'), 'currencies' => Cache::get('currencies'), 'title' => trans('texts.localization'), 'weekdays' => Utils::getTranslatedWeekdayNames()];
     return View::make('accounts.localization', $data);
 }
示例#4
0
 public function createPayment($invitation, $ref, $payerId = null)
 {
     $invoice = $invitation->invoice;
     $accountGateway = $invoice->client->account->getGatewayByType(Session::get('payment_type'));
     // sync pro accounts
     if ($invoice->account->account_key == NINJA_ACCOUNT_KEY && $invoice->amount == PRO_PLAN_PRICE) {
         $account = Account::with('users')->find($invoice->client->public_id);
         if ($account->pro_plan_paid && $account->pro_plan_paid != '0000-00-00') {
             $date = DateTime::createFromFormat('Y-m-d', $account->pro_plan_paid);
             $account->pro_plan_paid = $date->modify('+1 year')->format('Y-m-d');
         } else {
             $account->pro_plan_paid = date_create()->format('Y-m-d');
         }
         $account->save();
         $user = $account->users()->first();
         $this->accountRepo->syncAccounts($user->id, $account->pro_plan_paid);
     }
     $payment = Payment::createNew($invitation);
     $payment->invitation_id = $invitation->id;
     $payment->account_gateway_id = $accountGateway->id;
     $payment->invoice_id = $invoice->id;
     $payment->amount = $invoice->getRequestedAmount();
     $payment->client_id = $invoice->client_id;
     $payment->contact_id = $invitation->contact_id;
     $payment->transaction_reference = $ref;
     $payment->payment_date = date_create()->format('Y-m-d');
     if ($payerId) {
         $payment->payer_id = $payerId;
     }
     $payment->save();
     Event::fire(new InvoicePaid($payment));
     return $payment;
 }
 public function createPayment($ref = false, $paymentMethod = null)
 {
     $invitation = $this->invitation;
     $invoice = $this->invoice();
     $payment = Payment::createNew($invitation);
     $payment->invitation_id = $invitation->id;
     $payment->account_gateway_id = $this->accountGateway->id;
     $payment->invoice_id = $invoice->id;
     $payment->amount = $invoice->getRequestedAmount();
     $payment->client_id = $invoice->client_id;
     $payment->contact_id = $invitation->contact_id;
     $payment->transaction_reference = $ref;
     $payment->payment_date = date_create()->format('Y-m-d');
     $payment->ip = Request::ip();
     $payment = $this->creatingPayment($payment, $paymentMethod);
     if ($paymentMethod) {
         $payment->last4 = $paymentMethod->last4;
         $payment->expiration = $paymentMethod->expiration;
         $payment->routing_number = $paymentMethod->routing_number;
         $payment->payment_type_id = $paymentMethod->payment_type_id;
         $payment->email = $paymentMethod->email;
         $payment->bank_name = $paymentMethod->bank_name;
         $payment->payment_method_id = $paymentMethod->id;
     }
     $payment->save();
     // TODO move this code
     // enable pro plan for hosted users
     if ($invoice->account->account_key == NINJA_ACCOUNT_KEY) {
         foreach ($invoice->invoice_items as $invoice_item) {
             // Hacky, but invoices don't have meta fields to allow us to store this easily
             if (1 == preg_match('/^Plan - (.+) \\((.+)\\)$/', $invoice_item->product_key, $matches)) {
                 $plan = strtolower($matches[1]);
                 $term = strtolower($matches[2]);
                 $price = $invoice_item->cost;
                 if ($plan == PLAN_ENTERPRISE) {
                     if (count($matches)) {
                         $numUsers = $matches[1];
                     } else {
                         $numUsers = 5;
                     }
                 } else {
                     $numUsers = 1;
                 }
             }
         }
         if (!empty($plan)) {
             $account = Account::with('users')->find($invoice->client->public_id);
             $company = $account->company;
             if ($company->plan != $plan || DateTime::createFromFormat('Y-m-d', $account->company->plan_expires) >= date_create('-7 days')) {
                 // Either this is a different plan, or the subscription expired more than a week ago
                 // Reset any grandfathering
                 $company->plan_started = date_create()->format('Y-m-d');
             }
             if ($company->plan == $plan && $company->plan_term == $term && DateTime::createFromFormat('Y-m-d', $company->plan_expires) >= date_create()) {
                 // This is a renewal; mark it paid as of when this term expires
                 $company->plan_paid = $company->plan_expires;
             } else {
                 $company->plan_paid = date_create()->format('Y-m-d');
             }
             $company->payment_id = $payment->id;
             $company->plan = $plan;
             $company->plan_term = $term;
             $company->plan_price = $price;
             $company->num_users = $numUsers;
             $company->plan_expires = DateTime::createFromFormat('Y-m-d', $account->company->plan_paid)->modify($term == PLAN_TERM_MONTHLY ? '+1 month' : '+1 year')->format('Y-m-d');
             $company->save();
         }
     }
     return $payment;
 }
 public function showSection($section = ACCOUNT_DETAILS, $subSection = false)
 {
     if ($section == ACCOUNT_DETAILS) {
         $primaryUser = Auth::user()->account->users()->orderBy('id')->first();
         $data = ['account' => Account::with('users')->findOrFail(Auth::user()->account_id), 'countries' => Cache::get('countries'), 'sizes' => Cache::get('sizes'), 'industries' => Cache::get('industries'), 'timezones' => Cache::get('timezones'), 'dateFormats' => Cache::get('dateFormats'), 'datetimeFormats' => Cache::get('datetimeFormats'), 'currencies' => Cache::get('currencies'), 'languages' => Cache::get('languages'), 'showUser' => Auth::user()->id === $primaryUser->id, 'title' => trans('texts.company_details'), 'primaryUser' => $primaryUser];
         return View::make('accounts.details', $data);
     } elseif ($section == ACCOUNT_PAYMENTS) {
         $account = Auth::user()->account;
         $account->load('account_gateways');
         $count = count($account->account_gateways);
         if ($count == 0) {
             return Redirect::to('gateways/create');
         } else {
             return View::make('accounts.payments', ['showAdd' => $count < 3, 'title' => trans('texts.online_payments')]);
         }
     } elseif ($section == ACCOUNT_NOTIFICATIONS) {
         $data = ['account' => Account::with('users')->findOrFail(Auth::user()->account_id), 'title' => trans('texts.notifications')];
         return View::make('accounts.notifications', $data);
     } elseif ($section == ACCOUNT_IMPORT_EXPORT) {
         return View::make('accounts.import_export', ['title' => trans('texts.import_export')]);
     } elseif ($section == ACCOUNT_ADVANCED_SETTINGS) {
         $account = Auth::user()->account->load('country');
         $data = ['account' => $account, 'feature' => $subSection, 'title' => trans('texts.invoice_settings')];
         if ($subSection == ACCOUNT_INVOICE_DESIGN || $subSection == ACCOUNT_CUSTOMIZE_DESIGN) {
             $invoice = new stdClass();
             $client = new stdClass();
             $contact = new stdClass();
             $invoiceItem = new stdClass();
             $client->name = 'Sample Client';
             $client->address1 = '';
             $client->city = '';
             $client->state = '';
             $client->postal_code = '';
             $client->work_phone = '';
             $client->work_email = '';
             $invoice->invoice_number = $account->getNextInvoiceNumber();
             $invoice->invoice_date = Utils::fromSqlDate(date('Y-m-d'));
             $invoice->account = json_decode($account->toJson());
             $invoice->amount = $invoice->balance = 100;
             $invoice->terms = trim($account->invoice_terms);
             $invoice->invoice_footer = trim($account->invoice_footer);
             $contact->email = '*****@*****.**';
             $client->contacts = [$contact];
             $invoiceItem->cost = 100;
             $invoiceItem->qty = 1;
             $invoiceItem->notes = 'Notes';
             $invoiceItem->product_key = 'Item';
             $invoice->client = $client;
             $invoice->invoice_items = [$invoiceItem];
             $data['account'] = $account;
             $data['invoice'] = $invoice;
             $data['invoiceLabels'] = json_decode($account->invoice_labels) ?: [];
             $data['title'] = trans('texts.invoice_design');
             $data['invoiceDesigns'] = InvoiceDesign::getDesigns($subSection == ACCOUNT_CUSTOMIZE_DESIGN);
             $design = false;
             foreach ($data['invoiceDesigns'] as $item) {
                 if ($item->id == $account->invoice_design_id) {
                     $design = $item->javascript;
                     break;
                 }
             }
             if ($subSection == ACCOUNT_CUSTOMIZE_DESIGN) {
                 $data['customDesign'] = $account->custom_design && !$design ? $account->custom_design : $design;
             }
         } else {
             if ($subSection == ACCOUNT_EMAIL_TEMPLATES) {
                 $data['invoiceEmail'] = $account->getEmailTemplate(ENTITY_INVOICE);
                 $data['quoteEmail'] = $account->getEmailTemplate(ENTITY_QUOTE);
                 $data['paymentEmail'] = $account->getEmailTemplate(ENTITY_PAYMENT);
                 $data['emailFooter'] = $account->getEmailFooter();
                 $data['title'] = trans('texts.email_templates');
             } else {
                 if ($subSection == ACCOUNT_USER_MANAGEMENT) {
                     $data['title'] = trans('texts.users_and_tokens');
                 }
             }
         }
         return View::make("accounts.{$subSection}", $data);
     } elseif ($section == ACCOUNT_PRODUCTS) {
         $data = ['account' => Auth::user()->account, 'title' => trans('texts.product_library')];
         return View::make('accounts.products', $data);
     }
 }
示例#7
0
 public function create($clientPublicId = 0)
 {
     $client = null;
     $invoiceNumber = Auth::user()->account->getNextInvoiceNumber();
     $account = Account::with('country')->findOrFail(Auth::user()->account_id);
     if ($clientPublicId) {
         $client = Client::scope($clientPublicId)->firstOrFail();
     }
     $data = array('entityType' => ENTITY_INVOICE, 'account' => $account, 'invoice' => null, 'data' => Input::old('data'), 'invoiceNumber' => $invoiceNumber, 'method' => 'POST', 'url' => 'invoices', 'title' => trans('texts.new_invoice'), 'client' => $client, 'tasks' => Session::get('tasks') ? json_encode(Session::get('tasks')) : null);
     $data = array_merge($data, self::getViewModel());
     return View::make('invoices.edit', $data);
 }
 public function showSection($section = ACCOUNT_DETAILS, $subSection = false)
 {
     if ($section == ACCOUNT_DETAILS) {
         $data = ['account' => Account::with('users')->findOrFail(Auth::user()->account_id), 'countries' => Cache::get('countries'), 'sizes' => Cache::get('sizes'), 'industries' => Cache::get('industries'), 'timezones' => Cache::get('timezones'), 'dateFormats' => Cache::get('dateFormats'), 'datetimeFormats' => Cache::get('datetimeFormats'), 'currencies' => Cache::get('currencies'), 'languages' => Cache::get('languages'), 'showUser' => Auth::user()->id === Auth::user()->account->users()->first()->id];
         return View::make('accounts.details', $data);
     } elseif ($section == ACCOUNT_PAYMENTS) {
         $account = Auth::user()->account;
         $account->load('account_gateways');
         $count = count($account->account_gateways);
         if ($count == 0) {
             return Redirect::to('gateways/create');
         } else {
             return View::make('accounts.payments', ['showAdd' => $count < 3]);
         }
     } elseif ($section == ACCOUNT_NOTIFICATIONS) {
         $data = ['account' => Account::with('users')->findOrFail(Auth::user()->account_id)];
         return View::make('accounts.notifications', $data);
     } elseif ($section == ACCOUNT_IMPORT_EXPORT) {
         return View::make('accounts.import_export');
     } elseif ($section == ACCOUNT_ADVANCED_SETTINGS) {
         $account = Auth::user()->account;
         $data = ['account' => $account, 'feature' => $subSection];
         if ($subSection == ACCOUNT_INVOICE_DESIGN) {
             $invoice = new stdClass();
             $client = new stdClass();
             $invoiceItem = new stdClass();
             $client->name = 'Sample Client';
             $client->address1 = '';
             $client->city = '';
             $client->state = '';
             $client->postal_code = '';
             $client->work_phone = '';
             $client->work_email = '';
             $invoice->invoice_number = Auth::user()->account->getNextInvoiceNumber();
             $invoice->invoice_date = date_create()->format('Y-m-d');
             $invoice->account = json_decode(Auth::user()->account->toJson());
             $invoice->amount = $invoice->balance = 100;
             $invoiceItem->cost = 100;
             $invoiceItem->qty = 1;
             $invoiceItem->notes = 'Notes';
             $invoiceItem->product_key = 'Item';
             $invoice->client = $client;
             $invoice->invoice_items = [$invoiceItem];
             $data['invoice'] = $invoice;
             $data['invoiceDesigns'] = InvoiceDesign::availableDesigns();
         } else {
             if ($subSection == ACCOUNT_EMAIL_TEMPLATES) {
                 $data['invoiceEmail'] = $account->getEmailTemplate(ENTITY_INVOICE);
                 $data['quoteEmail'] = $account->getEmailTemplate(ENTITY_QUOTE);
                 $data['paymentEmail'] = $account->getEmailTemplate(ENTITY_PAYMENT);
                 $data['emailFooter'] = $account->getEmailFooter();
             }
         }
         return View::make("accounts.{$subSection}", $data);
     } elseif ($section == ACCOUNT_PRODUCTS) {
         $data = ['account' => Auth::user()->account];
         return View::make('accounts.products', $data);
     }
 }
 public function createPayment($invitation, $accountGateway, $ref, $payerId = null)
 {
     $invoice = $invitation->invoice;
     // enable pro plan for hosted users
     if ($invoice->account->account_key == NINJA_ACCOUNT_KEY && $invoice->amount == PRO_PLAN_PRICE) {
         $account = Account::with('users')->find($invoice->client->public_id);
         $account->pro_plan_paid = $account->getRenewalDate();
         $account->save();
         // sync pro accounts
         $user = $account->users()->first();
         $this->accountRepo->syncAccounts($user->id, $account->pro_plan_paid);
     }
     $payment = Payment::createNew($invitation);
     $payment->invitation_id = $invitation->id;
     $payment->account_gateway_id = $accountGateway->id;
     $payment->invoice_id = $invoice->id;
     $payment->amount = $invoice->getRequestedAmount();
     $payment->client_id = $invoice->client_id;
     $payment->contact_id = $invitation->contact_id;
     $payment->transaction_reference = $ref;
     $payment->payment_date = date_create()->format('Y-m-d');
     if ($payerId) {
         $payment->payer_id = $payerId;
     }
     $payment->save();
     return $payment;
 }
 private function executeRoleChange(Request $req, $email)
 {
     return DB::transaction(function () use($email, $req) {
         $acc = Account::with("roles")->where("email", $email)->get()->first();
         if (!isset($acc)) {
             return response()->json(["message" => "user_not_found"], 400);
         }
         $accessibleRoleNames = $this->manageableRoleNamesForUser();
         if ($req->has("add")) {
             $allAdd = $req->all()["add"];
             foreach ($allAdd as $rname) {
                 if (!in_array($rname, $accessibleRoleNames)) {
                     throw new BadRequestHttpException("role_not_accessible");
                 }
             }
             //Need to be careful not to add roles that are already in
             //as this causes primary key violations.
             $accRoleNames = array_map(function ($role) {
                 return $role['name'];
             }, $acc->roles->toArray());
             $add = array_filter($allAdd, function ($name) use($accRoleNames) {
                 return !in_array($name, $accRoleNames);
             });
             $okay = $this->doAccountRoleChange($add, function ($roles) use($acc) {
                 $acc->attachRoles($roles);
             });
         }
         if ($req->has("remove")) {
             $remove = $req->all()["remove"];
             foreach ($remove as $rname) {
                 if (!in_array($rname, $accessibleRoleNames)) {
                     throw new BadRequestHttpException("role_not_accessible");
                 }
             }
             $okay = $this->doAccountRoleChange($remove, function ($roles) use($acc) {
                 $acc->detachRoles($roles);
             });
         }
         if (isset($okay) && !$okay) {
             throw new BadRequestHttpException("role_not_found");
         }
         return response()->json(["message" => "roles_patched"]);
     });
 }
 public function createPayment($invitation, $accountGateway, $ref, $payerId = null)
 {
     $invoice = $invitation->invoice;
     $payment = Payment::createNew($invitation);
     $payment->invitation_id = $invitation->id;
     $payment->account_gateway_id = $accountGateway->id;
     $payment->invoice_id = $invoice->id;
     $payment->amount = $invoice->getRequestedAmount();
     $payment->client_id = $invoice->client_id;
     $payment->contact_id = $invitation->contact_id;
     $payment->transaction_reference = $ref;
     $payment->payment_date = date_create()->format('Y-m-d');
     if ($payerId) {
         $payment->payer_id = $payerId;
     }
     $payment->save();
     // enable pro plan for hosted users
     if ($invoice->account->account_key == NINJA_ACCOUNT_KEY) {
         foreach ($invoice->invoice_items as $invoice_item) {
             // Hacky, but invoices don't have meta fields to allow us to store this easily
             if (1 == preg_match('/^Plan - (.+) \\((.+)\\)$/', $invoice_item->product_key, $matches)) {
                 $plan = strtolower($matches[1]);
                 $term = strtolower($matches[2]);
             } elseif ($invoice_item->product_key == 'Pending Monthly') {
                 $pending_monthly = true;
             }
         }
         if (!empty($plan)) {
             $account = Account::with('users')->find($invoice->client->public_id);
             if ($account->company->plan != $plan || DateTime::createFromFormat('Y-m-d', $account->company->plan_expires) >= date_create('-7 days')) {
                 // Either this is a different plan, or the subscription expired more than a week ago
                 // Reset any grandfathering
                 $account->company->plan_started = date_create()->format('Y-m-d');
             }
             if ($account->company->plan == $plan && $account->company->plan_term == $term && DateTime::createFromFormat('Y-m-d', $account->company->plan_expires) >= date_create()) {
                 // This is a renewal; mark it paid as of when this term expires
                 $account->company->plan_paid = $account->company->plan_expires;
             } else {
                 $account->company->plan_paid = date_create()->format('Y-m-d');
             }
             $account->company->payment_id = $payment->id;
             $account->company->plan = $plan;
             $account->company->plan_term = $term;
             $account->company->plan_expires = DateTime::createFromFormat('Y-m-d', $account->company->plan_paid)->modify($term == PLAN_TERM_MONTHLY ? '+1 month' : '+1 year')->format('Y-m-d');
             if (!empty($pending_monthly)) {
                 $account->company->pending_plan = $plan;
                 $account->company->pending_term = PLAN_TERM_MONTHLY;
             } else {
                 $account->company->pending_plan = null;
                 $account->company->pending_term = null;
             }
             $account->company->save();
         }
     }
     return $payment;
 }
 /**
  * Stores new account
  *
  */
 public function save($accountGatewayPublicId = false)
 {
     $gatewayId = Input::get('primary_gateway_id') ?: Input::get('secondary_gateway_id');
     $gateway = Gateway::findOrFail($gatewayId);
     $rules = [];
     $fields = $gateway->getFields();
     $optional = array_merge(Gateway::$hiddenFields, Gateway::$optionalFields);
     if ($gatewayId == GATEWAY_DWOLLA) {
         $optional = array_merge($optional, ['key', 'secret']);
     } elseif ($gatewayId == GATEWAY_STRIPE) {
         if (Utils::isNinjaDev()) {
             // do nothing - we're unable to acceptance test with StripeJS
         } else {
             $rules['publishable_key'] = 'required';
             $rules['enable_ach'] = 'boolean';
         }
     }
     if ($gatewayId != GATEWAY_WEPAY) {
         foreach ($fields as $field => $details) {
             if (!in_array($field, $optional)) {
                 if (strtolower($gateway->name) == 'beanstream') {
                     if (in_array($field, ['merchant_id', 'passCode'])) {
                         $rules[$gateway->id . '_' . $field] = 'required';
                     }
                 } else {
                     $rules[$gateway->id . '_' . $field] = 'required';
                 }
             }
         }
     }
     $creditcards = Input::get('creditCardTypes');
     $validator = Validator::make(Input::all(), $rules);
     if ($validator->fails()) {
         return Redirect::to('gateways/create?other_providers=' . ($gatewayId == GATEWAY_WEPAY ? 'false' : 'true'))->withErrors($validator)->withInput();
     } else {
         $account = Account::with('account_gateways')->findOrFail(Auth::user()->account_id);
         $oldConfig = null;
         if ($accountGatewayPublicId) {
             $accountGateway = AccountGateway::scope($accountGatewayPublicId)->firstOrFail();
             $oldConfig = $accountGateway->getConfig();
         } else {
             // check they don't already have an active gateway for this provider
             // TODO complete this
             $accountGateway = AccountGateway::scope()->whereGatewayId($gatewayId)->first();
             if ($accountGateway) {
                 Session::flash('error', trans('texts.gateway_exists'));
                 return Redirect::to("gateways/{$accountGateway->public_id}/edit");
             }
             $accountGateway = AccountGateway::createNew();
             $accountGateway->gateway_id = $gatewayId;
             if ($gatewayId == GATEWAY_WEPAY) {
                 if (!$this->setupWePay($accountGateway, $wepayResponse)) {
                     return $wepayResponse;
                 }
                 $oldConfig = $accountGateway->getConfig();
             }
         }
         $config = new stdClass();
         if ($gatewayId != GATEWAY_WEPAY) {
             foreach ($fields as $field => $details) {
                 $value = trim(Input::get($gateway->id . '_' . $field));
                 // if the new value is masked use the original value
                 if ($oldConfig && $value && $value === str_repeat('*', strlen($value))) {
                     $value = $oldConfig->{$field};
                 }
                 if (!$value && ($field == 'testMode' || $field == 'developerMode')) {
                     // do nothing
                 } else {
                     $config->{$field} = $value;
                 }
             }
         } elseif ($oldConfig) {
             $config = clone $oldConfig;
         }
         $publishableKey = Input::get('publishable_key');
         if ($publishableKey = str_replace('*', '', $publishableKey)) {
             $config->publishableKey = $publishableKey;
         } elseif ($oldConfig && property_exists($oldConfig, 'publishableKey')) {
             $config->publishableKey = $oldConfig->publishableKey;
         }
         $plaidClientId = Input::get('plaid_client_id');
         if ($plaidClientId = str_replace('*', '', $plaidClientId)) {
             $config->plaidClientId = $plaidClientId;
         } elseif ($oldConfig && property_exists($oldConfig, 'plaidClientId')) {
             $config->plaidClientId = $oldConfig->plaidClientId;
         }
         $plaidSecret = Input::get('plaid_secret');
         if ($plaidSecret = str_replace('*', '', $plaidSecret)) {
             $config->plaidSecret = $plaidSecret;
         } elseif ($oldConfig && property_exists($oldConfig, 'plaidSecret')) {
             $config->plaidSecret = $oldConfig->plaidSecret;
         }
         $plaidPublicKey = Input::get('plaid_public_key');
         if ($plaidPublicKey = str_replace('*', '', $plaidPublicKey)) {
             $config->plaidPublicKey = $plaidPublicKey;
         } elseif ($oldConfig && property_exists($oldConfig, 'plaidPublicKey')) {
             $config->plaidPublicKey = $oldConfig->plaidPublicKey;
         }
         if ($gatewayId == GATEWAY_STRIPE || $gatewayId == GATEWAY_WEPAY) {
             $config->enableAch = boolval(Input::get('enable_ach'));
         }
         if ($gatewayId == GATEWAY_BRAINTREE) {
             $config->enablePayPal = boolval(Input::get('enable_paypal'));
         }
         $cardCount = 0;
         if ($creditcards) {
             foreach ($creditcards as $card => $value) {
                 $cardCount += intval($value);
             }
         }
         $accountGateway->accepted_credit_cards = $cardCount;
         $accountGateway->show_address = Input::get('show_address') ? true : false;
         $accountGateway->update_address = Input::get('update_address') ? true : false;
         $accountGateway->setConfig($config);
         if ($accountGatewayPublicId) {
             $accountGateway->save();
         } else {
             $account->account_gateways()->save($accountGateway);
         }
         if (isset($wepayResponse)) {
             return $wepayResponse;
         } else {
             if ($accountGatewayPublicId) {
                 $message = trans('texts.updated_gateway');
             } else {
                 $message = trans('texts.created_gateway');
             }
             Session::flash('message', $message);
             return Redirect::to("gateways/{$accountGateway->public_id}/edit");
         }
     }
 }
 /**
  * Stores new account
  *
  */
 public function save($accountGatewayPublicId = false)
 {
     $rules = array();
     $paymentType = Input::get('payment_type_id');
     $gatewayId = Input::get('gateway_id');
     if ($paymentType == PAYMENT_TYPE_PAYPAL) {
         $gatewayId = GATEWAY_PAYPAL_EXPRESS;
     } elseif ($paymentType == PAYMENT_TYPE_BITCOIN) {
         $gatewayId = GATEWAY_BITPAY;
     }
     if (!$gatewayId) {
         Session::flash('error', trans('validation.required', ['attribute' => 'gateway']));
         return Redirect::to('gateways/create')->withInput();
     }
     $gateway = Gateway::findOrFail($gatewayId);
     $fields = $gateway->getFields();
     foreach ($fields as $field => $details) {
         if (!in_array($field, ['testMode', 'developerMode', 'headerImageUrl', 'solutionType', 'landingPage', 'brandName', 'logoImageUrl', 'borderColor'])) {
             if (strtolower($gateway->name) == 'beanstream') {
                 if (in_array($field, ['merchant_id', 'passCode'])) {
                     $rules[$gateway->id . '_' . $field] = 'required';
                 }
             } else {
                 $rules[$gateway->id . '_' . $field] = 'required';
             }
         }
     }
     $creditcards = Input::get('creditCardTypes');
     $validator = Validator::make(Input::all(), $rules);
     if ($validator->fails()) {
         return Redirect::to('gateways/create')->withErrors($validator)->withInput();
     } else {
         $account = Account::with('account_gateways')->findOrFail(Auth::user()->account_id);
         $oldConfig = null;
         if ($accountGatewayPublicId) {
             $accountGateway = AccountGateway::scope($accountGatewayPublicId)->firstOrFail();
             $oldConfig = json_decode($accountGateway->config);
         } else {
             $accountGateway = AccountGateway::createNew();
             $accountGateway->gateway_id = $gatewayId;
         }
         $config = new stdClass();
         foreach ($fields as $field => $details) {
             $value = trim(Input::get($gateway->id . '_' . $field));
             // if the new value is masked use the original value
             if ($value && $value === str_repeat('*', strlen($value))) {
                 $value = $oldConfig->{$field};
             }
             if (!$value && ($field == 'testMode' || $field == 'developerMode')) {
                 // do nothing
             } else {
                 $config->{$field} = $value;
             }
         }
         $cardCount = 0;
         if ($creditcards) {
             foreach ($creditcards as $card => $value) {
                 $cardCount += intval($value);
             }
         }
         $accountGateway->accepted_credit_cards = $cardCount;
         $accountGateway->config = json_encode($config);
         if ($accountGatewayPublicId) {
             $accountGateway->save();
         } else {
             $account->account_gateways()->save($accountGateway);
         }
         if (Input::get('token_billing_type_id')) {
             $account->token_billing_type_id = Input::get('token_billing_type_id');
             $account->save();
         }
         if ($accountGatewayPublicId) {
             $message = trans('texts.updated_gateway');
         } else {
             $message = trans('texts.created_gateway');
         }
         Session::flash('message', $message);
         return Redirect::to('company/payments');
     }
 }