function AddTimeCredit($merchantAutobillId, $daysRemaining)
{
    $autoBill = new AutoBill();
    $autoBill->setMerchantAutoBillId($merchantAutobillId);
    $timeInterval = new TimeInterval();
    $timeInterval->setDays($daysRemaining);
    $timeInterval->setDescription("Early Pay on NonRecurring Billing");
    $timeInterval->setReason("Credit for July");
    $cr = new Credit();
    $cr->setTimeIntervals(array($timeInterval));
    $response = $autoBill->grantCredit($cr, '');
    logCall($response, 'AutoBill::GrantCredit', $daysRemaining);
}
 public function edit($publicId)
 {
     $credit = Credit::scope($publicId)->firstOrFail();
     $credit->credit_date = Utils::fromSqlDate($credit->credit_date);
     $data = array('client' => null, 'credit' => $credit, 'method' => 'PUT', 'url' => 'credits/' . $publicId, 'title' => 'Edit Credit', 'clients' => Client::scope()->with('contacts')->orderBy('name')->get());
     return View::make('credit.edit', $data);
 }
Example #3
0
 public static function boot()
 {
     parent::boot();
     Company::created(function ($company) {
         AuthorizationToken::createAuthorizationToken($company);
         Credit::createCredit($company->id);
         Credit::createCredit($company->id, Credit::PAID);
     });
 }
 public function revokeCredit($credit)
 {
     if (is_array($credit)) {
         $revokeReason = $credit['reason'];
         $credit = Credit::findOrFail($credit['model']->id);
     }
     if ($credit->count() && empty($credit->revoked_at)) {
         $credit->update(['revoke_reason' => $revokeReason, 'revoked_at' => Carbon::now()]);
     }
 }
Example #5
0
 /**
  * getCredits: Return all credits
  * @return		array		Array of all Credit objects
  */
 public static function getCredits()
 {
     $getCredits = TPP::db()->query("\r\n\t\t\tSELECT `id`, `name`, `title`, `pokemon`, `quote`, `generations`, `link`\r\n\t\t\tFROM `credits`\r\n\t\t\tWHERE `order_id` > 0\r\n\t\t\tORDER BY `order_id`, `id`") or die(TPP::db()->error);
     while ($credit = $getCredits->fetch_assoc()) {
         $newCredit = new self();
         $newCredit->setAttributes($credit);
         $newCredit->quote = Credit::getQuote($newCredit->quote);
         $newCredit->generations = self::getGenerations($newCredit->generations);
         $return[] = $newCredit;
     }
     return $return;
 }
Example #6
0
 private function handleCredits()
 {
     $criteria = array("condition" => "`enable` = 1", "order" => "`cid` ASC", "limit" => 5);
     $record = Credit::model()->fetchAll($criteria);
     if (!empty($record)) {
         $index = 1;
         foreach ($record as $credit) {
             $this->_setting["extcredits"][$index] = $credit;
             $this->_setting["creditremind"] && ($this->_setting["creditnames"][] = str_replace("'", "\\'", StringUtil::ihtmlSpecialChars($credit["cid"] . "|" . $credit["name"])));
             $index++;
         }
     }
     $this->_setting["creditnames"] = $this->_setting["creditremind"] ? @implode(",", $this->_setting["creditnames"]) : "";
 }
Example #7
0
 public function actionIndex()
 {
     $this->render('layouts/header');
     $this->render('general/index', array('general' => $this->getGeneral(), 'messages' => $this->getMessages()), true);
     $this->render('pokemon/index', array('pokemon' => Pokemon::getPartyPokemon(), 'owned' => $this->getGeneral()->pokedex_owned, 'seen' => $this->getGeneral()->pokedex_seen), true);
     $this->render('badge/index', array('badges' => Badge::getBadges(null, 'LIMIT 0, 8')), true);
     $this->render('pokemon_box/index', array('pokemon' => Pokemon::getBoxPokemon()), true);
     $this->render('pokemon_daycare/index', array('pokemon' => Pokemon::getDaycarePokemon()), true);
     $this->render('item/index', array('items' => Item::getAllItems()), true);
     $this->render('pokemon_history/index', array('pokemon' => Pokemon::getHistoryPokemon()), true);
     $this->render('milestone/index', array('milestones' => Milestone::getMilestones()), true);
     $this->render('fact/index', array('facts' => Fact::getFacts()), true);
     $this->render('credit/index', array('credits' => Credit::getCredits()), true);
     $this->render('layouts/footer');
 }
Example #8
0
 /**
  * Remove the specified resource from storage.
  *
  * @param  int  $id
  * @return Response
  */
 public function bulk()
 {
     $public_id = Input::get('public_id');
     $credit = Credit::scope($public_id)->first();
     if ($credit->balance < $credit->amount) {
         $message = "El Crédito ya fue utilizado en pagos.";
         Session::flash('error', $message);
         return Redirect::to('clientes');
     } else {
         $credit->delete();
         $message = "Crédito eliminado con éxito";
         Session::flash('message', $message);
         return Redirect::to('creditos');
     }
 }
Example #9
0
 /**
  * {@inheritDoc}
  */
 public static function fromObject($object)
 {
     $retval = new Album();
     $retval->ids = (array) $object->ids;
     $retval->title = $object->title;
     $retval->primaryArtists = Artist::fromObjectArray((array) $object->primaryArtists);
     $retval->guestArtists = Artist::fromObjectArray((array) $object->guestArtists);
     $retval->flags = $object->flags;
     $retval->duration = $object->duration;
     $retval->originalReleaseDate = $object->originalReleaseDate;
     $retval->rating = $object->rating;
     $retval->isPick = $object->isPick;
     $retval->genres = Genre::fromObjectArray((array) $object->genres);
     $retval->headlineReview = $object->headlineReview;
     $retval->classicalReview = ClassicalReview::fromObject($object->classicalReview);
     $retval->credits = Credit::fromObjectArray((array) $object->credits);
     $retval->tracks = Track::fromObjectArray((array) $object->tracks);
     $retval->styles = Style::fromObjectArray((array) $object->styles);
     return $retval;
 }
Example #10
0
 private function save()
 {
     $rules = array('client' => 'required', 'invoice' => 'required', 'amount' => 'required|positive');
     if (Input::get('invoice')) {
         $invoice = Invoice::scope(Input::get('invoice'))->firstOrFail();
         $rules['amount'] .= '|less_than:' . $invoice->balance;
     }
     if (Input::get('payment_type_id') == PAYMENT_TYPE_CREDIT) {
         $rules['payment_type_id'] = 'has_credit:' . Input::get('client') . ',' . Input::get('amount');
     }
     $messages = array('required' => 'El campo es Requerido', 'positive' => 'El Monto debe ser mayor a cero', 'less_than' => 'El Monto debe ser menor o igual a ' . $invoice->balance, 'has_credit' => 'El Cliente no tiene crédito suficiente');
     $validator = \Validator::make(Input::all(), $rules, $messages);
     if ($validator->fails()) {
         $url = 'pagos/create';
         return Redirect::to($url)->withErrors($validator)->withInput();
     } else {
         $payment = Payment::createNew();
         $paymentTypeId = Input::get('payment_type_id') ? Input::get('payment_type_id') : null;
         $clientId = Client::getPrivateId(Input::get('client'));
         $amount = floatval(Input::get('amount'));
         if ($paymentTypeId == PAYMENT_TYPE_CREDIT) {
             $credits = Credit::scope()->where('client_id', '=', $clientId)->where('balance', '>', 0)->orderBy('created_at')->get();
             $applied = 0;
             foreach ($credits as $credit) {
                 $applied += $credit->apply($amount);
                 if ($applied >= $amount) {
                     break;
                 }
             }
         }
         $payment->client_id = $clientId;
         $payment->invoice_id = Invoice::getPrivateId(Input::get('invoice'));
         $payment->payment_type_id = $paymentTypeId;
         $payment->payment_date = date("Y-m-d", strtotime(Input::get('payment_date')));
         $payment->amount = $amount;
         $payment->transaction_reference = trim(Input::get('transaction_reference'));
         $payment->save();
         Session::flash('message', 'Pago creado con éxito');
         return Redirect::to('clientes/' . Input::get('client'));
     }
 }
Example #11
0
 public function borrar()
 {
     $getTotalCredit = Credit::scope()->where('client_id', '=', $this->id)->whereNull('deleted_at')->where('balance', '>', 0)->sum('balance');
     if ($this->balance == 0) {
         if ($getTotalCredit == 0) {
             $this->error_message = 'Cliente ' . $this->name . '  con nit ' . $this->nit . ' eliminado con éxito';
             $this->delete();
             return true;
         } else {
             $this->error_message = ERROR_CREDITO;
             return false;
         }
     } else {
         $this->error_message = ERROR_BALANCE_CLIENTE;
         return false;
     }
 }
Example #12
0
    }
    if ($callerid2 == "") {
        $error_txt .= _("Subscriber number") . " 2 " . _("is empty") . "<br/>";
    }
    if ($amount == "" || $amount == 0 || !is_numeric($amount)) {
        $error_txt .= _("Invalid amount") . "<br/>";
    }
}
if (isset($_POST['add_credit']) && $error_txt != "") {
    print_form(1, $error_txt);
} elseif (isset($_POST['add_credit']) && $error_txt == "") {
    // get some data out based on user input
    $callerid = $_POST['callerid1'];
    $amount = $_POST['amount'];
    echo "<center>";
    $cred = new Credit();
    try {
        $cred->add($callerid, $amount);
        echo "<img src='img/true.png' width='200' height='170' /><br/><br/>";
        echo "<span style='font-size: 20px;'>" . _("Credit of") . " <b>{$amount}</b> " . _("pesos successfully added to subscriber") . " <b>{$callerid}</b>.</span><br/><br/><br/>";
        echo "<a href='credit.php'><button class='b1'>" . _("Go Back") . "</button></a>";
    } catch (CreditException $e) {
        echo "<img src='img/false.png' width='200' height='170' /><br/><br/>";
        echo "<span style='font-size: 20px; color: red;'>" . _("ERROR UPDATING BALANCE!") . "<br/>" . $e->getMessage() . " </span><br/><br/><br/><br/>";
        echo "<a href='credit.php'><button class='b1'>" . _("Go Back") . "</button></a>";
    }
    echo "</center>";
} else {
    print_form(0, '');
}
?>
Example #13
0
 public static function deletePayment($payment)
 {
     $client = $payment->client;
     $client->balance = $client->balance + $payment->amount;
     $client->paid_to_date = $client->paid_to_date - $payment->amount;
     $client->save();
     $invoice = $payment->invoice;
     $invoice->balance = $invoice->balance + $payment->amount;
     $invoice->save();
     if ($invoice->isPaid() && $invoice->balance > 0) {
         $invoice->invoice_status_id = $invoice->balance == $invoice->amount ? INVOICE_STATUS_DRAFT : INVOICE_STATUS_PARTIAL;
     }
     if ($payment->payment_type_id == PAYMENT_TYPE_CREDIT) {
         $credit = Credit::createNew();
         $credit->client_id = $client->id;
         $credit->balance = $credit->amount = $payment->amount;
         $credit->private_notes = $payment->transaction_reference;
         $credit->save();
     }
     $activity = Activity::getBlank();
     $activity->payment_id = $payment->id;
     $activity->client_id = $invoice->client_id;
     $activity->invoice_id = $invoice->id;
     $activity->activity_type_id = ACTIVITY_TYPE_DELETE_PAYMENT;
     // $activity->message = Utils::encodeActivity(Auth::user(), 'borró ' . $payment->getName());
     $activity->balance = $client->balance;
     $activity->adjustment = $payment->amount;
     $activity->save();
 }
Example #14
0
		<!-- //header -->
		<br>
		<br>

		<!-- Content -->
		<div class="row-fluid">

			<?php 
include_layout_template('admin_menu.php');
?>

			<div class="span9">
				<h2>Edit Developer Details</h2>
				<hr>
				<?php 
$credit = Credit::find_by_id(customDecrypt($_POST['cid']));
?>
				<!-- Begining of Credit form -->
				<form class="form-horizontal credit" id="credit">
					
					<div class="control-group">
						<label class="control-label">Fullname</label>
						<div class="controls">
							<div class="input-prepend">
								<span class="add-on"><i class="icon-user"></i></span>
								<input type="text" id="fullname" name="fullname" placeholder="Fullname" class="input-xlarge" value="<?php 
if (isset($credit->fullname)) {
    echo $credit->fullname;
}
?>
" />
Example #15
0
 private function save($publicId = null)
 {
     $action = Input::get('action');
     $entityType = Input::get('entityType');
     if ($action == 'archive' || $action == 'delete' || $action == 'mark') {
         return InvoiceController::bulk($entityType);
     }
     $input = json_decode(Input::get('data'));
     $invoice = $input->invoice;
     if (Utils::isAdmin()) {
         $branch_id = $input->invoice->branch_id;
         $branch = Branch::where('account_id', '=', Auth::user()->account_id)->where('public_id', $branch_id)->first();
         // $branch = DB::table('branches')->where('id',$branch_id)->first();
     } else {
         $branch = Auth::user()->branch;
         $branch_id = $branch->id;
         $branch = DB::table('branches')->where('id', $branch_id)->first();
     }
     $today = new DateTime('now');
     $today = $today->format('Y-m-d');
     $datelimit = DateTime::createFromFormat('Y-m-d', $branch->deadline);
     $datelimit = $datelimit->format('Y-m-d');
     $valoresPrimera = explode("-", $datelimit);
     $valoresSegunda = explode("-", $today);
     $diaPrimera = $valoresPrimera[2];
     $mesPrimera = $valoresPrimera[1];
     $anyoPrimera = $valoresPrimera[0];
     $diaSegunda = $valoresSegunda[2];
     $mesSegunda = $valoresSegunda[1];
     $anyoSegunda = $valoresSegunda[0];
     $a = gregoriantojd($mesPrimera, $diaPrimera, $anyoPrimera);
     $b = gregoriantojd($mesSegunda, $diaSegunda, $anyoSegunda);
     $errorS = "Expiró la fecha límite de " . $branch->name;
     if ($a - $b < 0) {
         Session::flash('error', $errorS);
         return Redirect::to("{$entityType}s/create")->withInput();
     } else {
         $last_invoice = Invoice::where('account_id', '=', Auth::user()->account_id)->first();
         if ($last_invoice) {
             $yesterday = $last_invoice->invoice_date;
             $today = date("Y-m-d", strtotime($invoice->invoice_date));
             $errorD = "La fecha de la factura es incorrecta";
             $yesterday = new DateTime($yesterday);
             $today = new DateTime($today);
             if ($yesterday > $today) {
                 Session::flash('error', $errorD);
                 return Redirect::to("{$entityType}s/create")->withInput();
             }
         }
         if ($errors = $this->invoiceRepo->getErrors($invoice)) {
             Session::flash('error', trans('texts.invoice_error'));
             return Redirect::to("{$entityType}s/create")->withInput()->withErrors($errors);
         } else {
             $this->taxRateRepo->save($input->tax_rates);
             $clientData = (array) $invoice->client;
             $clientData['branch'] = $branch->id;
             $client = $this->clientRepo->save($invoice->client->public_id, $clientData);
             $invoiceData = (array) $invoice;
             $invoiceData['branch_id'] = $branch->id;
             $invoiceData['client_id'] = $client->id;
             $invoiceData['client_nit'] = $client->nit;
             $invoiceData['client_name'] = $client->name;
             $invoiceData['action'] = $action;
             $invoice = $this->invoiceRepo->save($publicId, $invoiceData, $entityType);
             $account = Auth::user()->account;
             // if ($account->invoice_taxes != $input->invoice_taxes
             // 			|| $account->invoice_item_taxes != $input->invoice_item_taxes
             // 			|| $account->invoice_design_id != $input->invoice->invoice_design_id)
             // {
             // 	$account->invoice_taxes = $input->invoice_taxes;
             // 	$account->invoice_item_taxes = $input->invoice_item_taxes;
             // 	$account->invoice_design_id = $input->invoice->invoice_design_id;
             // 	$account->save();
             // }
             $client->load('contacts');
             $sendInvoiceIds = [];
             foreach ($client->contacts as $contact) {
                 if ($contact->send_invoice || count($client->contacts) == 1) {
                     $sendInvoiceIds[] = $contact->id;
                 }
             }
             foreach ($client->contacts as $contact) {
                 $invitation = Invitation::scope()->whereContactId($contact->id)->whereInvoiceId($invoice->id)->first();
                 if (in_array($contact->id, $sendInvoiceIds) && !$invitation) {
                     $invitation = Invitation::createNew();
                     $invitation->invoice_id = $invoice->id;
                     $invitation->contact_id = $contact->id;
                     $invitation->invitation_key = str_random(RANDOM_KEY_LENGTH);
                     $invitation->save();
                 } else {
                     if (!in_array($contact->id, $sendInvoiceIds) && $invitation) {
                         $invitation->delete();
                     }
                 }
             }
             $invoice_date = date("d/m/Y", strtotime($invoice->invoice_date));
             require_once app_path() . '/includes/BarcodeQR.php';
             // $ice = $invoice->amount-$invoice->fiscal;
             $desc = $invoice->subtotal - $invoice->amount;
             $subtotal = number_format($invoice->subtotal, 2, '.', '');
             $amount = number_format($invoice->amount, 2, '.', '');
             $fiscal = number_format($invoice->fiscal, 2, '.', '');
             // $icef = number_format($ice, 2, '.', '');
             $descf = number_format($desc, 2, '.', '');
             // if($icef=="0.00"){
             //   $icef = 0;
             // }
             if ($descf == "0.00") {
                 $descf = 0;
             }
             $icef = 0;
             $qr = new BarcodeQR();
             $datosqr = $invoice->account_nit . '|' . $invoice->invoice_number . '|' . $invoice->number_autho . '|' . $invoice_date . '|' . $subtotal . '|' . $amount . '|' . $invoice->control_code . '|' . $invoice->client_nit . '|' . $icef . '|0|0|' . $descf;
             $qr->text($datosqr);
             $qr->draw(150, 'qr/' . $account->account_key . '_' . $branch->name . '_' . $invoice->invoice_number . '.png');
             $input_file = 'qr/' . $account->account_key . '_' . $branch->name . '_' . $invoice->invoice_number . '.png';
             $output_file = 'qr/' . $account->account_key . '_' . $branch->name . '_' . $invoice->invoice_number . '.jpg';
             $inputqr = imagecreatefrompng($input_file);
             list($width, $height) = getimagesize($input_file);
             $output = imagecreatetruecolor($width, $height);
             $white = imagecolorallocate($output, 255, 255, 255);
             imagefilledrectangle($output, 0, 0, $width, $height, $white);
             imagecopy($output, $inputqr, 0, 0, 0, 0, $width, $height);
             imagejpeg($output, $output_file);
             $invoice->qr = HTML::image_data('qr/' . $account->account_key . '_' . $branch->name . '_' . $invoice->invoice_number . '.jpg');
             $invoice->save();
             $message = trans($publicId ? "texts.updated_{$entityType}" : "texts.created_{$entityType}");
             if ($input->invoice->client->public_id == '-1') {
                 $message = $message . ' ' . trans('texts.and_created_client');
                 $url = URL::to('clients/' . $client->public_id);
                 Utils::trackViewed($client->getDisplayName(), ENTITY_CLIENT, $url);
             }
             if ($action == 'clone') {
                 return $this->cloneInvoice($publicId);
             } else {
                 if ($action == 'convert') {
                     return $this->convertQuote($publicId);
                 } else {
                     if ($action == 'email') {
                         $aux = 0;
                         foreach ($client->contacts as $contact) {
                             if ($contact->email) {
                                 $aux = 1;
                             }
                         }
                         if ($aux == 0) {
                             $errorMessage = trans('El cliente no tiene Correo Electrónico.');
                             Session::flash('error', $errorMessage);
                         } else {
                             if (Auth::user()->confirmed && !Auth::user()->isDemo()) {
                                 $message = trans("texts.emailed_{$entityType}");
                                 $this->mailer->sendInvoice($invoice);
                                 Session::flash('message', $message);
                             } else {
                                 $errorMessage = trans(Auth::user()->registered ? 'texts.confirmation_required' : 'texts.registration_required');
                                 Session::flash('error', $errorMessage);
                                 Session::flash('message', $message);
                             }
                         }
                     } else {
                         if ($action == 'savepay') {
                             $payment = Payment::createNew();
                             $payment->client_id = $client->id;
                             $payment->invoice_id = $invoice->id;
                             $payment->payment_type_id = 1;
                             $payment->payment_date = $invoice->invoice_date;
                             $payment->amount = $invoice->amount;
                             $payment->save();
                             $message = trans("texts.savepay_{$entityType}");
                             Session::flash('message', $message);
                         } else {
                             if ($action == 'savepaycredit') {
                                 $payment = Payment::createNew();
                                 $credits = Credit::scope()->where('client_id', '=', $client->id)->where('balance', '>', 0)->orderBy('created_at')->get();
                                 $applied = 0;
                                 foreach ($credits as $credit) {
                                     $applied += $credit->apply($invoice->amount);
                                     if ($applied >= $invoice->amount) {
                                         break;
                                     }
                                 }
                                 $payment->client_id = $client->id;
                                 $payment->invoice_id = $invoice->id;
                                 $payment->payment_type_id = 2;
                                 $payment->payment_date = $invoice->invoice_date;
                                 $payment->amount = $invoice->amount;
                                 $payment->save();
                                 $message = trans("texts.savepay_{$entityType}");
                                 Session::flash('message', $message);
                             } else {
                                 Session::flash('message', $message);
                             }
                         }
                     }
                 }
             }
             $url = "{$entityType}s/" . $invoice->public_id . '/edit';
             return Redirect::to($url);
         }
     }
 }
Example #16
0
    }
    if ($callerid2 == "") {
        $error_txt .= _("Reseller number") . " 2 " . _("is empty") . "<br/>";
    }
    if ($amount == "" || $amount == 0 || !is_numeric($amount)) {
        $error_txt .= _("Invalid amount") . "<br/>";
    }
}
if (isset($_POST['add_credit']) && $error_txt != "") {
    print_form(1, $error_txt);
} elseif (isset($_POST['add_credit']) && $error_txt == "") {
    // get some data out based on user input
    $callerid = $_POST['callerid1'];
    $amount = $_POST['amount'];
    echo "<center>";
    $cred = new Credit();
    try {
        $cred->add_to_reseller($callerid, $amount);
        echo "<img src='img/true.png' width='200' height='170' /><br/><br/>";
        echo "<span style='font-size: 20px;'>" . _("Credit of") . " <b>{$amount}</b> " . _("pesos successfully added to reseller") . " <b>{$callerid}</b>.</span><br/><br/><br/>";
        echo "<a href='resellers_credit.php'><button class='b1'>" . _("Go Back") . "</button></a>";
    } catch (CreditException $e) {
        echo "<img src='img/false.png' width='200' height='170' /><br/><br/>";
        echo "<span style='font-size: 20px; color: red;'>" . _("ERROR UPDATING BALANCE!") . "<br/>" . $e->getMessage() . " </span><br/><br/><br/><br/>";
        echo "<a href='resellers_credit.php'><button class='b1'>" . _("Go Back") . "</button></a>";
    }
    echo "</center>";
} else {
    print_form(0, '');
}
?>
include_layout_template("header.php");
?>

<!--The Main Content Here Please-->


<!-- beginnning of main content-->
<div class="container">
	<div class="row-fluid">
		<div class="span9" >
			<h4>Developers Information Page</h4>
	        <hr>	
	 	</div>
	</div>
    <?php 
$credit = Credit::find_by_id(customDecrypt($_GET['id']));
?>
    <form class="form-horizontal credit" id="credit">
					
					<div class="control-group">
						<label class="control-label">Fullname</label>
						<div class="controls">
							<div class="input-prepend">
								<span class="add-on"><i class="icon-user"></i></span>
								<input type="text" id="fullname" name="fullname" placeholder="Fullname" class="input-xlarge" value="<?php 
if (isset($credit->fullname)) {
    echo $credit->fullname;
}
?>
" readonly />
							</div>
Example #18
0
        return '';
    }
    public function getEntityType()
    {
        return ENTITY_CREDIT;
    }
    public function apply($amount)
    {
        if ($amount > $this->balance) {
            $applied = $this->balance;
            $this->balance = 0;
        } else {
            $applied = $amount;
            $this->balance = $this->balance - $amount;
        }
        $this->save();
        return $applied;
    }
}
Credit::created(function ($credit) {
    Activity::createCredit($credit);
});
Credit::updating(function ($credit) {
    Activity::updateCredit($credit);
});
Credit::deleting(function ($credit) {
    Activity::archiveCredit($credit);
});
Credit::restoring(function ($credit) {
    Activity::restoreCredit($credit);
});
Example #19
0
<?php

require_once '../../inc/initialize.php';
if ($_FILES['picture']['size'] < $_POST['MAX_FILE_SIZE']) {
    $credit = new Credit();
    $credit->fullname = $_POST['fullname'];
    $credit->email = $_POST['email'];
    $credit->phone = $_POST['phone'];
    $credit->role = $_POST['role'];
    $filename = str_replace(' ', '.', $credit->fullname);
    $extention = explode('.', $_FILES['picture']['name']);
    $extention = "." . $extention[sizeof($extention) - 1];
    $credit->aboutyou = $_POST['aboutyou'];
    $credit->status = $_POST['status'];
    $target_path = SITE_ROOT . DS . "documents" . DS . "credit_passports" . DS . $filename . $extention;
    move_uploaded_file($_FILES['picture']['tmp_name'], $target_path);
    $credit->passport = $filename . $extention;
    if (isset($_POST['credit_id']) && !empty($_POST['credit_id'])) {
        $credit->credit_id = $_POST['credit_id'];
    } else {
        $credit_exist_query = "SELECT * from credits WHERE email = '" . $_POST['email'] . "' OR fullname = '" . $_POST['fullname'] . "' OR passport = '" . $target_path . "'";
        $credit_exist = Credit::find_by_sql($credit_exist_query);
        $credit_exist = array_shift($credit_exist);
        if ($credit_exist) {
            $credit->credit_id = $credit_exist->credit_id;
        }
    }
    if ($credit->save()) {
        sleep(2);
        echo '<h4 class="alert alert-success">Success</h4>';
        echo '<hr>';
Example #20
0
 private function delCredit()
 {
     if (Ibos::app()->getRequest()->getIsAjaxRequest()) {
         $id = EnvUtil::getRequest("id");
         $affected = Credit::model()->deleteByPk($id);
         if ($affected) {
             $this->ajaxReturn(array("IsSuccess" => true));
         }
     }
 }
Example #21
0
 public function getMaxCredit($client_id)
 {
     $credit = Credit::where('account_id', Auth::user()->account_id)->where('client_id', $client_id)->get();
     $credito = 0;
     foreach ($credit as $cre) {
         $credito += $cre->balance;
     }
     return $credito;
 }
Example #22
0
 public static function createCredit($companyId, $type = self::FREE, $quantity = 10)
 {
     return Credit::create(["company_id" => $companyId, "type" => $type, "quantity" => $quantity]);
 }
Example #23
0
    }
    public function getName()
    {
        return '';
    }
    public function getEntityType()
    {
        return ENTITY_CREDIT;
    }
    public function apply($amount)
    {
        if ($amount > $this->balance) {
            $applied = $this->balance;
            $this->balance = 0;
        } else {
            $applied = $amount;
            $this->balance = $this->balance - $amount;
        }
        $this->save();
        return $applied;
    }
}
Credit::created(function ($credit) {
    Activity::createCredit($credit);
});
Credit::updating(function ($credit) {
    Activity::updateCredit($credit);
});
Credit::deleting(function ($credit) {
    Activity::archiveCredit($credit);
});
 /**
  * Remove the specified resource from storage.
  * DELETE /credit/{id}
  *
  * @param  int  $id
  * @return Response
  */
 public function destroy($id)
 {
     Credit::find($id)->delete();
     return Redirect::route('credit');
 }
Example #25
0
 public function setAmount($amount)
 {
     if (is_null($amount)) {
         $this->fv_amount = "Factura " . ERROR_NULL . "<br>";
         return;
     }
     $credit = Credit::where('account_id', $this->getAccountId())->where('client_id', $this->getClientId())->get();
     $invoice = Invoice::where('id', $this->getInvoiceId())->first();
     $credito = 0;
     foreach ($credit as $cre) {
         $credito += $cre->balance;
     }
     //echo $amount." - ".$credito;
     if ($credito < $amount && $this->getPaymentTypeId() == 2) {
         $this->fv_amount = "No tiene suficiente crédito para realizar este pago.";
         return;
     }
     if ($invoice->balance < $amount) {
         $this->fv_amount = "No es posible pagar mas de lo adeudado.";
         return;
     }
     if ($amount <= 0) {
         $this->fv_amount = "El monto no puede ser menor o igual a 0";
         return;
     }
     $this->fv_amount = null;
     $this->amount = $amount;
     return $this;
 }
 /**
  * Returns the data model based on the primary key given in the GET variable.
  * If the data model is not found, an HTTP exception will be raised.
  * @param integer $id the ID of the model to be loaded
  * @return Credit the loaded model
  * @throws CHttpException
  */
 public function loadModel($id)
 {
     $model = Credit::model()->findByPk($id);
     if ($model === null) {
         throw new CHttpException(404, 'The requested page does not exist.');
     }
     return $model;
 }
Example #27
0
 private function save($publicId = null)
 {
     $action = Input::get('action');
     $entityType = Input::get('entityType');
     if ($action == 'archive' || $action == 'delete' || $action == 'mark') {
         return InvoiceController::bulk($entityType);
     }
     $input = json_decode(Input::get('data'));
     //echo "this is the result";
     $invoice = $input->invoice;
     //print_r($invoice);exit();
     $branch = Branch::where('account_id', '=', Auth::user()->account_id)->where('id', Auth::user()->branch_id)->first();
     $today = new DateTime('now');
     $today = $today->format('Y-m-d');
     $datelimit = DateTime::createFromFormat('Y-m-d', $branch->deadline);
     $datelimit = $datelimit->format('Y-m-d');
     $first = explode("-", $datelimit);
     $second = explode("-", $today);
     $first_day = $first[2];
     $first_month = $first[1];
     $first_year = $first[0];
     $second_day = $second[2];
     $second_month = $second[1];
     $second_year = $second[0];
     $a = gregoriantojd($first_month, $first_day, $first_year);
     $b = gregoriantojd($second_month, $second_day, $second_year);
     $errorS = "Expiró la Fecha Límite de " . $branch->name;
     if ($a - $b < 0) {
         Session::flash('error', $errorS);
         return Redirect::to("{$entityType}s/create")->withInput();
     } else {
         $last_invoice = Invoice::where('account_id', '=', Auth::user()->account_id)->first();
         if ($last_invoice) {
             $yesterday = $last_invoice->invoice_date;
             $today = date("Y-m-d", strtotime($invoice->invoice_date));
             $errorD = "La fecha de la factura es incorrecta";
             $yesterday = new DateTime($yesterday);
             $today = new DateTime($today);
             if ($yesterday > $today) {
                 Session::flash('error', $errorD);
                 return Redirect::to("{$entityType}s/create")->withInput();
             }
         }
         if (false && ($errors = $this->invoiceRepo->getErrors($invoice))) {
             Session::flash('error', trans('texts.invoice_error'));
             return Redirect::to("{$entityType}s/create")->withInput()->withErrors($errors);
         } else {
             //$this->taxRateRepo->save($input->tax_rates);
             $clientData = (array) $invoice->client;
             $clientData['branch'] = $branch->id;
             $client = $this->saveClient($invoice->client->public_id, $clientData);
             $invoiceData = (array) $invoice;
             $invoiceData['branch_id'] = $branch->id;
             $invoiceData['client_id'] = $client->id;
             $invoiceData['client_nit'] = $client->nit;
             $invoiceData['client_name'] = $client->name;
             $invoiceData['action'] = $action;
             //$invoice = $this->invoiceRepo->save($publicId, $invoiceData, $entityType);
             $account = Auth::user()->account;
             $client->load('contacts');
             $sendInvoiceIds = [];
             foreach ($client->contacts as $contact) {
                 if ($contact->send_invoice || count($client->contacts) == 1) {
                     $sendInvoiceIds[] = $contact->id;
                 }
             }
             /*foreach ($client->contacts as $contact)
             			{
             				$invitation = Invitation::scope()->whereContactId($contact->id)->whereInvoiceId($invoice->id)->first();
             
             				if (in_array($contact->id, $sendInvoiceIds) && !$invitation)
             				{
             					$invitation = Invitation::createNew();
             					$invitation->invoice_id = $invoice->id;
             					$invitation->contact_id = $contact->id;
             					$invitation->invitation_key = str_random(RANDOM_KEY_LENGTH);
             					$invitation->save();
             				}
             				else if (!in_array($contact->id, $sendInvoiceIds) && $invitation)
             				{
             					$invitation->delete();
             				}
             			}*/
             $message = trans($publicId ? "texts.updated_{$entityType}" : "texts.created_{$entityType}");
             if ($input->invoice->client->public_id == '-1') {
                 $message = $message . ' ' . trans('texts.and_created_client');
                 $url = URL::to('clients/' . $client->public_id);
                 Utils::trackViewed($client->getDisplayName(), ENTITY_CLIENT, $url);
             }
             if ($action == 'email') {
                 $aux = 0;
                 foreach ($client->contacts as $contact) {
                     if ($contact->email) {
                         $aux = 1;
                     }
                 }
                 if ($aux == 0) {
                     $errorMessage = trans('El cliente no tiene Correo Electrónico.');
                     Session::flash('error', $errorMessage);
                 } else {
                     if (Auth::user()->confirmed && !Auth::user()->isDemo()) {
                         $message = trans("texts.emailed_{$entityType}");
                         $this->mailer->sendInvoice($invoice);
                         Session::flash('message', $message);
                     } else {
                         $errorMessage = trans(Auth::user()->registered ? 'texts.confirmation_required' : 'texts.registration_required');
                         Session::flash('error', $errorMessage);
                         Session::flash('message', $message);
                     }
                 }
             } else {
                 if ($action == 'savepay') {
                     $payment = Payment::createNew();
                     $payment->client_id = $client->id;
                     $payment->invoice_id = $invoice->id;
                     $payment->payment_type_id = 1;
                     $payment->payment_date = $invoice->invoice_date;
                     $payment->amount = $invoice->amount;
                     $payment->save();
                     $message = trans("texts.savepay_{$entityType}");
                     Session::flash('message', $message);
                 } else {
                     if ($action == 'savepaycredit') {
                         $payment = Payment::createNew();
                         $credits = Credit::scope()->where('client_id', '=', $client->id)->where('balance', '>', 0)->orderBy('created_at')->get();
                         $applied = 0;
                         foreach ($credits as $credit) {
                             $applied += $credit->apply($invoice->amount);
                             if ($applied >= $invoice->amount) {
                                 break;
                             }
                         }
                         $payment->client_id = $client->id;
                         $payment->invoice_id = $invoice->id;
                         $payment->payment_type_id = 2;
                         $payment->payment_date = $invoice->invoice_date;
                         $payment->amount = $invoice->amount;
                         $payment->save();
                         $message = trans("texts.savepay_{$entityType}");
                         Session::flash('message', $message);
                     } else {
                         Session::flash('message', $message);
                     }
                 }
             }
             //$url = "factura/" . $invoice->public_id . '/show';
             $url = "factura/1";
             return Redirect::to($url);
         }
     }
 }
Example #28
0
<div class="clear"></div>
<form name="payment_form" id="payment_form" method="post" action="" >
<div class="grid_10 push_1">
        <div class="credit_box">
                <div class="credit_pic">
                        <h2>เติมเครดิต</h2>
                </div>
                <div class="credit_select">
                        <h2>เลือกจำนวนเครดิตที่ต้องการเติม</h2>
                                <?php 
$criteria = new CDbCriteria();
$criteria->select = '*';
$criteria->condition = 'credit_status=:status ';
$criteria->params = array(':status' => 1);
$criteria->order = 'credit_order';
$credits = Credit::model()->findAll($criteria);
?>
                                <ul>

                                     <?php 
$i = 1;
foreach ($credits as $credit) {
    ?>
                                        <li>
                                                <input type="radio" id="tick_<?php 
    echo $i;
    ?>
" name="tick" value="<?php 
    echo $credit->credit_amount;
    ?>
"/>
Example #29
0
 /**
  * Display the specified resource.
  *
  * @param int $id
  * @return Response
  */
 public function show($publicId)
 {
     $client = Client::scope($publicId)->withTrashed()->with('contacts')->first();
     if ($client) {
         //$client = Client::scope($publicId)->with('contacts')->firstOrFail();
         $getTotalCredit = Credit::scope()->where('client_id', '=', $client->id)->whereNull('deleted_at')->where('balance', '>', 0)->sum('balance');
         $invoices = Invoice::join('invoice_statuses', 'invoice_statuses.id', '=', 'invoices.invoice_status_id')->where('invoices.account_id', Auth::user()->account_id)->where('invoices.client_id', $client->id)->where('invoices.branch_id', Session::get('branch_id'))->select('invoices.invoice_number', 'invoices.invoice_date', 'invoices.importe_total', 'invoices.balance', 'invoices.due_date', 'invoice_statuses.name', 'invoices.public_id')->get();
         $pagos = Payment::join('invoices', 'invoices.id', '=', 'payments.invoice_id')->join('payment_types', 'payment_types.id', '=', 'payments.payment_type_id')->where('payments.account_id', Auth::user()->account_id)->where('payments.client_id', $client->id)->select('invoices.invoice_number', 'payments.transaction_reference', 'payment_types.name', 'payments.amount', 'payments.payment_date')->get();
         $creditos = Credit::where('account_id', '=', Auth::user()->account_id)->where('client_id', '=', $client->getId())->get();
         $data = array('title' => 'Ver Cliente', 'client' => $client, 'invoices' => $invoices, 'pagos' => $pagos, 'credit' => $getTotalCredit, 'creditos' => $creditos);
         // return Response::json($data);
         return View::make('clientes.show', $data);
     }
     Session::flash('error', 'No existe el usuario');
     return Redirect::to('clientes');
 }
 private function export()
 {
     $output = fopen('php://output', 'w') or Utils::fatalError();
     header('Content-Type:application/csv');
     header('Content-Disposition:attachment;filename=export.csv');
     $clients = Client::scope()->get();
     AccountController::exportData($output, $clients->toArray());
     $contacts = Contact::scope()->get();
     AccountController::exportData($output, $contacts->toArray());
     $invoices = Invoice::scope()->get();
     AccountController::exportData($output, $invoices->toArray());
     $invoiceItems = InvoiceItem::scope()->get();
     AccountController::exportData($output, $invoiceItems->toArray());
     $payments = Payment::scope()->get();
     AccountController::exportData($output, $payments->toArray());
     $credits = Credit::scope()->get();
     AccountController::exportData($output, $credits->toArray());
     fclose($output);
     exit;
 }