Beispiel #1
0
 function exchange($val)
 {
     $date = sqlDate('now');
     $kes = $this->getDi()->currencyExchangeTable->getRate('KES', $date);
     $usd = $this->getDi()->currencyExchangeTable->getRate('USD', $date);
     return moneyRound($val * $kes / $usd);
 }
Beispiel #2
0
 function addTo($date)
 {
     if ($this->isEmpty()) {
         throw new Am_Exception_InternalError("Could not do this operation on empty object " . __METHOD__);
     }
     if ($this->unit == self::FIXED) {
         return $this->count;
     }
     list($y, $m, $d) = explode('-', sqlDate($date));
     $tm = amstrtotime($date);
     switch ($this->unit) {
         case self::DAY:
             $tm2 = mktime(0, 0, 0, $m, $d + $this->count, $y);
             break;
         case self::MONTH:
             $tm2 = mktime(0, 0, 0, $m + $this->count, $d, $y);
             break;
         case self::YEAR:
             $tm2 = mktime(0, 0, 0, $m, $d, $y + $this->count);
             break;
         default:
             throw new Am_Exception_InternalError("Unknown period unit configured in " . $this->__toString());
     }
     if ($tm2 < $tm) {
         // overflow, assign fixed "lifetime" date
         return self::MAX_SQL_DATE;
     }
     return date('Y-m-d', $tm2);
 }
Beispiel #3
0
 public function onSubscriptionDeleted(Am_Event_SubscriptionDeleted $event)
 {
     if (!$this->getConfig('expired_list')) {
         return;
     }
     $user = $event->getUser();
     $lmDb = $this->getConfig('db') . '.' . $this->getConfig('prefix');
     Am_Di::getInstance()->db->query("\n            INSERT INTO {$lmDb}users\n                (uid,list,fname,lname,email,cseq,cdel,cnf,dateadd,htmail)\n            VALUES\n                (?,?,?,?,?, 1, 0, 1, ?, 1)\n            ", $this->_getUniqUid(), $this->getConfig('expired_list'), $user->name_f, $user->name_l, $user->email, sqlDate(time()));
 }
 public function insert($reload = true)
 {
     if ($this->currency == Am_Currency::getDefault()) {
         $this->base_currency_multi = 1.0;
     } else {
         $this->base_currency_multi = $this->getDi()->currencyExchangeTable->getRate($this->currency, sqlDate($this->dattm));
     }
     parent::insert($reload);
     $this->getDi()->hook->call(new Am_Event_PaymentAfterInsert(null, array('payment' => $this, 'invoice' => $this->getInvoice(), 'user' => $this->getInvoice()->getUser())));
     return $this;
 }
 public function insert($reload = true)
 {
     if ($this->currency == Am_Currency::getDefault()) {
         $this->base_currency_multi = 1.0;
     } else {
         $this->base_currency_multi = $this->getDi()->currencyExchangeTable->getRate($this->currency, sqlDate($this->dattm));
     }
     $ret = parent::insert($reload);
     $this->getDi()->hook->call('refundAfterInsert', array('invoice' => $this->getInvoice(), 'refund' => $this, 'user' => $this->getInvoice()->getUser()));
     return $ret;
 }
Beispiel #6
0
 /**
  * @return int status constant
  */
 function getStatus()
 {
     $now = sqlDate('now');
     if ($this->expire_date < $now) {
         return self::EXPIRED;
     }
     if ($this->begin_date > $now) {
         return self::FUTURE;
     }
     return self::ACTIVE;
 }
    function init()
    {
        $this->addText('users_count')->setLabel(___('Generate Users Count'))->setValue(100);
        $this->addText('email_domain')->setLabel(___("Email Domain\nused to generate email address for users"))->setValue('cgi-central.int');
        if ($this->isProductsExists()) {
            $this->addCheckbox('do_not_generate_products', array('checked' => 'checked'))->setLabel(___("Do not generate products\n" . "use existing products for demo records"))->setId('form-do-not-generate-products');
            $this->addMagicSelect('product_ids')->setLabel(___("Use the following product for demo users\n" . 'keep it empty to use any products'))->setId('form-product_ids')->loadOptions(Am_Di::getInstance()->productTable->getOptions());
            $script = <<<CUT
\$(function() {

    function toggle_do_not_generate_products() {
        if (\$('input[name=do_not_generate_products]').prop('checked')) {
            \$('#form-products-count').parents('.row').hide();
            \$('#form-product_ids').parents('.row').show();
        } else {
            \$('#form-products-count').parents('.row').show();
            \$('#form-product_ids').parents('.row').hide();
        }
    }

    toggle_do_not_generate_products()

    \$('input[name=do_not_generate_products]').bind('change', function(){
        toggle_do_not_generate_products();
    })
});
CUT;
            $this->addScript('script')->setScript($script);
        }
        $this->addText('products_count', array('size' => 3))->setLabel(___('Generate Products Count'))->setValue(3)->setId('form-products-count');
        $gr = $this->addGroup()->setLabel(___('Invoices Per User'));
        $gr->addText('invoices_per_user', array('size' => 3))->setValue(2);
        $gr->addStatic()->setContent(' +/- ');
        $gr->addText('invoices_per_user_variation', array('size' => 3))->setValue(1);
        $gr = $this->addGroup()->setLabel(___('Products Per Invoice'));
        $gr->addText('products_per_invoice', array('size' => 3))->setValue(2);
        $gr->addStatic()->setContent(' +/- ');
        $gr->addText('products_per_invoice_variation', array('size' => 3))->setValue(1);
        $gr = $this->addGroup()->setLabel(___('Period'));
        $gr->setSeparator(' ');
        $gr->addDate('date_begin', array('size' => 8))->setValue(sqlDate('-60 days'));
        $gr->addDate('date_end', array('size' => 8))->setValue(sqlDate('now'));
        parent::init();
        $this->addSaveButton(___('Generate'));
    }
Beispiel #8
0
 public function run()
 {
     $this->grid->getDi()->plugins_payment->loadEnabled()->getAllEnabled();
     $ds = $this->grid->getDataSource();
     $fn = tempnam(DATA_DIR, 'zip_');
     $zip = new ZipArchive();
     $zip->open($fn, ZipArchive::OVERWRITE);
     $st = $ds->query();
     while ($iprec = $this->grid->getDi()->db->fetchRow($st)) {
         $ip = $ds->getDataSourceQuery()->getTable()->createRecord($iprec);
         $pdf = Am_Pdf_Invoice::create($ip);
         $zip->addFromString($pdf->getFileName(), $pdf->render());
     }
     $zip->close();
     register_shutdown_function(array($this, 'cleanup'), $fn);
     $helper = new Am_Controller_Action_Helper_SendFile();
     $helper->sendFile($fn, 'application/octet-stream', array('filename' => sprintf('invoices-%s.zip', sqlDate('now'))));
 }
 function run()
 {
     $form = new Am_Form_Admin('form-grid-payout');
     $form->setAttribute('name', 'payout');
     $date = $form->addDate('payout_date')->setLabel(___('Payout Date'))->setValue(sqlDate($this->getDi()->dateTime));
     foreach ($this->grid->getVariablesList() as $k) {
         $form->addHidden($this->grid->getId() . '_' . $k)->setValue($this->grid->getRequest()->get($k, ""));
     }
     $form->addSaveButton(___("Run Payout"));
     $form->setDataSources(array($this->grid->getCompleteRequest()));
     if ($form->isSubmitted() && $form->validate()) {
         $values = $form->getValue();
         $this->getDi()->affCommissionTable->runPayout($values['payout_date']);
         $this->grid->redirectBack();
     } else {
         echo $this->renderTitle();
         echo $form;
     }
 }
Beispiel #10
0
 public function indexAction()
 {
     /* @var $invoice Invoice */
     $invoice = $this->getDi()->invoiceTable->findBySecureId($this->getParam('secure_id'), 'payment-link');
     if (!$invoice || $invoice->status != Invoice::PENDING) {
         throw new Am_Exception_InternalError(sprintf('Unknow invoice [%s] or invoice is already processed', filterId($this->getParam('secure_id'))));
     }
     if (!$invoice->due_date && sqlDate($invoice->tm_added) < sqlDate("-" . Invoice::DEFAULT_DUE_PERIOD . " days")) {
         throw new Am_Exception_InputError(___('Invoice is expired'));
     } elseif ($invoice->due_date && $invoice->due_date < sqlDate('now')) {
         throw new Am_Exception_InputError(___('Invoice is expired'));
     }
     $form = new Am_Form();
     if (!$invoice->paysys_id) {
         $psOptions = array();
         foreach (Am_Di::getInstance()->paysystemList->getAllPublic() as $ps) {
             $psOptions[$ps->getId()] = $this->renderPaysys($ps);
         }
         $paysys = $form->addAdvRadio('paysys_id')->setLabel(___('Payment System'))->loadOptions($psOptions);
         $paysys->addRule('required', ___('Please choose a payment system'));
         if (count($psOptions) == 1) {
             $paysys->toggleFrozen(true);
         }
     }
     $form->addSaveButton(___('Pay'));
     $this->view->invoice = $invoice;
     $this->view->form = $form;
     $form->setDataSources(array($this->getRequest()));
     if ($form->isSubmitted() && $form->validate()) {
         $vars = $form->getValue();
         if (!$invoice->paysys_id) {
             $invoice->setPaysystem($vars['paysys_id']);
             $invoice->save();
         }
         $payProcess = new Am_Paysystem_PayProcessMediator($this, $invoice);
         $result = $payProcess->process();
         throw new Am_Exception_InternalError(sprintf('Error occurred while trying proccess invoice [%s]', filterId($invoice->public_id)));
     }
     $this->view->layoutNoMenu = true;
     $this->view->display('pay.phtml');
 }
Beispiel #11
0
 private function seed()
 {
     $parser = new Csv();
     $parser->setFilePath(DOC_ROOT . '/data/restaurants.csv');
     $data = $parser->parse();
     if ($data === false) {
         echo "Error parsing CSV";
         return 1;
     }
     foreach ($data as $row) {
         $restaurant = ORM::for_table("restaurants")->create();
         $name = $row["restaurant_name"];
         $restaurant->restaurant_name = $name;
         $restaurant->cuisine_type = $row["cuisine_type"];
         $restaurant->created = sqlDate();
         $restaurant->updated = sqlDate();
         $restaurant->save();
         echo "Created restaurant `{$name}` \n";
     }
     return 0;
 }
 public function getAddForm()
 {
     $form = new Am_Form_Admin();
     $form->setAction($url = $this->getUrl(null, 'c', null, 'payments', 'addpayment', 'user_id', $this->user_id));
     $form->addText("receipt_id", array('tabindex' => 2))->setLabel("Receipt#")->addRule('required');
     $amt = $form->addSelect("amount", array('tabindex' => 3), array('intrinsic_validation' => false))->setLabel("Amount");
     $amt->addRule('required', 'This field is required');
     if ($this->_request->getInt('invoice_id')) {
         $invoice = $this->getDi()->invoiceTable->load($this->_request->getInt('invoice_id'));
         if (!$invoice->first_total || $invoice->getPaymentsCount()) {
             $amt->addOption($invoice->second_total, $invoice->second_total);
         } else {
             $amt->addOption($invoice->first_total, $invoice->first_total);
         }
     }
     $form->addSelect("paysys_id", array('tabindex' => 1))->setLabel("Payment System")->loadOptions($this->getDi()->paysystemList->getOptions());
     $date = $form->addDate("dattm", array('tabindex' => 4))->setLabel("Date Of Transaction");
     $date->addRule('required', 'This field is required');
     $date->setValue(sqlDate('now'));
     $form->addHidden("invoice_id");
     $form->addSaveButton();
     return $form;
 }
Beispiel #13
0
 public function getStartStop($key)
 {
     $start = $this->getStart($key);
     return array(sqlDate($start), sqlDate(strtotime('+3 month', $start) - 1));
 }
Beispiel #14
0
 public function onDaily(Am_Event $event)
 {
     $this->di->userTable->checkAllSubscriptions();
     $this->di->emailTemplateTable->sendCronExpires();
     $this->di->emailTemplateTable->sendCronAutoresponders();
     $this->di->emailTemplateTable->sendCronPendingNotifications();
     $this->di->store->cronDeleteExpired();
     $this->di->storeRebuild->cronDeleteExpired();
     Am_Auth_BruteforceProtector::cleanUp();
     if ($this->di->config->get('clear_access_log') && $this->di->config->get('clear_access_log_days') > 0) {
         $dat = sqlDate($this->di->time - $this->di->config->get('clear_access_log_days') * 3600 * 24);
         $this->di->accessLogTable->clearOld($dat);
     }
     if ($this->di->config->get('clear_inc_payments') && $this->di->config->get('clear_inc_payments_days') > 0) {
         $dat = sqlDate($this->di->time - $this->di->config->get('clear_inc_payments_days') * 3600 * 24);
         $this->di->invoiceTable->clearPending($dat);
     }
     if ($this->di->config->get('clear_inc_users') && $this->di->config->get('clear_inc_users_days') > 0) {
         $dat = sqlDate($this->di->time - $this->di->config->get('clear_inc_users_days') * 3600 * 24);
         $this->di->userTable->clearPending($dat);
     }
     $this->di->uploadTable->cleanUp();
     Am_Mail_Queue::getInstance()->cleanUp();
 }
Beispiel #15
0
 *		{user: "", pass: ""}
 *
 * Response Wrapper Body:
 *		{token: ..., expires: ...}
 */
include_once "utils.php";
include_once "model.php";
/** Validate **/
$username = requireParam("user");
$password = requireParam("pass");
$passwordHash = md5(md5($password) . $salt);
/** Check the DB for this user / pass combination **/
$account = Account::fromCredentials($username, $passwordHash);
if ($account == false) {
    error('User not found', 600);
}
if ($account->status != 1) {
    error('Account suspended', 601);
}
/** Kill old sessions **/
Session::clearForAccount($account->accountId);
/** Create a session **/
$session = new Session();
$session->sessionId = gen_uuid();
$session->accountId = $account->accountId;
$session->expires = sqlDate(time() + 1200);
if ($session->create()) {
    success(array('valid' => true, 'uid' => $account->uuid, 'sessionID' => $session->sessionId, 'sessionStart' => $session->created, 'sessionEnd' => $session->expires));
} else {
    error('Failed to create session', 602);
}
Beispiel #16
0
 public function actionSubmitpaypal()
 {
     $paypal = new GetExpressCheckoutDetails();
     $details = $paypal->getResponse();
     //$totalPrice = urldecode($details['AMT']);
     $what = urldecode($details['CUSTOM']);
     $desc = urldecode($details["DESC"]);
     $cst = $details["CUSTOM"];
     $cst = explode("_", $cst);
     $type = $cst[2];
     $cst = $cst[1];
     $discount = $cst[3];
     if ($type == "basic") {
         $totalPrice = "19.95";
     } else {
         if ($type == "basicplus") {
             $totalPrice = "24.95";
         } else {
             if ($type == "pro") {
                 $totalPrice = "29.95";
             }
         }
     }
     $prorate = round($totalPrice * (((double) date('t') - (double) date('j')) / (double) date('t')), 2);
     $initAmt = $prorate + 0;
     // switch ($_SESSION["discount"]) {
     //     case 'MFVideoMgr-100':
     //         $prorate = $initAmt = 0;
     //         break;
     //     case 'MFVM-50A':
     //         $prorate = round((float)$prorate * 0.50, 2);
     //         $initAmt = round((float)$initAmt * 0.50, 2);
     //         break;
     //     case 'MFVM25':
     //         $prorate = round((float)$prorate * 0.25, 2);
     //         $initAmt = round((float)$initAmt * 0.25, 2);
     //         break;
     // }
     if (isset($_SESSION["discount"])) {
         Yii::import('admin.models.*');
         $coupon = Coupon::model()->findByAttributes(array('name' => $_SESSION["discount"]));
         if ($coupon) {
             if ($coupon->discount >= 100) {
                 //$initAmt = $initAmt - (2*$initAmt);
                 $prorate = 0.01;
                 $initAmt = 0.01;
             } else {
                 $prorate = $prorate - round((double) $prorate * ($coupon->discount / 100), 2);
                 $initAmt = $initAmt - round((double) $initAmt * ($coupon->discount / 100), 2);
             }
         }
     }
     $payment = new DoExpressCheckoutPayment($initAmt);
     $payment_response1 = $payment->getResponse();
     $recur = new CreateRecurringPaymentsProfile(ucfirst($type) . " Subscription for VidMgr, {$totalPrice} /mo", $totalPrice);
     // \n $0 One Time Setup Fee
     $recur->setNVP("SUBSCRIBERNAME", user()->Name);
     $recur->setNVP("PROFILEREFERENCE", "userid_" . uid() . "_" . $cst);
     $recur->setNVP("PROFILESTARTDATE", date("Y-m-d\\TH:i:s\\Z", mktime(0, 0, 0, date("m") + 1, 1, date("y"))));
     $recur->setNVP("MAXFAILEDPAYMENTS", "1");
     $recur->setNVP("BILLINGPERIOD", "Month");
     $recur->setNVP("BILLINGFREQUENCY", "1");
     $recur->setNVP("CURRENCYCODE", "USD");
     $recur->setNVP('L_PAYMENTREQUEST_0_NAME0', "Video Subscription - Basic 40MB");
     $recur->setNVP('L_PAYMENTREQUEST_0_ITEMCATEGORY0', 'Digital');
     $recur->setNVP('L_PAYMENTREQUEST_0_AMT0', $totalPrice);
     $recur->setNVP('L_PAYMENTREQUEST_0_QTY0', "1");
     $recur->setNVP("INITAMT", $initAmt);
     $payment_response = $recur->getResponse();
     Ytrace($payment_response);
     Ytrace($details);
     if ($payment_response["ACK"] == "Success" && $payment_response1["ACK"] == "Success") {
         Video::model()->updateByPk($cst, array("active" => "1", "lastPayment" => sqlDate(), "payModel" => $type));
         User::model()->updateByPk(uid(), array("payModel" => $type, "coupon" => ""));
         $this->process($cst, $type);
     } else {
         $this->renderText("There was some problem in processing your request. Please try again. If you repeatedly face this error please use the contact page, we would love to help you.");
     }
 }
 /**
  * Process refund to rollback existing commissions
  */
 public function processRefund(Invoice $invoice, InvoiceRefund $refund)
 {
     if ($refund->invoice_payment_id) {
         $toRefund = $this->getDi()->affCommissionTable->findByInvoicePaymentId($refund->invoice_payment_id);
     } else {
         $toRefund = $this->getDi()->affCommissionTable->findLastRecordsByInvoiceId($refund->invoice_id);
     }
     foreach ($toRefund as $affCommission) {
         $void = $this->getDi()->affCommissionRecord;
         $void->fromRow($affCommission->toRow());
         $void->date = $refund ? $refund->dattm : sqlDate('now');
         $void->commission_id = null;
         $void->record_type = AffCommission::VOID;
         try {
             $void->insert();
         } catch (Am_Exception_Db_NotUnique $e) {
             // already handled? keep silence
         }
     }
 }
 public function run()
 {
     Am_Di::getInstance()->affCommissionTable->runPayout(sqlDate('now'));
     echo ___('Payout generated') . '.';
     echo $this->renderBackUrl();
 }
Beispiel #19
0
 public function beforeSave()
 {
     $tmpPassword = empty($this->password) ? '' : md5($this->password . "-SomeRandomSalt");
     if ($this->isNewRecord) {
         $this->hashkey = $tmpPassword;
         $this->createdAt = sqlDate();
         $this->confirmKey = $this->generateRandomString();
         $this->email = strtolower($this->email);
     }
     if ($this->scenario == 'adminUpdate') {
         if (!empty($tmpPassword) && $this->hashkey != $tmpPassword) {
             $this->hashkey = $tmpPassword;
         }
     }
     $this->lastvisit = sqlDate();
     return parent::beforeSave();
 }
Beispiel #20
0
 protected function sendPendingNotifications($day, $invoices, $tpls, $sendCallback)
 {
     foreach ($invoices as $invoice) {
         $user = $invoice->getUser();
         if (!$user) {
             continue;
         }
         foreach ($tpls as $tpl) {
             if ($this->isNotificationRuleMatch($tpl, $invoice)) {
                 if (!empty($this->_pendingSent[$sendCallback[1]][$invoice->getUser()->pk()])) {
                     continue;
                 }
                 $mailTpl = Am_Mail_Template::createFromEmailTemplate($tpl);
                 $mailTpl->setUser($invoice->getUser());
                 $mailTpl->setInvoice($invoice);
                 if ($invoice->due_date < sqlDate('+ 7 days')) {
                     $invoice->updateQuick('due_date', sqlDate('+ 7 days'));
                 }
                 $mailTpl->setPaylink(ROOT_SURL . sprintf('/pay/%s', $invoice->getSecureId('payment-link')));
                 $mailTpl->setDay($day);
                 $products = array();
                 foreach ($invoice->getProducts() as $product) {
                     $products[] = $product->getTitle();
                 }
                 $mailTpl->setProduct_title(implode(", ", $products));
                 call_user_func($sendCallback, $mailTpl, $invoice);
                 $this->_pendingSent[$sendCallback[1]][$invoice->getUser()->pk()] = true;
                 break;
             }
         }
     }
 }
 public function refundAction()
 {
     $this->getDi()->authAdmin->getUser()->checkPermission('grid_payment', 'insert');
     do {
         $this->invoice_payment_id = $this->getInt('invoice_payment_id');
         if (!$this->invoice_payment_id) {
             $res = array('success' => false, 'text' => ___("Not payment# submitted"));
             continue;
         }
         $p = $this->getDi()->invoicePaymentTable->load($this->invoice_payment_id);
         /* @var $p InvoicePayment */
         if (!$p) {
             $res = array('success' => false, 'text' => ___("No payment found"));
             continue;
         }
         if ($this->user_id != $p->user_id) {
             $res = array('success' => false, 'text' => ___("Payment belongs to another customer"));
             continue;
         }
         if ($p->isFullRefunded()) {
             $res = array('success' => false, 'text' => ___("Payment is already refunded"));
             continue;
         }
         $amount = sprintf('%.2f', $this->_request->get('amount'));
         if ($p->amount < $amount) {
             $res = array('success' => false, 'text' => ___("Refund amount cannot exceed payment amount"));
             continue;
         }
         if ($this->_request->getInt('manual')) {
             $el = new Am_Form_Element_Date();
             $dattm = $el->convertReadableToSQL($this->_request->get('dattm'));
             if (!$dattm) {
                 $dattm = sqlDate('now');
             }
             $dattm .= ' 00:00:00';
             if ($dattm < $p->dattm) {
                 $res = array('success' => false, 'text' => ___("Refund date cannot be before payment date"));
                 continue;
             }
             switch ($type = $this->_request->getFiltered('type')) {
                 case 'refund':
                 case 'chargeback':
                     $pl = $this->getDi()->plugins_payment->loadEnabled()->get($p->paysys_id);
                     if (!$pl) {
                         $res = array('success' => false, 'text' => ___("Could not load payment plugin [%s]", $pl));
                         continue 2;
                     }
                     $invoice = $p->getInvoice();
                     $transaction = new Am_Paysystem_Transaction_Manual($pl);
                     $transaction->setAmount($amount);
                     $transaction->setReceiptId($p->receipt_id . '-manual-' . $type);
                     $transaction->setTime(new DateTime($dattm));
                     if ($type == 'refund') {
                         $invoice->addRefund($transaction, $p->receipt_id);
                     } else {
                         $invoice->addChargeback($transaction, $p->receipt_id);
                     }
                     break;
                 case 'correction':
                     $this->getDi()->accessTable->deleteBy(array('invoice_payment_id' => $this->invoice_payment_id));
                     $invoice = $p->getInvoice();
                     $p->delete();
                     $invoice->updateStatus();
                     break;
                 default:
                     $res = array('success' => false, 'text' => ___("Incorrect refund [type] passed: %s", $type));
                     continue 2;
             }
             $res = array('success' => true, 'text' => ___("Payment has been successfully refunded"));
         } else {
             // automatic
             /// ok, now we have validated $p here
             $pl = $this->getDi()->plugins_payment->loadEnabled()->get($p->paysys_id);
             if (!$pl) {
                 $res = array('success' => false, 'text' => ___("Could not load payment plugin [%s]", $pl));
                 continue;
             }
             /* @var $pl Am_Paysystem_Abstract */
             $result = new Am_Paysystem_Result();
             $pl->processRefund($p, $result, $amount);
             if ($result->isSuccess()) {
                 if ($transaction = $result->getTransaction()) {
                     $p->getInvoice()->addRefund($result->getTransaction(), $p->receipt_id, $amount);
                 }
                 $res = array('success' => true, 'text' => ___("Payment has been successfully refunded"));
             } elseif ($result->isAction()) {
                 $action = $result->getAction();
                 if ($action instanceof Am_Paysystem_Action_Redirect) {
                     $res = array('success' => 'redirect', 'url' => $result->getUrl());
                 } else {
                     // todo handle other actions if necessary
                     throw new Am_Exception_NotImplemented("Could not handle refund action " . get_class($action));
                 }
             } elseif ($result->isFailure()) {
                 $res = array('success' => false, 'text' => join(";", $result->getErrorMessages()));
             }
         }
     } while (false);
     $this->_response->setHeader("Content-Type", "application/json", true);
     echo $this->getJson($res);
 }
Beispiel #22
0
 public function getLabel($key)
 {
     return sqlDate($key);
 }
Beispiel #23
0
 /**
  * run payouts when scheduled
  */
 function onDaily(Am_Event $event)
 {
     $delay = $this->getConfig('payout_day');
     if (!$delay) {
         return;
     }
     list($count, $unit) = preg_split('/(\\D)/', $delay, 2, PREG_SPLIT_DELIM_CAPTURE);
     switch ($unit) {
         case 'd':
             if ($count != (int) date('d', amstrtotime($event->getDatetime()))) {
                 return;
             }
             break;
         case 'w':
             $w = date('w', amstrtotime($event->getDatetime()));
             if ($count != $w) {
                 return;
             }
             break;
         default:
             throw new Am_Exception_InternalError(sprintf('Unknown unit [%s] in %s::%s', $unit, __CLASS__, __METHOD__));
     }
     $this->getDi()->affCommissionTable->runPayout(sqlDate($event->getDatetime()));
 }
Beispiel #24
0
 /**
  * Refresh totals according to currently selected
  *   items, _coupon, user and so ons
  * Should be called on a fresh invoice only, because
  * it may break reporting later if called on a paid
  * invoice
  * @return Invoice provides fluent interface
  */
 function calculate()
 {
     foreach ($this->getCalculators() as $calc) {
         $calc->calculate($this);
     }
     // now summarize all items to invoice totals
     $priceFields = array('first_subtotal' => null, 'first_discount' => 'first_discount', 'first_tax' => 'first_tax', 'first_shipping' => 'first_shipping', 'first_total' => 'first_total', 'second_subtotal' => null, 'second_discount' => 'second_discount', 'second_tax' => 'second_tax', 'second_shipping' => 'second_shipping', 'second_total' => 'second_total');
     foreach ($priceFields as $k => $kk) {
         $this->{$k} = 0.0;
     }
     foreach ($this->getItems() as $item) {
         $this->first_subtotal += moneyRound($item->first_price * $item->qty);
         $this->second_subtotal += moneyRound($item->second_price * $item->qty);
         foreach ($priceFields as $k => $kk) {
             $this->{$k} += $kk ? $item->{$kk} : 0;
         }
     }
     foreach ($priceFields as $k => $kk) {
         $this->{$k} = moneyRound($this->{$k});
     }
     /// set periods, it has been checked for compatibility in @see add()
     foreach ($this->getItems() as $item) {
         $this->currency = $item->currency;
         if (!@$this->first_period) {
             $this->first_period = $item->first_period;
         }
         if (!@$this->second_period) {
             $this->second_period = $item->second_period;
         }
         $this->rebill_times = max(@$this->rebill_times, $item->rebill_times);
     }
     if ($this->currency == Am_Currency::getDefault()) {
         $this->base_currency_multi = 1.0;
     } else {
         $this->base_currency_multi = $this->getDi()->currencyExchangeTable->getRate($this->currency, sqlDate(!empty($this->tm_added) ? $this->tm_added : $this->getDi()->sqlDateTime));
         if (!$this->base_currency_multi) {
             $this->base_currency_multi = 1;
         }
     }
     $this->getDi()->hook->call(Am_Event::INVOICE_CALCULATE, array('invoice' => $this));
     return $this;
 }
 public function renderLink(CcRebill $obj)
 {
     $linkRun = $linkDetail = '';
     if ($obj->rebill_date <= sqlDate('now')) {
         if ($obj->status_3 < $obj->total) {
             $iconRun = $this->getDi()->view->icon('retry', ___('Run'));
             $back_url = $this->grid->makeUrl();
             $linkRun = "<a href='javascript:;' class='run' id='run-{$obj->rebill_date}' data-back_url='{$back_url}'>{$iconRun}</a>";
         }
         if ($obj->is_log) {
             $iconDetail = $this->getDi()->view->icon('view', ___('Details'));
             $linkDetail = "<a href='javascript:;' class='detail' id='detail-{$obj->rebill_date}'>{$iconDetail}</a>";
         }
     }
     return "<td width='1%' nowrap>{$linkRun} {$linkDetail}</td>";
 }
Beispiel #26
0
 function log(Am_Record $user, Am_Record $notification)
 {
     $this->_db->query("INSERT INTO ?_notification_click SET ?a", array('user_id' => $user->pk(), 'dattm' => sqlDate('now'), 'notification_id' => $notification->pk()));
 }
Beispiel #27
0
 public function beforeSave()
 {
     if ($this->isNewRecord) {
         $this->user_id = uid();
         $this->createDate = sqlDate();
         $this->code = $this->getRandomString();
         $user = User::model()->findByPk(uid());
         if ($user->pay != 0 && time() - 30 * 24 * 60 * 60 <= strtotime($user->createdAt)) {
             $pay = intval($user->pay);
             if ($pay === 1) {
                 $this->payModel = 'small';
             } else {
                 if ($pay === 2) {
                     $this->payModel = 'medium';
                 } else {
                     if ($pay === 3) {
                         $this->payModel = 'large';
                     }
                 }
             }
         }
     }
     if ($this->tz) {
         $this->startTime = absDate($this->startTime, $this->tz, "H:i");
         $this->endTime = absDate($this->endTime, $this->tz, "H:i");
     }
     $this->updateDate = sqlDate();
     return parent::beforeSave();
 }
 /**
  * Process invoice and insert necessary commissions for it
  *
  * External code should guarantee that this method with $payment = null will be called
  * only once for each user for First user invoice
  */
 public function processPayment(Invoice $invoice, InvoicePayment $payment = null)
 {
     $aff_id = $invoice->aff_id;
     /* @var $coupon Coupon */
     try {
         if (!$aff_id && ($coupon = $invoice->getCoupon())) {
             // try to find affiliate by coupon
             $aff_id = $coupon->aff_id ? $coupon->aff_id : $coupon->getBatch()->aff_id;
         }
     } catch (Am_Exception_Db_NotFound $e) {
         //coupon not found
     }
     if (empty($aff_id)) {
         $aff_id = $invoice->getUser()->aff_id;
     }
     if ($aff_id && empty($invoice->aff_id)) {
         // set aff_id to invoice for quick access next time
         $invoice->updateQuick('aff_id', $aff_id);
     }
     // run event to get plugins chance choose another affiliate
     $event = new Am_Event(Bootstrap_Aff::AFF_FIND_AFFILIATE, array('invoice' => $invoice, 'payment' => $payment));
     $event->setReturn($aff_id);
     $this->getDi()->hook->call($event);
     $aff_id = $event->getReturn();
     if (empty($aff_id)) {
         return;
     }
     // no affiliate id registered
     if ($aff_id == $invoice->getUser()->pk()) {
         return;
     }
     //strange situation
     // load affiliate and continue
     $aff = $this->getDi()->userTable->load($aff_id, false);
     if (!$aff || !$aff->is_affiliate) {
         return;
     }
     // affiliate not found
     $user = $invoice->getUser();
     if (!$user->aff_id) {
         $user->aff_id = $aff->pk();
         $user->aff_added = sqlTime('now');
         $user->data()->set('aff-source', 'invoice-' . $invoice->pk());
         $user->save();
     }
     // try to load other tier affiliate
     $aff_tier = $aff;
     $aff_tiers = array();
     $aff_tiers_exists = array($aff->pk());
     for ($tier = 1; $tier <= $this->getMaxTier(); $tier++) {
         if (!$aff_tier->aff_id || $aff_tier->pk() == $invoice->getUser()->pk()) {
             break;
         }
         $aff_tier = $this->getDi()->userTable->load($aff_tier->aff_id, false);
         if (!$aff_tier || !$aff_tier->is_affiliate || $aff_tier->pk() == $invoice->getUser()->pk() || in_array($aff_tier->pk(), $aff_tiers_exists)) {
             //already in chain
             break;
         }
         $aff_tiers[$tier] = $aff_tier;
         $aff_tiers_exists[] = $aff_tier->pk();
     }
     $isFirst = !$payment || $payment->isFirst();
     //to define price field
     $paymentNumber = is_null($payment) ? 0 : $invoice->getPaymentsCount();
     if (!$payment) {
         $tax = 0;
     } else {
         $tax = $this->getDi()->config->get('aff.commission_include_tax', false) ? 0 : doubleval($payment->tax);
     }
     $amount = $payment ? $payment->amount - $tax : 0;
     $date = $payment ? $payment->dattm : 'now';
     // now calculate commissions
     $items = is_null($payment) ? array_slice($invoice->getItems(), 0, 1) : $invoice->getItems();
     foreach ($items as $item) {
         //we do not calculate commission for free items in invoice
         $prefix = $isFirst ? 'first' : 'second';
         if (!is_null($payment) && !(double) $item->get("{$prefix}_total")) {
             continue;
         }
         $comm = $this->getDi()->affCommissionRecord;
         $comm->date = sqlDate($date);
         $comm->record_type = AffCommission::COMMISSION;
         $comm->invoice_id = $invoice->invoice_id;
         $comm->invoice_item_id = $item->invoice_item_id;
         $comm->invoice_payment_id = $payment ? $payment->pk() : null;
         $comm->receipt_id = $payment ? $payment->receipt_id : null;
         $comm->product_id = $item->item_id;
         $comm->is_first = $paymentNumber <= 1;
         $comm->_setPayment($payment);
         $comm->_setInvoice($invoice);
         $comm_tier = clone $comm;
         $rules = array();
         $topay_this = $topay = $this->calculate($invoice, $item, $aff, $paymentNumber, 0, $amount, $date, $rules);
         if ($topay > 0) {
             $comm->aff_id = $aff->pk();
             $comm->amount = $topay;
             $comm->tier = 0;
             $comm->_setAff($aff);
             $comm->insert();
             $comm->setCommissionRules(array_map(create_function('$el', 'return $el->pk();'), $rules));
         }
         foreach ($aff_tiers as $tier => $aff_tier) {
             $rules = array();
             $topay_this = $this->calculate($invoice, $item, $aff_tier, $paymentNumber, $tier, $topay_this, $date, $rules);
             if ($topay_this > 0) {
                 $comm_this = clone $comm_tier;
                 $comm_this->aff_id = $aff_tier->pk();
                 $comm_this->amount = $topay_this;
                 $comm_this->tier = $tier;
                 $comm_this->_setAff($aff_tier);
                 $comm_this->insert();
                 $comm_this->setCommissionRules(array_map(create_function('$el', 'return $el->pk();'), $rules));
             }
         }
     }
 }
Beispiel #29
0
 /** @return array of int future product# */
 function getFutureProductIds()
 {
     return $this->getAdapter()->selectCol("SELECT DISTINCT product_id\n            FROM ?_access a\n            LEFT JOIN ?_user_status us\n            USING(user_id,product_id)\n            WHERE a.user_id = ?\n            AND a.begin_date>?\n            AND (us.status IS NULL OR us.status<>?)", $this->user_id, sqlDate('now'), self::STATUS_ACTIVE);
 }
Beispiel #30
0
 function getStats($start, $stop)
 {
     return (double) $this->_db->selectCell("SELECT SUM(amount) FROM ?_aff_commission\n            WHERE record_type=? AND date BETWEEN ? AND ?", AffCommission::COMMISSION, sqlDate($start), sqlDate($stop));
 }