public static function logToReceiptRecords($f) { $file_db = new PDO('sqlite:' . $f); $file_db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $result = $file_db->query('SELECT * FROM transactions;'); $receiptNO = ""; foreach ($result as $m) { $receiptNo = $m["receiptNo"]; } $receiptlines = ReceiptLine::where('receiptNo', $receiptNo)->get(); foreach ($receiptlines as $receiptline) { ReceiptLine::destroy($receiptline->id); } $receiptRecords = Receiptrecord::where(['receiptNo' => $receiptNo, 'progress' => '提供済み'])->get(); foreach ($receiptRecords as $receiptRecord) { $receiptRecord->payment_id = $m['payment_id']; $receiptRecord->progress = "支払い済み"; $receiptRecord->save(); } $file_db = new PDO('sqlite:' . $f); $file_db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $result = $file_db->query('SELECT * FROM payments;'); foreach ($result as $m) { $payment = new Payment(); $payment->price = $m["price"]; $payment->payment = $m["payment"]; $payment->changes = $m["changes"]; $payment->time = $m["time"]; $payment->uuid = $m["uuid"]; $payment->shopName = $m["shopName"]; $payment->employeeName = $m["employeeName"]; $payment->save(); } // unlink($f); }
public function postPayment() { // Step 1: Check if the request contains required fields if (!$this->validatePaymentRequest()) { $this->response->addMessage('Invalid Payment Request.'); return $this->output(); } // Step 2: Validation passed -> Create new payment $payment = new \Payment(); $payment->payment_amount_ex_vat = $this->data['payment_amount_ex_vat']; $payment->vat_amount = $this->data['vat_amount']; $payment->gratuity_amount = isset($this->data['gratuity_amount']) ? $this->data['gratuity_amount'] : 0; $payment->branch_id = $this->data['branch_id']; $payment->payment_vendor_id = $this->data['payment_vendor_id']; $payment->employee_id = $this->data['employee_id']; $payment->order_id = $this->data['order_id']; $payment->payment_taken_at = $this->data['payment_taken_at']; $payment->terminal_id = $this->data['terminal_id']; $payment->created_at = \Carbon\Carbon::now(); // Step 3: Save the payment into the database if ($payment->save()) { $this->response->setSuccess(1); $this->response->setPaymentId($payment->id); return $this->output(); } }
/** * @param Response $response * @return OrderInterface */ public function bankReturn(Response $response) { $this->status = $response->isSuccessful() ? 'paid' : 'error'; $this->save(); // log bank return $log = new Payment(['user_id' => $this->user_id, 'order_id' => $this->id, 'bank_code' => $response->getAdapter()->adapterTag, 'amount' => $this->due_amount, 'status' => $this->status, 'data_dump' => $response->__toString(), 'created' => new Expression('NOW()')]); $log->save(); return $this; }
public static function add($input) { // init $total_donation = 0; $currency = 'IDR'; // get payment ids $donation_ids = explode(',', $input['donation_ids']); unset($input['donation_ids']); // compare total of donation with total of payment $donations = Donation::whereIn('id', $donation_ids)->get(); foreach ($donations as $donation) { $total_donation += $donation->total; $currency = $donation->currency; } if ($total_donation > $input['total']) { return array('success' => false, 'errors' => array('Total yang Anda inputkan tidak sama dengan total donasi Anda. Jika Anda ingin melakukan perubahan donasi silahkan batalkan donasi sebelumnya dan lakukan donasi kembali.')); } else { if ($currency != $input['currency']) { return array('success' => false, 'errors' => array('Mata uang yang Anda inputkan tidak sama dengan mata uang donasi Anda. Jika Anda ingin melakukan perubahan donasi silahkan batalkan donasi sebelumnya dan lakukan donasi kembali.')); } } // set rules $rules = array('user_id' => 'required|exists:users,id', 'currency' => 'required', 'transferred_at' => 'required|numeric', 'total' => 'required|numeric', 'to_bank' => 'required|max:100', 'bank_name' => 'required|max:40', 'bank_account' => 'required|max:25', 'bank_account_name' => 'required|max:40', 'message' => ''); $validator = Validator::make($input, $rules); if ($validator->fails()) { // if fails return array('success' => false, 'errors' => $validator->errors()->all()); } else { // save to database $payment = new Payment(); // set input foreach ($input as $field => $value) { $payment->{$field} = $value; } $payment->status = 0; // new (waiting approval) $payment->save(); // update donation foreach ($donation_ids as $donation_id) { $donation = Donation::find($donation_id); $donation->payment_id = $payment->id; $donation->save(); } // send email $payment = Payment::with(array('user', 'donations'))->find($payment->id); // set type for each donation foreach ($payment->donations as $donation) { $donation->setAppends(array('type')); } // send email to donor Newsletter::addPaymentNewsletter($payment); return array('success' => true, 'data' => $payment); } }
/** * Creates a new model. * If creation is successful, the browser will be redirected to the 'view' page. */ public function actionCreate() { $model = new Payment(); // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if (isset($_POST['Payment'])) { $model->attributes = $_POST['Payment']; if ($model->save()) { $this->redirect(array('view', 'id' => $model->payment_id)); } } $this->render('create', array('model' => $model)); }
public function getPaymentUrl($invoice_id, $options = array()) { $invoice = Invoice::model()->findByPk($invoice_id); if ($invoice == null) { return false; } if ($invoice->customer_id != Yii::app()->user->getId()) { return false; } $amount = $invoice->amount; $amount = $amount * 100; $merchantSession = urlencode(time() . '-' . $this->makePaystationSessionID(8, 8)); $this->setSessionId($merchantSession); $this->merchantRef = Yii::app()->user->getId(); $paystationUrl = "https://www.paystation.co.nz/direct/paystation.dll"; $paystationParameters = "paystation=_empty&pstn_pi=" . $this->paystationId . "&pstn_gi=" . $this->gatewayId . "&pstn_ms=" . $merchantSession . "&pstn_mr=" . $this->merchantRef . "&pstn_am=" . $amount . "&pstn_nr=t"; if ($this->testMode == 'true') { $paystationParameters = $paystationParameters . "&pstn_tm=t"; } foreach ($options as $key => $value) { $paystationParameters .= "&" . $key . "=" . $value; } $result = $this->doPostRequest($paystationUrl, $paystationParameters); // handle result $xmlData = new SimpleXMLElement($result); $digitalOrder = $xmlData->DigitalOrder; // The URL that we re-direct the customer too. $transactionID = $xmlData->PaystationTransactionID; //The transaction ID Paystation has just created. $PaymentRequestTime = $xmlData->PaymentRequestTime; // The time that the transaction was initiated $DigitalOrderTime = $xmlData->DigitalOrderTime; //The time Paystation responds // redirect if ($digitalOrder) { $payment = new Payment(); $payment->transaction_id = $transactionID; $payment->session_id = $merchantSession; $payment->order_time = $DigitalOrderTime; $payment->merchant_ref = $this->merchantRef; $payment->customer_id = Yii::app()->user->getId(); $payment->invoice_id = $invoice_id; $payment->save(false); return $digitalOrder; } else { //echo "<pre>".htmlentities($result)."</pre>"; //no digitalorder variable, so initiation must have failed. Print out xml packet for debugging purposes return false; } return false; }
public function actionCreate() { $model = new Payment(); if (isset($_POST['Payment'])) { $model->setAttributes($_POST['Payment']); if ($model->save()) { if (Yii::app()->getRequest()->getIsAjaxRequest()) { Yii::app()->end(); } else { $this->redirect(array('view', 'id' => $model->payment_id)); } } } $this->render('create', array('model' => $model)); }
/** * Store a newly created payment in storage. * * @return Response */ public function store() { $validator = Validator::make($data = Input::all(), Payment::$rules, Payment::$messages); if ($validator->fails()) { return Redirect::back()->withErrors($validator)->withInput(); } $payment = new Payment(); $payment->erporder_id = Input::get('order'); $payment->amount_paid = Input::get('amount'); $payment->receipt_no = Input::get('receipt'); $payment->received_by = Input::get('received_by'); $payment->date = date("Y-m-d", strtotime(Input::get('pay_date'))); $payment->save(); return Redirect::route('payments.index')->withFlashMessage('Payment successfully created!'); }
public function actionAdd() { if (empty($_POST)) { $viewData = array(); $this->render('add', $viewData); exit; } $res = array('statusCode' => 200, 'message' => '添加成功!'); try { $imageConfig = Yii::app()->params['image']['bank']; if (empty($imageConfig)) { throw new exception('缺少商品图片配置'); } $image = CUploadedFile::getInstanceByName('payment_logo'); $imageNamePath = ''; if ($image) { $imageName = date('YmdHis') . rand(1, 1000); $imageNamePath = $imageConfig['path'] . $imageName . '.' . $image->getExtensionName(); $image->saveAs($imageNamePath, true); } $payment = new Payment(); $payment->pay_code = $_POST['pay_code']; $payment->pay_name = $_POST['pay_name']; if ($imageNamePath) { $payment->payment_logo = str_replace(ROOT_PATH . '/images/bank/', '', $imageNamePath); } $payment->keya = $_POST['keya']; $payment->keyb = $_POST['keyb']; $payment->is_valid = $_POST['is_valid']; $payment->is_plat = $_POST['is_plat']; $payment->sort = $_POST['sort']; $flag = $payment->save(); if (!$flag) { throw new exception('添加失败'); } } catch (Exception $e) { $res['statusCode'] = 300; $res['message'] = '失败【' . $e->getMessage() . '】'; } $res['navTabId'] = 'paymentList'; $res['callbackType'] = 'closeCurrent'; $res['forwardUrl'] = '/manage/payment/index'; $this->ajaxDwzReturn($res); }
function testDestroyAssociatedRecords() { $c = new Company(); $c->set(array('name' => 'destroy_test')); $c->save(); $p = new Project(); $p->set(array('company_id' => $c->id, 'name' => 'destroy_project_test')); $p->save(); $e = new Estimate(); $e->set(array('project_id' => $p->id, 'name' => 'destroy_estimate_test')); $e->save(); $h = new Hour(); $h->set(array('estimate_id' => $e->id, 'name' => 'destroy_hour_test')); $h->save(); $ch = new Charge(); $ch->set(array('company_id' => $c->id, 'name' => 'destroy_charge_test')); $ch->save(); $con = new SupportContract(); $con->set(array('company_id' => $c->id, 'name' => 'destroy_contract_test')); $con->save(); $sup_hr = new Hour(); $sup_hr->set(array('support_contract_id' => $con->id, 'description' => 'destroy_support_hour_test')); $sup_hr->save(); $pay = new Payment(); $pay->set(array('company_id' => $c->id, 'name' => 'destroy_payment_test')); $pay->save(); $deleted_items = array('company' => $c->id, 'project' => $p->id, 'estimate' => $e->id, 'hour' => $h->id, 'support_hour' => $sup_hr->id, 'charge' => $ch->id, 'support_contract' => $con->id, 'payment' => $pay->id); $c->destroyAssociatedRecords(); $c->delete(); $dbcon = AMP::getDb(); foreach ($deleted_items as $table => $id) { if ($table == 'support_hour') { $table = 'hour'; } $sql = 'SELECT * FROM ' . $table . ' WHERE id = ' . $id; if ($records = $dbcon->Execute($sql)) { $this->assertEqual($records->RecordCount(), 0, "{$table} not deleted correctly: %s"); } else { trigger_error($dbcon->ErrorMsg()); } } }
public function actionCreate() { $model = new Payment(); if (Yii::app()->getRequest()->getIsPostRequest() && isset($_POST['Payment'])) { $model->setAttributes(Yii::app()->getRequest()->getPost('Payment')); $model->setPaymentSystemSettings(Yii::app()->getRequest()->getPost('PaymentSettings', [])); if ($model->save()) { Yii::app()->user->setFlash(yupe\widgets\YFlashMessages::SUCCESS_MESSAGE, Yii::t('PaymentModule.payment', 'Record was created!')); if (!isset($_POST['submit-type'])) { $this->redirect(['update', 'id' => $model->id]); } else { $this->redirect([$_POST['submit-type']]); } } } //@TODO вынести в метод модели $criteria = new CDbCriteria(); $criteria->select = new CDbExpression('MAX(position) as position'); $max = $model->find($criteria); $model->position = $max->position + 1; $this->render('create', ['model' => $model]); }
/** * Store a newly created resource in storage. * POST /accountreceivables * * @return Response */ public function store() { $input = Input::all(); $v = Validator::make(Input::All(), array('invoiceID' => 'required|max:50|', 'houseID' => 'required', 'amount' => 'required|min:2', 'paymenttype' => 'required', 'amountpayed' => 'required', 'paymenttyperef' => 'required')); if ($v->passes()) { $gamount = Input::get('amount'); $gpayed = Input::get('amountpayed'); $initpaid = Input::get('initpaid'); $id = Input::get('invoiceID'); $balance = $gamount - $gpayed; $invoice = Invoice::find($id); $invoice->balance = $gamount - $gpayed; $invoice->amountpaid = $gpayed + $initpaid; $invoice->save(); $payment = new Payment(); $payment->invoiceID = Input::get('invoiceID'); $payment->amount = Input::get('amount'); $payment->amountpayed = Input::get('amountpayed'); $payment->houseID = Input::get('houseID'); $payment->balance = $gamount - $gpayed; $payment->paymenttype = Input::get('paymenttype'); $payment->paymenttyperef = Input::get('paymenttyperef'); $payment->save(); #send an sms to the tenant $findTenant = $invoice->recipient; $tenants = Tenant::where('name', $findTenant)->get(); foreach ($tenants as $tenant) { $t_name = $tenant->name; $to = $tenant->phone; } $message = ' Hi ' . $t_name . ', Your invoivce Payment of amount: Ksh. ' . number_format($gpayed, 2) . ' has been received due balance ' . number_format($balance, 2) . ', Thank you for Choosing us'; LaravelAtApi::sendMessage($to, $message); return Redirect::route('admin.invoice.show', $id); } return Redirect::back()->withInput()->withErrors($v)->with('message', 'There were validation errors'); }
/** * Updates a particular model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id the ID of the model to be updated */ public function actionUpdate($id) { if (isset($_GET['sid'])) { // Меняем статус, ajax $sid = $_GET['sid']; $model = $this->loadModel($id); $model->status = $sid; $model->save(); Yii::app()->end(); } if (Yii::app()->request->isAjaxRequest) { //echo 'test'; $data = Yii::app()->request->getRestParams(); $field = str_replace('Zakaz_', '', $data['elid']); if (is_array($data)) { $model = $this->loadModel($data['id']); echo json_encode($model->{$field} = $data['data']); echo json_encode($model->save()); echo json_encode($model->errors); Yii::app()->end(); } $this->renderPartial('_order_list_update'); Yii::app()->end(); } Yii::app()->session['project_id'] = $id; $model = $this->loadModel($id); if (Yii::app()->request->getParam('close') == 'yes') { $model->old_status = $model->status; $model->status = 5; $model->save(false); $user = User::model()->findByPk($model->user_id); if ($user->pid) { $payed = Payment::model()->exists('order_id = :p1 AND payment_type = :p2', array(':p1' => $model->id, ':p2' => Payment::OUTCOMING_WEBMASTER)); if (!$payed) { // Only first time $webmaster = User::model()->with('profile')->findByPk($user->pid); $openlog = WebmasterLog::model()->findByAttributes(array('order_id' => $model->id), 'action = :p1 OR action = :p2', array(':p1' => WebmasterLog::FIRST_ORDER, ':p2' => WebmasterLog::NON_FIRST_ORDER)); $webmasterlog = new WebmasterLog(); $webmasterlog->pid = $user->pid; $webmasterlog->uid = $user->id; $webmasterlog->date = date("Y-m-d"); $webmasterlog->order_id = $model->id; if ($openlog->action == WebmasterLog::FIRST_ORDER) { $webmasterlog->action = WebmasterLog::FINISH_FIRST_ORDER_SUCCESS; } elseif ($openlog->action == WebmasterLog::NON_FIRST_ORDER) { $webmasterlog->action = WebmasterLog::FINISH_NON_FIRST_ORDER_SUCCESS; } $webmasterlog->save(); // Pament for webmaster ~~~~~~~~~~~~~~~~~~~~~~~~~~ $payment = ProjectPayments::model()->find('order_id = :ORDER_ID', array(':ORDER_ID' => $model->id)); $manag = User::model()->findByPk(Yii::app()->user->id); $buh = new Payment(); $buh->order_id = $model->id; $buh->receive_date = date('Y-m-d'); $buh->theme = $model->title; $buh->user = $webmaster->email; $buh->details_ya = $webmaster->profile->yandex; $buh->details_wm = $webmaster->profile->wmr; $buh->details_bank = $webmaster->profile->bank_account; $buh->payment_type = Payment::OUTCOMING_WEBMASTER; $buh->manager = $manag->email; //$buh->approve = 0; $buh->method = 'Cash or Bank'; if ($openlog->action == WebmasterLog::FIRST_ORDER) { $buh->summ = (double) $payment->project_price * Company::getWebmasterFirstOrderRate(); } elseif ($openlog->action == WebmasterLog::NON_FIRST_ORDER) { $buh->summ = (double) $payment->project_price * Company::getWebmasterSecondOrderRate(); } $buh->save(); } } $this->redirect(array('update', 'id' => $model->id)); } elseif (Yii::app()->request->getParam('open') == 'yes') { $model->status = $model->old_status; $model->save(false); $this->redirect(array('update', 'id' => $model->id)); } elseif (Yii::app()->request->getParam('refound') == 'yes') { $model->old_status = $model->status; $model->status = 5; $model->save(false); $user = User::model()->findByPk($model->user_id); // Refound ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $manag = User::model()->findByPk(Yii::app()->user->id); $payment = ProjectPayments::model()->find('order_id = :ORDER_ID', array(':ORDER_ID' => $model->id)); if ($payment && $payment->received > 0) { $refound = $payment->received; $payment->received = 0; $payment->save(); $buh = new Payment(); $buh->order_id = $model->id; $buh->receive_date = date('Y-m-d'); $buh->theme = $model->title; $buh->user = $user->email; $buh->summ = (double) $refound; $buh->payment_type = Payment::OUTCOMING_CUSTOMER; $buh->manager = $manag->email; //$buh->approve = 0; $buh->method = 'Cash or Bank'; $buh->save(); } if ($user->pid) { $webmasterlog = new WebmasterLog(); $webmasterlog->pid = $user->pid; $webmasterlog->uid = $user->id; $webmasterlog->date = date("Y-m-d"); $webmasterlog->order_id = $model->id; $openlog = WebmasterLog::model()->findByAttributes(array('order_id' => $model->id), 'action = :p1 OR action = p2', array(':p1' => WebmasterLog::FIRST_ORDER, ':p2' => WebmasterLog::NON_FIRST_ORDER)); if ($openlog->action == WebmasterLog::FIRST_ORDER) { $webmasterlog->action = WebmasterLog::FINISH_FIRST_ORDER_FAILURE; } elseif ($openlog->action == WebmasterLog::NON_FIRST_ORDER) { $webmasterlog->action = WebmasterLog::FINISH_NON_FIRST_ORDER_FAILURE; } else { echo 'Somthing wrong...'; Yii::app()->end(); } $webmasterlog->save(); } $this->redirect(array('update', 'id' => $model->id)); } // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if (isset($_POST['Zakaz'])) { $model->attributes = $_POST['Zakaz']; if (isset($_POST['Zakaz']['dbdate'])) { $model->dbdate = $_POST['Zakaz']['dbdate']; } $projectFields = $model->getFields(); if ($projectFields) { foreach ($projectFields as $field) { if ($field->field_type == "TIMESTAMP") { // ---------------------------------------------------- $tmp = $field->varname; if (isset($_POST['Zakaz'][$tmp])) { $model->{$tmp} = $_POST['Zakaz'][$tmp]; $model->timestampInput($field); } } } } if ($model->save()) { if (Yii::app()->request->getParam('accepted') && User::model()->isCorrector()) { EventHelper::correctorAccepted($model->id); } $role = User::model()->getUserRole(); if ($role != 'Manager' && $role != 'Admin') { // где-то есть дублрующий вызов записи события, поэтому этот комментируем // oldbadger 09.10.2015 // EventHelper::editOrder($model->id); //$view = 'orderInModerate'; $this->redirect(array("../project/chat?orderId={$id}")); } else { // $this->redirect(array('project/chat','orderId'=>$model->id)); $this->redirect(array('update', 'id' => $model->id)); } } } $managerlog = new ManagerLog(); $managerlog->uid = Yii::app()->user->id; $managerlog->action = ManagerLog::ORDER_PAGE_VIEW; $managerlog->datetime = date('Y-m-d H:i:s'); $managerlog->order_id = $model->id; $managerlog->save(); $hints = Templates::model()->getTemplateList(4); $view = 'update'; $isModified = false; $this->render($view, array('model' => $model, 'hints' => $hints, 'isModified' => $isModified)); }
public function charges_store() { $user_id = Auth::user()->id; $colonia = Session::get("colonia"); $urbanism = Urbanism::where('colony_id', '=', $colonia)->first(); $collector = Collector::where('user_id', '=', $user_id)->where('urbanism_id', '=', $urbanism->id)->first(); $ano = date("Y"); $neighbor = Input::get('valorid'); $amount = Input::get('amount'); $income_charge = new Payment(); $income_charge->neighbor_property_id = $neighbor; $income_charge->collector_id = $collector->id; $income_charge->amount = $amount; $income_charge->sub_account_id = Input::get('sub_account_id'); $income_charge->coments = Input::get('coments'); $income_charge->deposit = null; $income_charge->debt = null; $income_charge->status_id = 1; $income_charge->updated_at = date('Y') . '-01-01 ' . date('H:i:s'); if ($income_charge->save()) { $neighbor_payments = $income_charge; $payment_state = PaymentStates::where('neighbor_property_id', '=', $neighbor)->where('year', '=', $ano)->orderBy('created_at', 'desc')->first(); $months = array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"); $monthly_all = MonthlyFee::where('monthly_fee.urbanism_id', '=', $collector->urbanism_id)->where(DB::raw('DATE_FORMAT(monthly_fee.since,\'%Y\')'), '=', $ano)->get(); $monthly_ini = MonthlyFee::where('monthly_fee.urbanism_id', '=', $collector->urbanism_id)->where(DB::raw('DATE_FORMAT(monthly_fee.since,\'%Y\')'), '=', $ano)->orderBy('monthly_fee.created_at', 'ASC')->pluck('since'); $mes_ini = (int) date("m", strtotime($monthly_ini)); $cuotas = array(); foreach ($monthly_all as $cuota_mensual) { $ini = (int) date("m", strtotime($cuota_mensual->since)); $fin = (int) date("m", strtotime($cuota_mensual->until)); if ($cuota_mensual->until == NULL) { $fin = (int) date("m"); } for ($i = $ini; $i <= $fin; $i++) { $cuotas[$months[$i - 1]] = $cuota_mensual->amount; } } $acumulado = $amount; //para guardar el monto $ValorInicial = $amount; //para guardar el valor inicial del monto ingresado $ValorResto = 0; //para comparar con el valor inicial $balance = Balance::where('neighbor_property_id', '=', $neighbor)->pluck('amount'); $balance_saldo = Balance::where('neighbor_property_id', '=', $neighbor)->first(); if ($balance) { $saldo = $balance; if ($saldo > $amount) { $saldo = $saldo - $amount; $amount = 0; $balance_saldo->amount = $saldo; $balance_saldo->update(['id']); } else { if ($saldo < $amount) { $saldo = $amount - $saldo; $amount = $saldo; $balance_saldo->delete(['id']); } else { $saldo = 0; $amount = 0; $balance_saldo->delete(['id']); } } } else { $saldo = 0; } //Si el usuario no ha realizado ningún pago, se llena la tabla Payment_States por primera vez if (!$payment_state) { $TotalCuotas = 0; $payment_state_detail = new PaymentStates(); $payment_state_detail->neighbor_property_id = $neighbor_payments->neighbor_property_id; $payment_state_detail->year = date('Y', strtotime($neighbor_payments->created_at)); //Ciclo hasta el mes actual for ($i = $mes_ini - 1; $i < date('m'); $i++) { if (date('m') != $i + 1) { if ($amount > $cuotas[$months[$i]]) { $payment_state_detail->{$months}[$i] = $cuotas[$months[$i]]; $amount = $amount - $cuotas[$months[$i]]; } else { if ($amount < $cuotas[$months[$i]] && $amount != 0) { $payment_state_detail->{$months}[$i] = $amount; $amount = 0; } else { $payment_state_detail->{$months}[$i] = $cuotas[$months[$i]]; $amount = 0; } } } else { //si es el mes actual // for: suma todas las cuotas de cada mes, las q se deben for ($j = $mes_ini - 1; $j < date('m'); $j++) { if ($payment_state_detail->{$months}[$j] == null) { $TotalCuotas = $TotalCuotas + $cuotas[$months[$j]]; } elseif ($payment_state_detail->{$months}[$j] < $cuotas[$months[$j]] && $payment_state_detail->{$months}[$j] > 0) { $resto_mes = $cuotas[$months[$j]] - $payment_state_detail->{$months}[$j]; $TotalCuotas = $TotalCuotas + $resto_mes; } } if ($TotalCuotas > $amount) { $TotalCuotas = $TotalCuotas - $amount; $payment_state_detail->{$months}[$i] = "-" . $TotalCuotas; } elseif ($TotalCuotas < $amount) { $TotalCuotas = $amount - $TotalCuotas; $payment_state_detail->{$months}[$i] = $cuotas[$months[$i]] + $TotalCuotas; $amount = $TotalCuotas; } elseif ($TotalCuotas == $amount) { //si la cuota es igual al monto que esta pagando $payment_state_detail->{$months}[$i] = $cuotas[$months[$i]]; $amount = 0; } } } //fin del ciclo $payment_state_detail->accumulated = $acumulado; //Se guardan los datos en Payment_States $payment_state_detail->save(); } else { //si ya tiene registros en payment_state $fondo = $payment_state->accumulated + $amount; $valorResto = 0; $abono = 0; for ($i = $mes_ini - 1; $i < date('m'); $i++) { if (date('m') != $i + 1) { if ($payment_state->{$months}[$i]) { if ($payment_state->{$months}[$i] != $cuotas[$months[$i]] && $payment_state->{$months}[$i] > 0) { $valorResto = $ValorResto + $payment_state->{$months}[$i]; $amount = $amount + $valorResto; if ($amount > $cuotas[$months[$i]]) { $payment_state->{$months}[$i] = $cuotas[$months[$i]]; $amount = $amount - $cuotas[$months[$i]]; } else { $payment_state->{$months}[$i] = $amount; $amount = 0; } } } else { if ($amount > $cuotas[$months[$i]]) { $payment_state->{$months}[$i] = $cuotas[$months[$i]]; $amount = $amount - $cuotas[$months[$i]]; } else { if ($amount < $cuotas[$months[$i]]) { $payment_state->{$months}[$i] = $amount; $amount = 0; } else { $payment_state->{$months}[$i] = $cuotas[$months[$i]]; $amount = 0; } } } } else { //si es el mes actual if ($payment_state->{$months}[$i] < 0) { $deuda = -1 * $payment_state->{$months}[$i]; $deuda = $amount - $deuda; if ($deuda < 0) { $payment_state->{$months}[$i] = $deuda; } else { if ($deuda == 0) { $payment_state->{$months}[$i] = $cuotas[$months[$i]]; } else { $payment_state->{$months}[$i] = $deuda + $cuotas[$months[$i]]; } } } else { $abono = $payment_state->{$months}[$i] + $amount; $payment_state->{$months}[$i] = $abono; } } } $payment_state->accumulated = $fondo; $payment_state->update(['id']); } //---envio por email de recibo al pagador--- $mensaje = null; $monto = Input::get('amount'); $infoCobrador = Neighbors::with('NeighborProperty')->where('user_id', '=', $user_id)->first(); $infoPagador = NeighborProperty::where('id', '=', $neighbor)->first(); $email = UserNeighbors::where('id', '=', $infoPagador->Neighbors->user_id)->pluck('email'); $tipoUrb = $infoPagador->Urbanism->UrbanismType->id; if ($tipoUrb == 3) { $Domicilio = "Piso " . $infoPagador->Building->description . ' - Apartamento ' . $infoPagador->num_house_or_apartment; } else { $Domicilio = "Calle " . $infoPagador->Street->name . ' - Casa ' . $infoPagador->num_house_or_apartment; } $Colony = Urbanism::with('Colony.City')->where('id', '=', $infoPagador->Urbanism->id)->first(); $state = DB::table('states')->where('id', $Colony->Colony->City->state_id)->first(); $dias = array("Domingo", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado"); $meses = array("Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"); $fecha = $dias[date('w')] . " " . date('d') . " de " . $meses[date('n') - 1] . " del " . date('Y'); $pay_states = PaymentStates::where('neighbor_property_id', '=', $neighbor)->where('year', '=', $ano)->get(); $data = array('Cobrador' => $infoCobrador->name . " " . $infoCobrador->last_name, 'Nombre' => $infoPagador->Neighbors->name . " " . $infoPagador->Neighbors->last_name, 'Domicilio' => $Domicilio, 'monto' => $monto, 'Fecha' => $fecha, 'colonia' => $Colony->Colony->name, 'urbanismo' => $infoPagador->Urbanism->name, 'estado' => $state->name, 'ciudad' => $Colony->Colony->City->name, 'payments' => $pay_states, 'months' => $months, 'cuotas' => $cuotas, 'mes_ini' => $mes_ini); try { Mail::send('emails.Recibo', $data, function ($message) use($email) { $message->to($email); $message->subject('Recibo de pago'); }); } catch (Exception $exc) { Mail::send('emails.Recibo', $data, function ($message) use($email) { $message->to($email); $message->subject('Recibo de pago'); }); } // ---/fin de envio por email de recibo al pagador/---- //se agrego el logs Event::fire('logs', 'hizo un Cobro al Domicilio ' . $Domicilio . ' de un Monto de' . $monto); //fin logs return Redirect::action('IncomesController@charges_index')->with('error', false)->with('msg', 'Cobro ingresado con éxito.')->with('class', 'info'); } else { return Redirect::back()->with('error', true)->with('msg', '¡Algo salió mal! Contacte con administrador.')->with('class', 'danger'); } }
public function postSave() { $in = Input::get(); //print_r($in); /* current_trx:3IseB cc_amount: cc_number: cc_expiry: dc_amount: dc_number: payable_amount:632500 cash_amount: cash_change: */ $trx = Payment::where('sessionId', $in['current_trx'])->first(); //print_r($trx); if ($trx) { } else { $trx = new Payment(); $trx->sessionId = $in['current_trx']; $trx->createdDate = new MongoDate(); $trx->sessionStatus = 'open'; } $trx->by_name = $in['by_name']; $trx->by_gender = $in['by_gender']; $trx->by_address = $in['by_address']; $trx->cc_amount = $in['cc_amount']; $trx->cc_number = $in['cc_number']; $trx->cc_expiry = $in['cc_expiry']; $trx->dc_amount = $in['dc_amount']; $trx->dc_number = $in['dc_number']; $trx->payable_amount = $in['payable_amount']; $trx->cash_amount = $in['cash_amount']; $trx->cash_change = $in['cash_change']; $trx->lastUpdate = new MongoDate(); $trx->save(); return Response::json(array('result' => 'OK')); }
public function doRefund($id) { $user = Auth::user(); $club = $user->clubs()->FirstOrFail(); $uuid = Uuid::generate(); $payment = Payment::where('club_id', '=', $club->id)->where('transaction', '=', $id)->FirstOrFail(); $user_parent = User::find($payment->user_id); $uuid = Uuid::generate(); if ($payment->event_type) { $participant = Participant::Find($payment->items->first()->participant_id); $event = Evento::find($participant->event->id); } else { $participant = Member::Find($payment->items->first()->member_id); $event = Team::find($participant->team->id); } $player = Player::Find($participant->player->id); //$amount = $payment->getOriginal('subtotal'); $amount = Input::get('amount'); if ($amount > $payment->getOriginal('subtotal')) { return Redirect::action('AccountingController@refund', $payment->transaction)->with('error', "You cannot refund more than " . $payment->getOriginal('subtotal')); } if ($amount <= 0 || $amount == '') { return Redirect::action('AccountingController@refund', $payment->transaction)->with('error', "Amount must be more than 0"); } if ($amount > 0) { $param = array('transactionid' => $payment->transaction, 'club' => $club->id, 'amount' => number_format($amount, 2, ".", "")); $transaction = $payment->refund($param); if ($transaction->response == 3 || $transaction->response == 2) { return Response::json($transaction); return Redirect::action('AccountingController@transaction', $payment->transaction)->with('error', $transaction->responsetext); } else { $payment1 = new Payment(); $payment1->id = $uuid; $payment1->customer = $user_parent->profile->customer_vault; $payment1->transaction = $transaction->transactionid; $payment1->subtotal = -$transaction->total; $payment1->total = -$transaction->total; $payment1->club_id = $club->id; $payment1->user_id = $user_parent->id; $payment1->player_id = $player->id; $payment1->type = $transaction->type; $sale = new Item(); $sale->description = $event->name . " ({$transaction->type})"; $sale->quantity = 1; $sale->price = -$transaction->total; $sale->payment_id = $uuid; if ($payment->event_type) { $payment1->event_type = $event->type_id; } else { $payment1->event_type = NULL; } $payment1->save(); $sale->save(); $data = array('club' => $club, 'transaction' => $transaction, 'user' => $user, 'contact' => $user_parent); //send notification for refund confirmation $mail = Mail::send('emails.receipt.refund', $data, function ($message) use($user, $club, $user_parent) { $message->to($user_parent->email)->subject("Refund Confirmation | " . $club->name); foreach ($club->users()->get() as $value) { $message->bcc($value->email, $club->name); } }); } //end of transaction result } //end of amount test return Redirect::action('AccountingController@transaction', $payment->transaction); }
$date = DateTime::createFromFormat('Y-m-d H:i:s', $user_date); $date->modify($cat->days); $update_date = $date->format('Y-m-d H:i:s'); } $user->category_id = $cat->id; $user->prem_valid = $update_date; $user->avl_bytes = $cat->max_bytes; $user->save(); $payment = new Payment(); $payment->description = $cat->name; $payment->amount = $v2; $payment->user_id = $user_id; $payment->payer_email = $_POST['payer_email']; $payment->payment_date = $_POST['payment_date']; $payment->payment_id = $_POST['txn_id']; $payment->save(); } } } } else { } } } }); Route::post('/datasrpc/tunnel/auth/i', function () { foreach ($_POST as $key => $row) { $skip = false; try { if (!isset($_POST[$key]['user'])) { $rel6 = '{(\\d+)-(\\d+)}'; preg_match($rel6, $key, $matches_user);
public function Leave($block = 0) { Auth::RequireLogin(true); // Make sure the user is logged in if (!$this->auth->isLogged()) { $this->json->error("You need to be logged in."); } // Find the game $this->Block = new Game_Block($block); // Make sure the game exists if (!$this->Block->exists()) { $this->json->error("Block could not be found."); } // Make sure the game is not in the past if ($this->Block->time != 0 && $this->Block->time < time()) { $this->json->error("This block is already in the past."); } // Load your account $this->Account = new Account(Auth::Get("id")); // Make sure your account has been loaded if (!$this->Account->exists()) { $this->json->error("Your account could not be loaded."); } // Make sure you are playing this game if (!$this->Block->is_related_to($this->Account)) { $this->json->error("You are not playing this block."); } // Try getting the fixture $this->Fixture = $this->Block->fixture->get(); // Make sure fixture is loaded if (!$this->Fixture->exists()) { $this->json->error("Fixture could not be loaded."); } $this->Related_Account = $this->Block->account->where("id", Auth::Get("id"))->include_join_fields()->get(); if ($this->Related_Account->exists() && !$this->Related_Account->join_active) { $this->json->error("You already left this game."); } // If the fixture is not free if ($this->Fixture->payp_cost) { // Mark his last payment canceled $this->LastPayment = new Payment(); $this->LastPayment = $this->LastPayment->where(array("account_id" => Auth::Get("id"), "game_block_id" => $this->Block->id))->order_by("id", "DESC")->limit(1)->get(); if ($this->LastPayment->exists()) { $this->LastPayment->status = "canceled"; $this->LastPayment->save(); } // Return the money $Payment = new Payment(); if ($this->Related_Account->join_type == "game") { $Payment->amount = $this->Fixture->payp_cost - $this->Fixture->payp_cost * 2; } else { if ($this->Related_Account->join_type == "block") { $this->BlocksCount = $this->Fixture->game_block->count(); $Payment->amount = floor($this->Fixture->player_cost / $this->BlocksCount) - floor($this->Fixture->player_cost / $this->BlocksCount * 2); } } $Payment->date = time(); $Payment->account_id = Auth::Get("id"); $Payment->game_block_id = $this->Block->id; $Payment->fixture_id = $this->Fixture->id; $Payment->type = "game"; $Payment->status = "active"; $Payment->save(); // Return credits to your account $this->Account->credits += $Payment->amount; $this->Account->save(); } // Set this account inactive $this->Block->set_join_field($this->Account, "active", 0); $this->json->success(); }
$p->set_surcharge(0); $p->set_discount(0); $p->set_comment(''); $p->set_status(1); $p->set_date(strtotime('now')); $payment_id = Payment::save($p); exit; } if (!empty($_GET['switch'])) { // Update status of old device $d = Device::getById($device_id); $d->set_status(0); Device::save($d); // Update status of new device $device_id = (int) $_GET['new_device_id']; $d = Device::getById($device_id); $d->set_status(1); Device::save($d); $p = Payment::getById($payment_id); $p->set_device($device_id); Payment::save($p); echo $device_id; exit; } $smarty->assign('start', $start); $smarty->assign('stop', $stop); $smarty->assign('total', $total); $smarty->assign('total1', $total1); $smarty->assign('payment', Payment::getById($payment_id)); $smarty->assign('device', $device); $smarty->display('payment.tpl');
public function receivePayment() { $input = Input::all(); $v = Validator::make(Input::All(), array('invoiceID' => 'required|max:50|', 'houseID' => 'required', 'amountdue' => 'required|min:2', 'paymenttype' => 'required', 'amountpayed' => 'required', 'totalpaid' => 'required', 'paymenttyperef' => 'required', 'agent_id' => 'required')); if ($v->passes()) { $findHouse = Input::get('houseID'); $propertyId = House::where('name', $findHouse)->pluck('propertyID'); $propertyName = Property::where('id', $propertyId)->pluck('name'); $agent_id = Input::get('agent_id'); $gamount = Input::get('amountdue'); $gpayed = Input::get('totalpaid'); $currentPaid = Input::get('amountpayed'); $initpaid = Input::get('initpaid'); $cpaid = $gpayed + $currentPaid; $agent_id = Input::get('agent_id'); $billedusr = User::find($agent_id); $hisBalance = $billedusr->credit_balance; $newBalance = $hisBalance - 3; $billedusr->credit_balance = $newBalance; $billedusr->save(); $billstatement = new Statement(); $billstatement->type = "Receiving Payment"; $billstatement->amount = 3; $billstatement->save(); $id = Input::get('invoiceID'); $balance = $gamount - $cpaid; $invoice = Invoice::find($id); $invoiceid = $invoice->id; $invoice->balance = $gamount - $cpaid; $invoice->amountpaid = $cpaid; $invoice->save(); // Create a new Receipt $reciept = new Receipt(); $reciept->invoiceID = $invoice->id; $reciept->agent_id = $invoice->agent_id; $reciept->type = $invoice->type; $reciept->houseID = $invoice->houseID; $reciept->recipient = $invoice->recipient; $reciept->propertyid = $invoice->propertyid; $reciept->invoice_amt = $gamount; $reciept->amountpaid = $currentPaid; $reciept->balance = $gamount - $cpaid; $reciept->duedate = $invoice->duedate; $reciept->save(); // Create a new payment report $payment = new Payment(); $payment->invoiceID = Input::get('invoiceID'); $payment->amount = Input::get('amountdue'); $payment->amountpayed = Input::get('amountpayed'); $payment->houseID = $findHouse; $payment->client = $invoice->recipient; $payment->property = $propertyName; $payment->balance = $gamount - $cpaid; $payment->paymenttype = Input::get('paymenttype'); $payment->paymenttyperef = Input::get('paymenttyperef'); $payment->save(); #send an sms to the tenant $findTenant = $invoice->recipient; $ftname = strtok($findTenant, " "); $tenants = Tenant::where('name', $ftname)->get(); foreach ($tenants as $tenant) { $t_name = $tenant->name; $to = $tenant->phone; } $message = ' Hi ' . $t_name . ', Your payment of Ksh. ' . number_format($currentPaid, 2) . ' for ' . $findHouse . ' has been received successfully, due balance ' . number_format($balance, 2) . ', Thank you'; // Queue::push('SendSMS', array('message' =>$message ,'number'=>$to )); $noteP = array('error' => false, 'message' => 'Payment received successfully'); return $noteP; } $notePE = array('error' => true, 'message' => $v->errors()->all()); return $notePE; }
public function contract($order_id, $step = null) { AuthPlugins::required($this, array('销售经理', '销售顾问')); $order_id = abs(intval($order_id)); $order = Order::get_by_id($order_id); if (!$step) { $step = 'solution'; } $smarty = parent::load('smarty'); $smarty->assign('order', $order); switch ($step) { case 'solution': $solution_id = abs(intval($_GET['id'])); if ($solution_id) { /* * 全部设为非选定方案 */ Solution::set_unchecked(); /* * 选定某个方案 */ Solution::select($solution_id); HttpRedirect::to('order/contract/' . $order_id . '/paper'); } else { $solutions = Solution::get_by_order($order_id); if (!$solutions) { $message = '您还没有为此订单添加方案, 请返回添加'; HTTPRedirect::flash_to('order/detail/' . $order_id, $message, $smarty); } $smarty->assign('page_title', '签约订单 - 选定方案 Step 1'); $smarty->display('contract/solution'); } break; case 'paper': if (!Solution::get_checked($order_id)) { $message = '您还没有选择方案, 请返回选择'; HTTPRedirect::flash_to('order/contract/' . $order_id . '/solution', $message, $smarty); } if ($this->is_post() || $_FILES) { import('system/share/io/filesystem'); FileSystem::init(); $http_path = FileSystem::Upload($_FILES['paper_attachment'], false); if (!FileSystem::$local_path) { $message = '不支持的附件类型, 请检查'; HTTPRedirect::flash_to('order/detail/' . $order_id, $message, $smarty); } $order->paper_attachment = $http_path; $order->save(); HTTPRedirect::flash_to('order/contract/' . $order_id . '/payment', '上传合同成功', $this->smarty); } else { $smarty->assign('page_title', '签约订单 - 上传合同附件 Step 2'); $smarty->display('contract/paper'); } break; case 'payment': if ($this->is_post()) { /* * 获取选定的订单方案 */ $solution = Solution::get_checked($order_id); /*首付款*/ $first_pay = new Payment(); $first_pay->order_id = $order_id; $first_pay->type = 'first'; $first_pay->price = abs(intval($_POST['deposit'])); $first_pay->invoice = abs(intval($_POST['invoice'])); $first_pay->public = abs(intval($_POST['pub'])); $first_pay->bank = trim(strip_tags($_POST['bank'])); $first_pay->is_payed = abs(intval($_POST['is_deposit'])); $first_pay->save(); /*二期款*/ $second_pay = new Payment(); $second_pay->order_id = $order_id; $second_pay->type = 'second'; $second_pay->price = abs(intval($_POST['payment'])); $second_pay->invoice = abs(intval($_POST['invoice'])); $second_pay->public = abs(intval($_POST['pub'])); $second_pay->bank = trim(strip_tags($_POST['bank'])); $second_pay->is_payed = abs(intval($_POST['is_payment'])); $second_pay->save(); /*尾款*/ $last_pay = new Payment(); $last_pay->order_id = $order_id; $last_pay->type = 'last'; $last_pay->price = abs(intval($_POST['last_pay'])); $last_pay->invoice = abs(intval($_POST['invoice'])); $last_pay->public = abs(intval($_POST['pub'])); $last_pay->bank = trim(strip_tags($_POST['bank'])); $last_pay->is_payed = abs(intval($_POST['is_last_pay'])); $last_pay->save(); $old_workflow = $order->Workflow->action; $workflow = Workflow::get_by_alias('新增财务订单'); $order->Workflow = $workflow; $order->save(); /* * 在用户表中写入客户的登录信息 * 登录名为客户填写的名字加订单ID * 密码为'MG-客服ID-订单号' */ $user = new User(); $user->username = $order->Customer->name . $order->id; $user->password = User::generate_password(sprintf('MG-%s-%s', $order->customer_service_id, $order->id)); $user->Role[0] = Role::get_by_alias('客户'); $user->save(); $order->Customer->CustomerUser = $user; $order->Customer->save(); $message = '恭喜您签约订单成功, 目前订单已转入财务管理页面'; HTTPRedirect::flash_to('order/list/6', $message, $smarty); } else { $smarty->assign('page_title', '签约订单 - 付款信息 Step 3'); $smarty->display('contract/payment'); } break; } }
/** * Execute the console command. * * @return mixed */ public function fire() { $startDate = Carbon::now(); $from = Carbon::now()->hour(0)->minute(0)->second(0); $to = Carbon::now()->hour(23)->minute(59)->second(59); $schedules = SchedulePayment::where('status', 0)->whereBetween('date', array($from, $to))->with('member.user.profile')->get(); //$schedules = SchedulePayment::where('status', 0)->with('member.user.profile')->get(); $errors = array(); $totalAmount = array(); $errorAmount = array(); //save daylog $dayLog = new ScheduleDailyLog(); $dayLog->started_on = Carbon::now()->toDateTimeString(); $dayLog->payments_count = count($schedules); $dayLog->save(); Cart::destroy(); foreach ($schedules as $schedule) { try { $vault = $schedule->member->user->profile->customer_vault; $user = User::find($schedule->member->user->id); $player = Player::find($schedule->member->player->id); $club = Club::find($schedule->club_id); $team = Team::find($schedule->member->team_id); $uuid = Uuid::generate(); $member = Member::find($schedule->member->id); $history = SchedulePayment::find($schedule->id); //manually login user out before login new user Auth::logout(); //manually login user Auth::login($user); //clear cart content Cart::destroy(); //set cart item $itemCart = array('id' => $team->id, 'name' => "Scheduled payment for " . $team->name, 'price' => $schedule->subtotal, 'quantity' => 1, 'organization' => $club->name, 'organization_id' => $club->id, 'player_id' => $player->id, 'user_id' => $user->id, 'type' => 'full', 'autopay' => true); Cart::insert($itemCart); //check if vault exist if ($vault) { $param = array('customer_vault_id' => $vault, 'discount' => null, 'club' => $club->id); $payment = new Payment(); $transaction = $payment->sale($param); //temp json_decode(json_encode($array), FALSE); //$transaction = json_decode(json_encode(array('response' => 1, 'total'=>$schedule->total, 'fee'=>$schedule->fee)), FALSE); if ($transaction->response == 3 || $transaction->response == 2) { $errors[] = array('payment_schedule_id' => $schedule->id, 'error_description' => $transaction->transactionid . ' : ' . $transaction->responsetext, 'error_amount' => $schedule->total, 'daily_log_id' => $dayLog->id); array_push($errorAmount, number_format($schedule->total, 2)); //Email error $emailerrorstatus = $payment->error($transaction, $club->id, $player->id); } else { array_push($totalAmount, number_format($transaction->total, 2)); $payment->id = $uuid; $payment->customer = $vault; $payment->transaction = $transaction->transactionid; $payment->subtotal = $transaction->subtotal; $payment->service_fee = $transaction->fee; $payment->total = $transaction->total; $payment->promo = $transaction->promo; $payment->tax = $transaction->tax; $payment->discount = $transaction->discount; $payment->club_id = $club->id; $payment->user_id = $user->id; $payment->player_id = $player->id; $payment->event_type = null; $payment->type = $transaction->type; $payment->save(); //Email receipt $payment->receipt($transaction, $club->id, $player->id); $sale = new Item(); $sale->description = $itemCart['name']; $sale->quantity = $itemCart['quantity']; $sale->price = $itemCart['price']; $sale->fee = $transaction->fee; $sale->member_id = $member->id; $sale->team_id = $team->id; $sale->payment_id = $uuid; $sale->save(); //update schedule $history->status = 2; $history->save(); } } else { //save error that vault didnt exist $errors[] = array('payment_schedule_id' => $schedule->id, 'error_description' => 'Customer Vault not found', 'error_amount' => number_format($schedule->total, 2), 'daily_log_id' => $dayLog->id); array_push($errorAmount, number_format($schedule->total, 2)); } } catch (Exception $e) { //save internal error $errors[] = array('payment_schedule_id' => $schedule->id, 'error_description' => $e, 'error_amount' => number_format($schedule->total, 2), 'daily_log_id' => $dayLog->id); array_push($errorAmount, number_format($schedule->total, 2)); } } //end of foreach schedule //save log for everything done $dayLogEnd = ScheduleDailyLog::find($dayLog->id); $dayLogEnd->ended_on = Carbon::now()->toDateTimeString(); $dayLogEnd->successful_count = Count($totalAmount); $dayLogEnd->error_count = Count($errors); $dayLogEnd->total_amount = array_sum($totalAmount); $dayLogEnd->total_amount_error = array_sum($errorAmount); $dayLogEnd->save(); //save log for errors if (Count($errors) > 0) { foreach ($errors as $errorItem) { $scheduleError = new ScheduleDailyError(); $scheduleError->error_description = $errorItem['error_description']; $scheduleError->error_amount = $errorItem['error_amount']; $scheduleError->payment_schedule_id = $errorItem['payment_schedule_id']; $scheduleError->daily_log_id = $dayLogEnd->id; $scheduleError->save(); } } return Log::info($errors); }
public function actionClone($id) { $model = $this->loadModel($id); $payment = new Payment(); $payment->attributes = $model->attributes; $payment->unsetAttributes(array('payment_id', 'month_rk', 'account_rk', 'date', 'payment_date', 'deadline', 'account_number', 'comment')); $payment->deadline = date('Y-m-d', strtotime(date('Y-m-d', strtotime($model->deadline)) . ' + 1 month')); $payment->save(); $this->redirect('/payment/update/' . $payment->payment_id); }
public function savePayment() { $amount = Input::get('amount'); $other = Input::get('other'); $currencyId = Input::get('currency'); $driverID = Input::get('driver'); try { $payment = new Payment(); $payment->amount = $amount; $payment->other = $other; $payment->currency = $currencyId; $payment->driver_id = $driverID; $payment->save(); $result = array('success' => true); } catch (Exception $ex) { \Log::error(__METHOD__ . ' | error :' . print_r($ex, 1)); $result = array('success' => false); } return $result; }
public function saveUserPayment() { $payment_token = Input::get('stripeToken'); $owner_id = Session::get('user_id'); $owner_data = Owner::find($owner_id); try { if (Config::get('app.default_payment') == 'stripe') { Stripe::setApiKey(Config::get('app.stripe_secret_key')); $customer = Stripe_Customer::create(array("card" => $payment_token, "description" => $owner_data->email)); $last_four = substr(Input::get('number'), -4); if ($customer) { $customer_id = $customer->id; $payment = new Payment(); $payment->owner_id = $owner_id; $payment->customer_id = $customer_id; $payment->last_four = $last_four; $payment->card_token = $customer->cards->data[0]->id; $payment->save(); $message = "Your Card is successfully added."; $type = "success"; return Redirect::to('/user/payments')->with('message', $message)->with('type', $type); } else { $message = "Sorry something went wrong."; $type = "danger"; return Redirect::to('/user/payments')->with('message', $message)->with('type', $type); } } else { Braintree_Configuration::environment(Config::get('app.braintree_environment')); Braintree_Configuration::merchantId(Config::get('app.braintree_merchant_id')); Braintree_Configuration::publicKey(Config::get('app.braintree_public_key')); Braintree_Configuration::privateKey(Config::get('app.braintree_private_key')); $result = Braintree_Customer::create(array("firstName" => $owner_data->first_name, "lastName" => $owner_data->last_name, "creditCard" => array("number" => Input::get('number'), "expirationMonth" => Input::get('month'), "expirationYear" => Input::get('year'), "cvv" => Input::get('cvv')))); Log::info('result = ' . print_r($result, true)); if ($result->success) { $num = $result->customer->creditCards[0]->maskedNumber; $last_four = substr($num, -4); $customer_id = $result->customer->id; $payment = new Payment(); $payment->owner_id = $owner_id; $payment->customer_id = $customer_id; $payment->last_four = $last_four; $payment->card_token = $result->customer->creditCards[0]->token; $payment->save(); $message = "Your Card is successfully added."; $type = "success"; return Redirect::to('/user/payments')->with('message', $message)->with('type', $type); } else { $message = "Sorry something went wrong."; $type = "danger"; return Redirect::to('/user/payments')->with('message', $message)->with('type', $type); } } } catch (Exception $e) { $message = "Sorry something went wrong."; $type = "danger"; return Redirect::to('/user/payments')->with('message', $message)->with('type', $type); } }
public function actionPosSaveBill() { $postedData = $this->getPostedData(); $order = new Order; $payment = new Payment; $rtn = false; $trans = Yii::app()->db->beginTransaction(); try{ $currentmode = (empty($postedData['currentmode'])?0:$postedData['currentmode']); $oldorderid = (empty($postedData['oldorderid'])?0:$postedData['oldorderid']); $closedstsid = $this->getStatusIdFromName(Helper::CONST_CLOSED); $ordersts = $closedstsid; $noerror = true; $oldorder = null; if($currentmode != 0 && $oldorderid == 0) { $noerror = false; } else if($currentmode == 1 || $currentmode == 3) { $oldorder = Order::model()->findByPk($oldorderid); if(empty($oldorder)) { $noerror=false; } else { if($currentmode == 1) { $refundoldstsid = $this->getStatusIdFromName(Helper::CONST_REFUNDOLD); $oldorder->status = $refundoldstsid; $refundnewstsid = $this->getStatusIdFromName(Helper::CONST_REFUNDNEW); $ordersts = $refundnewstsid; }else { $canceloldstsid = $this->getStatusIdFromName(Helper::CONST_CANCELOLD); $oldorder->status = $canceloldstsid; $cancelnewstsid = $this->getStatusIdFromName(Helper::CONST_CANCELNEW); $ordersts = $cancelnewstsid; } } } else if($currentmode == 2) { $oldorder = Order::model()->findByPk($oldorderid); if(empty($oldorder)) { $noerror=false; } else { $refundoldstsid = $this->getStatusIdFromName(Helper::CONST_EXCHANGEOLD); $oldorder->status = $refundoldstsid; $refundnewstsid = $this->getStatusIdFromName(Helper::CONST_EXCHANGENEW); $ordersts = $refundnewstsid; } } if(!$noerror) { $RetCode = Helper::CONST_Error; $message = Helper::CONST_OldBillNotFound_Message; $data = array(); $this->returnJsonResponse($RetCode, $data, $message); } $order->status = $ordersts; $order->addnlinfo = $oldorderid; $customer_id = $postedData['customer_id']; $payment_modecheck = (empty($postedData['payment_modecheck'])?-1:$postedData['payment_modecheck']); if($payment_modecheck == '-1') { $payment_mode = $postedData['payment_mode']; } else { $payment_mode = Helper::CONST_OnAccount; } $exchange = $postedData['exchange']; $roundoff = (empty($postedData['roundoff'])?0:$postedData['roundoff']); $lineItems = $postedData['lineItems']; $order->type = Helper::CONST_Order; $order->customer_id = $customer_id; $order->created_id = Yii::app()->user->person->id; $order->modified_id = Yii::app()->user->person->id; $order->createdemp_id = Yii::app()->user->person->id; $order->modifiedemp_id = Yii::app()->user->person->id; $isconvert = $this->IsConversion($order); $extId = ($this->getEnableautoordrid()?($isconvert?null:$order->qoi_id):($isconvert?$order->new_id:$order->qoi_id)); $isautogenerated = false; $curtype = $order->type; $isnew = empty($order->id); $gnrtdId = $this->getOrderAutoId($curtype, $isnew, $extId, $isautogenerated, $isconvert); if($isautogenerated) { $order->qoi_id = $gnrtdId; } $order->name = $order->qoi_id; $totalBilltax = 0; $totalBillcost = 0; $totalBillamount = 0; $orderproducts = array(); $temporders = array(); foreach($lineItems as $lineitem) { $orderproduct = new Orderproduct; $temppurchasedetails=new Poslogreport; $qnty = $lineitem['quantity']; $temppurchasedetails->sold_out = $qnty; $temporders[] = $temppurchasedetails; $prdprice = $lineitem['unit_sp']; $lineitemdisc = $lineitem['disc']; $prdid = $lineitem['productprice'][0]['product_id']; $prdprcid = $lineitem['productprice'][0]['id']; $prdcost = $lineitem['productprice'][0]['unit_cp']; $prdtax = $lineitem['productprice'][0]['tax']; $skucode = $lineitem['productprice'][0]['sku']; $temppurchasedetails->barcode = $skucode; $lineitemcost = $qnty * $prdcost; $lineitemamount = $qnty * $prdprice; $lineitemtax = $qnty * $prdtax; $lineitemamount += $lineitemtax - $lineitemdisc; $orderproduct->product_id = $prdid; $orderproduct->productprice_id = $prdprcid; $orderproduct->cost = $lineitemcost; $orderproduct->tax = $lineitemtax; $orderproduct->quantity = $qnty; $orderproduct->unit_sp = $prdprice; $orderproduct->amount = $lineitemamount; $orderproduct->disc = $lineitemdisc; if($lineitemamount > 0) { $orderproduct->discper = round(($lineitemdisc/$lineitemamount * 100),2); } else { $orderproduct->discper = 0; } $orderproducts[] = $orderproduct; $totalBilltax += $lineitemtax; $totalBillcost += $lineitemcost; $totalBillamount += $lineitemamount; } $billdiscount = $postedData['billdiscount']; if($currentmode == '1' || $currentmode == '3') { $billdiscount = $billdiscount * -1; } if($currentmode == '1' || $currentmode == '2' || $currentmode == '3') { $roundoff = $roundoff * -1; } $totalBillamount = $totalBillamount - $billdiscount + $roundoff; if($currentmode == 2 && $totalBillamount <= 0) { $order->exchange = -$totalBillamount;//should add the amount in the name 'getback old bill discount' $totalBillamount = 0; } else if($currentmode != 1 && $currentmode != 2 && $currentmode != 3 && $totalBillamount <= 0) { $RetCode = Helper::CONST_Error; $message = Helper::CONST_InvalidBillAmount_Message; $data = array(); $this->returnJsonResponse($RetCode, $data, $message); } $order->disc = $billdiscount; $order->roundoff = $roundoff; $order->tax = $totalBilltax; $order->cost = $totalBillcost; $order->amount = $totalBillamount; if(strtolower($payment_mode) === strtolower(Helper::CONST_OnAccount)) { $order->paid = 0; } else { $order->paid = $order->amount; } $tenderedamount = $postedData['tenderedamount']; $balancereturned = $postedData['balancereturned']; $paymentdetails = $postedData['paymentdetails']; switch($currentmode) { case 1: $paymentdetails = $paymentdetails . ':Refund:'; break; case 2: $paymentdetails = $paymentdetails . ':Exchange:'; break; case 3: $paymentdetails = $paymentdetails . ':Cancel:'; break; default: break; } $payment->person_id = Yii::app()->user->person->id; $payment->amount = $totalBillamount; $payment->party_id = $customer_id; $payment->type = $payment_mode; $payment->tendered = $tenderedamount; $payment->balreturned = $balancereturned; $payment->details = $paymentdetails; $payment->direction = Helper::CONST_Inwards; $rtn = true; if(!empty($oldorder)) { $rtn = $oldorder->save(); } if($rtn) { $this->setOrderConfigs($order); $rtn = $order->save(); if($rtn) { $rtn = $this->updateOrderAutoId($order->qoi_id); if($rtn) { foreach($orderproducts as $orderproduct) { $orderproduct->order_id = $order->id; $orderproduct->order_type = $order->type; $rtn = $orderproduct->save(); if(!$rtn) break; } if($rtn) { $payment->order_id = $order->id; $rtn = $payment->save(); } } $poslogs = new Poslogreport; foreach($temporders as $temppurchasedetails) { $quantities = $temppurchasedetails->sold_out; $barcode = $temppurchasedetails->barcode; $rowsql = "select id from subproductprices where sku='$barcode'"; $result = Yii::app()->db->createCommand( $rowsql )->queryScalar(); $product = Subproductprice::model()->findByPk($result); $stockupdate = "update `subproductprices` set `initial_stock`=`initial_stock`-'$quantities' where `id`='$result'"; Yii::app()->db->createCommand($stockupdate)->execute(); $rowsqlquery = "select `sno` from `poslogreport` where `barcode`='$barcode' and `log_status`=0"; $resultset = Yii::app()->db->createCommand( $rowsqlquery )->queryScalar(); $rowsqlquery1 = "select `stock` from `subproductprices` where `sku`='$barcode'"; $stockresult = Yii::app()->db->createCommand( $rowsqlquery1)->queryScalar(); if($resultset=="") { $insertrowsql = "insert into `poslogreport`(`date`,`barcode`,`previous_stock`,`current_stock`) values(CURDATE(),'$barcode','$stockresult','$stockresult')"; $result = Yii::app()->db->createCommand( $insertrowsql )->execute(); } $rowsqlupdate = "select sno from poslogreport where barcode='$barcode' and `log_status`=0"; $resultupdate = Yii::app()->db->createCommand( $rowsqlupdate )->queryScalar(); $productupdate = Poslogreport::model()->findByPk($resultupdate); $rtn = !empty($productupdate); if($rtn) { if($quantities>0) { $productupdate->current_stock -= $quantities; $rtn = $productupdate->save(); } else { $cancelstockupdate = "update `poslogreport` set `rtn_product_quantity`=-$quantities where `sno`='$resultupdate'"; Yii::app()->db->createCommand($cancelstockupdate)->execute(); } } } } } }catch(Exception $e){ $rtn = false; } if($rtn) { // $curr_date=Yii::app()->Date->now(); $trans->commit(); $RetCode = Helper::CONST_Error_None; $message = 'Saved Bill No.:.' .$order->qoi_id; $data = array(); $this->printSavedbill($postedData,$order->qoi_id); }else { $trans->rollback(); $RetCode = Helper::CONST_Error; $message = $cancelstockupdate; $data = array(); } $this->returnJsonResponse($RetCode, $data, $message); }
function testCalculateBalanceWithDateRange() { #Company $cp = new Company(); $cp->set(array('name' => 'Test Company', 'status' => 'active')); $cp->save(); $pb = new CompanyPreviousBalance(); $pb->set(array('company_id' => $cp->id, 'amount' => 600.25, 'date' => '2010-01-30')); $pb->save(); $this->assertWithinMargin($pb->getAmount(), '600.25', '.01'); ######### Support $sc = new SupportContract(); $sc->set(array('company_id' => $cp->id, 'domain_name' => 'Test', 'start_date' => '2010-01-01', 'end_date' => '2010-04-30', 'hourly_rate' => '120', 'support_hours' => '.5', 'monthly_rate' => '50')); $sc->save(); # add support hours # before previous balance $h = new Hour(); $h->set(array('description' => 'Test', 'support_contract_id' => $sc->id, 'date' => '2010-01-20', 'hours' => '2.5')); $h->save(); # in range $h = new Hour(); $h->set(array('description' => 'Test', 'support_contract_id' => $sc->id, 'date' => '2010-02-20', 'hours' => '2.5')); $h->save(); # in range $h = new Hour(); $h->set(array('description' => 'Test', 'support_contract_id' => $sc->id, 'date' => '2010-03-20', 'hours' => '2.5')); $h->save(); # out of range $h = new Hour(); $h->set(array('description' => 'Test', 'support_contract_id' => $sc->id, 'date' => '2010-05-20', 'hours' => '2')); $h->save(); ### Support Totals = in range is 2 months x 50 = 100, 4 @ 120 = 480 = 580 $date_range = array('start_date' => '2010-01-01', 'end_date' => '2010-03-31'); $total = $cp->calculateSupportTotal($date_range); $this->assertEqual($total, 580); ###### Project $pj = new Project(); $pj->set(array('name' => 'Test Project', 'company_id' => $cp->id, 'hourly_rate' => '120')); $pj->save(); # Add an Estimate item #1 $es1 = new Estimate(); $es1->set(array('project_id' => $pj->id, 'name' => 'Test Estimate 1', 'high_hours' => '10', 'low_hours' => '5')); $es1->save(); # Add an Estimate item #2 $es2 = new Estimate(); $es2->set(array('project_id' => $pj->id, 'name' => 'Test Estimate 2', 'high_hours' => '10', 'low_hours' => '5')); $es2->save(); # Add some before previous balance hours for #1 - 5 hours at 120 = 600 $hr = new Hour(); $hr->set(array('estimate_id' => $es1->id, 'description' => 'Test Hours for Estimate 1', 'date' => '2010-01-15', 'hours' => '5')); $hr->save(); # Add some in range hours for #1 - 5 hours at 120 = 600 $hr = new Hour(); $hr->set(array('estimate_id' => $es1->id, 'description' => 'Test Hours for Estimate 1', 'date' => '2010-02-15', 'hours' => '5')); $hr->save(); # Add some in range hours for #2 - 5 hours at 120 = 600 $hr = new Hour(); $hr->set(array('estimate_id' => $es2->id, 'description' => 'Test Hours for Estimate 2', 'date' => '2010-02-15', 'hours' => '5')); $hr->save(); # Add some out of range hours for #2 - 5 hours at 120 = 600 $hr = new Hour(); $hr->set(array('estimate_id' => $es2->id, 'description' => 'Test Hours for Estimate 2', 'date' => '2010-05-15', 'hours' => '5')); $hr->save(); ## Project Totals = In range 1200, out of range 1800 $date_range = array('start_date' => '2010-01-01', 'end_date' => '2010-03-31'); $total = $cp->calculateProjectsTotal($date_range); $this->assertEqual($total, 1200); #Charge # before previous balance $cr = new Charge(); $cr->set(array('name' => 'Test', 'company_id' => $cp->id, 'date' => '2010-01-10', 'amount' => '20.50')); $cr->save(); # in date range $cr = new Charge(); $cr->set(array('name' => 'Test', 'company_id' => $cp->id, 'date' => '2010-03-14', 'amount' => '50.25')); $cr->save(); # in date range $cr = new Charge(); $cr->set(array('name' => 'Test', 'company_id' => $cp->id, 'date' => '2010-03-20', 'amount' => '50')); $cr->save(); # out of date range $cr = new Charge(); $cr->set(array('name' => 'Test', 'company_id' => $cp->id, 'date' => '2010-05-15', 'amount' => '50')); $cr->save(); # Total Charges = in range 100.25, out of range 150.25 $date_range = array('start_date' => '2010-01-01', 'end_date' => '2010-03-31'); $charge_total = $cp->calculateChargesTotal($date_range); $this->assertEqual($charge_total, 100.25); ## Test Total Costs # Charges 100.25 + project 1200 + support 580 $date_range = array('start_date' => '2010-01-01', 'end_date' => '2010-03-31'); $total = $cp->calculateCosts($date_range); $this->assertEqual($total, 1880.25); ## Payments # add payment before previous balance date $py = new Payment(); $py->set(array('company_id' => $cp->id, 'date' => '2010-01-22', 'amount' => '20.50')); $py->save(); # add payment in range $py = new Payment(); $py->set(array('company_id' => $cp->id, 'date' => '2010-02-10', 'amount' => '20.00')); $py->save(); # add payment in range $py = new Payment(); $py->set(array('company_id' => $cp->id, 'date' => '2010-03-01', 'amount' => '120.00')); $py->save(); # add payment out of range $py = new Payment(); $py->set(array('company_id' => $cp->id, 'date' => '2010-04-01', 'amount' => '20.25')); $py->save(); # Total Payments are 20 + 120 = 140 in range and after previous balance $date_range = array('start_date' => '2010-01-01', 'end_date' => '2010-03-31'); $payment_total = $cp->calculatePaymentsTotal($date_range); $this->assertEqual($payment_total, 140); #### fails because the previous balance isn't getting included FIX ME!! # Total Balance Costs 1880.25 - Payments 140 + Previous balance 600.25 = 2340.5 $date_range = array('start_date' => '2010-01-01', 'end_date' => '2010-03-31'); $balance = $cp->calculateBalance($date_range); $this->assertWithinMargin($balance, 2340.5, 0.001); ## clean up $cp->destroyAssociatedRecords(); $cp->delete(); }
public function addcardtoken() { $payment_token = Input::get('payment_token'); $last_four = Input::get('last_four'); $token = Input::get('token'); $owner_id = Input::get('id'); if (Input::has('card_type')) { $card_type = strtoupper(Input::get('card_type')); } else { $card_type = strtoupper("VISA"); } $validator = Validator::make(array('last_four' => $last_four, 'payment_token' => $payment_token, 'token' => $token, 'owner_id' => $owner_id), array('last_four' => 'required', 'payment_token' => 'required', 'token' => 'required', 'owner_id' => 'required|integer')); $payments = array(); if ($validator->fails()) { $error_messages = $validator->messages(); $response_array = array('success' => false, 'error' => 'Invalid Input', 'error_code' => 401, 'payments' => $payments); $response_code = 200; } else { $is_admin = $this->isAdmin($token); if ($owner_data = $this->getOwnerData($owner_id, $token, $is_admin)) { // check for token validity if (is_token_active($owner_data->token_expiry) || $is_admin) { try { if (Config::get('app.default_payment') == 'stripe') { Stripe::setApiKey(Config::get('app.stripe_secret_key')); $customer = Stripe_Customer::create(array("card" => $payment_token, "description" => $owner_data->email)); /* Log::info('customer = ' . print_r($customer, true)); */ if ($customer) { $card_count = DB::table('payment')->where('owner_id', '=', $owner_id)->count(); $customer_id = $customer->id; $payment = new Payment(); $payment->owner_id = $owner_id; $payment->customer_id = $customer_id; $payment->last_four = $last_four; $payment->card_type = $card_type; $payment->card_token = $customer->sources->data[0]->id; if ($card_count > 0) { $payment->is_default = 0; } else { $payment->is_default = 1; } $payment->save(); $payment_data = Payment::where('owner_id', $owner_id)->orderBy('is_default', 'DESC')->get(); foreach ($payment_data as $data1) { $default = $data1->is_default; if ($default == 1) { $data['is_default_text'] = "default"; } else { $data['is_default_text'] = "not_default"; } $data['id'] = $data1->id; $data['owner_id'] = $data1->owner_id; $data['customer_id'] = $data1->customer_id; $data['last_four'] = $data1->last_four; $data['card_token'] = $data1->card_token; $data['card_type'] = $data1->card_type; $data['card_id'] = $data1->card_token; $data['is_default'] = $default; array_push($payments, $data); } $response_array = array('success' => true, 'payments' => $payments); $response_code = 200; } else { $payment_data = Payment::where('owner_id', $owner_id)->orderBy('is_default', 'DESC')->get(); foreach ($payment_data as $data1) { $default = $data1->is_default; if ($default == 1) { $data['is_default_text'] = "default"; } else { $data['is_default_text'] = "not_default"; } $data['id'] = $data1->id; $data['owner_id'] = $data1->owner_id; $data['customer_id'] = $data1->customer_id; $data['last_four'] = $data1->last_four; $data['card_token'] = $data1->card_token; $data['card_type'] = $data1->card_type; $data['card_id'] = $data1->card_token; $data['is_default'] = $default; array_push($payments, $data); } $response_array = array('success' => false, 'error' => 'Could not create client ID', 'error_code' => 450, 'payments' => $payments); $response_code = 200; } } else { Braintree_Configuration::environment(Config::get('app.braintree_environment')); Braintree_Configuration::merchantId(Config::get('app.braintree_merchant_id')); Braintree_Configuration::publicKey(Config::get('app.braintree_public_key')); Braintree_Configuration::privateKey(Config::get('app.braintree_private_key')); $result = Braintree_Customer::create(array('paymentMethodNonce' => $payment_token)); Log::info('result = ' . print_r($result, true)); if ($result->success) { $card_count = DB::table('payment')->where('owner_id', '=', $owner_id)->count(); $customer_id = $result->customer->id; $payment = new Payment(); $payment->owner_id = $owner_id; $payment->customer_id = $customer_id; $payment->last_four = $last_four; $payment->card_type = $card_type; $payment->card_token = $result->customer->creditCards[0]->token; if ($card_count > 0) { $payment->is_default = 0; } else { $payment->is_default = 1; } $payment->save(); $payment_data = Payment::where('owner_id', $owner_id)->orderBy('is_default', 'DESC')->get(); foreach ($payment_data as $data1) { $default = $data1->is_default; if ($default == 1) { $data['is_default_text'] = "default"; } else { $data['is_default_text'] = "not_default"; } $data['id'] = $data1->id; $data['owner_id'] = $data1->owner_id; $data['customer_id'] = $data1->customer_id; $data['last_four'] = $data1->last_four; $data['card_token'] = $data1->card_token; $data['card_type'] = $data1->card_type; $data['card_id'] = $data1->card_token; $data['is_default'] = $default; array_push($payments, $data); } $response_array = array('success' => true, 'payments' => $payments); $response_code = 200; } else { $payment_data = Payment::where('owner_id', $owner_id)->orderBy('is_default', 'DESC')->get(); foreach ($payment_data as $data1) { $default = $data1->is_default; if ($default == 1) { $data['is_default_text'] = "default"; } else { $data['is_default_text'] = "not_default"; } $data['id'] = $data1->id; $data['owner_id'] = $data1->owner_id; $data['customer_id'] = $data1->customer_id; $data['last_four'] = $data1->last_four; $data['card_token'] = $data1->card_token; $data['card_type'] = $data1->card_type; $data['card_id'] = $data1->card_token; $data['is_default'] = $default; array_push($payments, $data); } $response_array = array('success' => false, 'error' => 'Could not create client ID', 'error_code' => 450, 'payments' => $payments); $response_code = 200; } } } catch (Exception $e) { $response_array = array('success' => false, 'error' => $e, 'error_code' => 405); $response_code = 200; } } else { $response_array = array('success' => false, 'error' => 'Token Expired', 'error_code' => 405); $response_code = 200; } } else { if ($is_admin) { /* $var = Keywords::where('id', 2)->first(); $response_array = array('success' => false, 'error' => '' . $var->keyword . ' ID not Found', 'error_code' => 410); */ $response_array = array('success' => false, 'error' => '' . Config::get('app.generic_keywords.User') . ' ID not Found', 'error_code' => 410); } else { $response_array = array('success' => false, 'error' => 'Not a valid token', 'error_code' => 406); } $response_code = 200; } } $response = Response::json($response_array, $response_code); return $response; }
public function PaymentStore($id) { $user = Auth::user(); $participant = Participant::find($id); $title = 'League Together - ' . $participant->event->club->name . ' Teams'; $player = $participant->player; $club = $participant->event->club; $cart = Cart::contents(true); $uuid = Uuid::generate(); //Addition for stub feature $follow = Follower::where("user_id", "=", $user->id)->FirstOrFail(); //check if follower equal club if ($follow->club_id != $club->id) { $param = array('ccnumber' => str_replace('_', '', Input::get('card')), 'ccexp' => sprintf('%02s', Input::get('month')) . Input::get('year'), 'cvv' => Input::get('cvv'), 'address1' => Input::get('address'), 'city' => Input::get('city'), 'state' => Input::get('state'), 'zip' => Input::get('zip'), 'discount' => Input::get('discount'), 'club' => $club->id, 'firstname' => $user->profile->firstname, 'lastname' => $user->profile->lastname, 'phone' => $user->profile->mobile); } else { $param = array('customer_vault_id' => $user->profile->customer_vault, 'discount' => Input::get('discount'), 'club' => $club->id); } $payment = new Payment(); $transaction = $payment->sale($param); if ($transaction->response == 3 || $transaction->response == 2) { return Redirect::action('ParticipantController@paymentCreate', array($participant->id))->with('error', $transaction->responsetext); } else { foreach (Cart::contents() as $item) { $payment->id = $uuid; $payment->customer = $user->profile->customer_vault; $payment->transaction = $transaction->transactionid; $payment->subtotal = $transaction->subtotal; $payment->service_fee = $transaction->fee; $payment->total = $transaction->total; $payment->promo = $transaction->promo; $payment->tax = $transaction->tax; $payment->discount = $transaction->discount; $payment->club_id = $club->id; $payment->user_id = $user->id; $payment->player_id = $item->player_id; $payment->event_type = $participant->event->type_id; $payment->type = $transaction->type; $payment->save(); $salesfee = $item->price / getenv("SV_FEE") - $item->price; $sale = new Item(); $sale->description = $item->name; $sale->quantity = $item->quantity; $sale->price = $item->price; $sale->fee = $salesfee; $sale->participant_id = $participant->id; $sale->payment_id = $uuid; $sale->event_id = $participant->event->id; $sale->save(); $participant->accepted_on = Carbon::Now(); $participant->accepted_by = $user->profile->firstname . ' ' . $user->profile->lastname; $participant->accepted_user = $user->id; $participant->method = $item->type; $participant->status = 1; $participant->save(); //create payments plan schedule if ($item->type == "plan") { $subtotal = $participant->plan->getOriginal('recurring'); $fee = $subtotal / getenv("SV_FEE") - $subtotal; $total = $fee + $subtotal; for ($x = 1; $x < $participant->plan->recurrences + 1; $x++) { $today = Carbon::now(); $today->addMonths($x); $payon = $participant->plan->getOriginal('on'); //make sure the payday is a valid day if ($payon == 31) { if ($today->month == 2) { $payon = 28; } if ($today->month == 4 || $today->month == 6 || $today->month == 9 || $today->month == 11) { $payon = 30; } } $payday = Carbon::create($today->year, $today->month, $payon, 0); $schedule = new SchedulePayment(); $schedule->date = $payday; $schedule->description = "Membership Team " . $participant->event->name; $schedule->subtotal = number_format($subtotal, 2); $schedule->fee = number_format($fee, 2); $schedule->total = number_format($total, 2); $schedule->plan_id = $participant->plan->id; $schedule->club_id = $club->id; $schedule->participant_id = $participant->id; $status = $schedule->save(); if (!$status) { return "We process your payment but and error occurred in the process, please contact us: support@leaguetogether.com Error# 597"; } } //end for loop } //end if plan } //email receipt $payment->receipt($transaction, $club->id, $item->player_id); $data = array('club' => $club, 'player' => $player, 'user' => $user, 'participant' => $participant); $mail = Mail::send('emails.notification.event.accept', $data, function ($message) use($user, $club, $participant) { $message->from('*****@*****.**', 'C2C Lacrosse')->to($user->email, $participant->accepted_by)->subject("Thank you for joining our event | " . $club->name); foreach ($club->users()->get() as $value) { $message->bcc($value->email, $club->name); } }); return Redirect::action('ParticipantController@paymentSuccess', array($participant->id))->with('result', $transaction); } }
public function addcardtoken() { $payment_token = Input::get('payment_token'); $last_four = Input::get('last_four'); $token = Input::get('token'); $user_id = Input::get('user_id'); try { if (Config::get('app.default_payment') == 'stripe') { Stripe::setApiKey(Config::get('app.stripe_secret_key')); $user = User::find($user_id); $customer = Stripe_Customer::create(array("card" => $payment_token, "description" => $user->email)); if ($customer) { $customer_id = $customer->id; $payment = new Payment(); $payment->user_id = $user_id; $payment->customer_id = $customer_id; $payment->last_four = $last_four; $payment->save(); $response_array = array('success' => true, 'payment_id' => $payment->id); $response_code = 200; } else { $response_array = array('success' => false, 'error' => 'Could not create client ID', 'error_code' => 450); $response_code = 200; } } } catch (Exception $e) { $response_array = array('success' => false, 'error' => $e, 'error_code' => 412); $response_code = 200; } $response = Response::json($response_array, $response_code); return $response; }