示例#1
0
 public function __construct($name = null, $attributes = null, $data = null)
 {
     parent::__construct($name, $attributes, null);
     $this->addElement('text', $data . '_c', array('size' => 5));
     $this->addStatic()->setContent(' ');
     $sel = $this->addElement('select', $data . '_t', array('size' => 1), array('options' => array('%' => '%', '$' => Am_Currency::getDefault())));
 }
示例#2
0
 public function init()
 {
     parent::init();
     if (empty($this->currency)) {
         $this->currency = Am_Currency::getDefault();
     }
 }
    function init()
    {
        $this->addDataSource(new HTML_QuickForm2_DataSource_Array(array('_count' => 1, 'use_count' => 10, 'discount' => 10, 'discount_type' => '%', 'user_use_count' => 1, '_code_len' => 8)));
        if (!$this->record->isLoaded()) {
            $this->addElement('text', '_count', array('size' => 20))->setLabel(___("Coupons Count\nhow many coupons need to be generated"))->addRule('gt', 'Should be greater than 0', 0);
        }
        $this->addElement('text', 'use_count', array('size' => 20))->setLabel(___("Coupons Usage Count\n" . "how many times coupon can be used"));
        $discountGroup = $this->addElement('group')->setLabel(array('Discount'));
        $discountGroup->addElement('text', 'discount', array('size' => 5))->addRule('gt', 'must be greater than 0', 0);
        $discountGroup->addElement('select', 'discount_type')->loadOptions(array(Coupon::DISCOUNT_PERCENT => '%', Coupon::DISCOUNT_NUMBER => Am_Currency::getDefault()));
        $this->addElement('textarea', 'comment')->setLabel(___("Comment\nfor admin reference"));
        /// advanced settings
        $fs = $this->addAdvFieldset('advanced')->setLabel(___('Advanced Settings'));
        if (!$this->record->isLoaded()) {
            $fs->addElement('text', '_code_len', array('size' => 20))->setLabel(array(___("Code Length\ngenerated coupon code length\nbetween 5 and 32")))->addRule('gt', 'Should be greater than 4', 4)->addRule('lt', 'Should be less then 33', 33);
        }
        $fs->addElement('text', 'user_use_count', array('size' => 20))->setLabel(___("User Coupon Usage Count\nhow many times a coupon code can be used by customer"));
        $dateGroup = $fs->addElement('group')->setLabel(___("Dates\ndate range when coupon can be used"));
        $dateGroup->addCheckbox('_date-enable', array('class' => 'enable_date'));
        $begin = $dateGroup->addDate('begin_date');
        $expire = $dateGroup->addDate('expire_date');
        $fs->addElement('advcheckbox', 'is_recurring')->setLabel(___("Apply to recurring?\n" . "apply coupon discount to recurring rebills?"));
        $fs->addElement('advcheckbox', 'is_disabled')->setLabel(___("Is Disabled?\n" . "If you disable this coupons batch, it will\n" . "not be available for new purchases.\n" . "Existing invoices are not affected.\n"));
        $fs->addElement('select', 'product_ids', array('multiple' => 1, 'class' => 'magicselect'))->loadOptions(Am_Di::getInstance()->productTable->getOptions())->setLabel(___("Products\n" . "coupons can be used with selected products only.\n" . "if nothing selected, coupon can be used with any product"));
        $jsCode = <<<CUT
\$(".enable_date").prop("checked", \$("input[name=expire_date]").val() ? "checked" : "");   
\$(".enable_date").live("change", function(){
    var dates = \$(this).parent().find("input[type=text]");
    dates.prop('disabled', \$(this).prop("checked") ? '' : 'disabled');
}).trigger("change");
CUT;
        $fs->addScript('script')->setScript($jsCode);
    }
 public function createForm()
 {
     $form = new Am_Form_Admin();
     $options = Am_Currency::getSupportedCurrencies();
     array_remove_value($options, Am_Currency::getDefault());
     $sel = $form->addSelect('currency', array('class' => 'am-combobox'))->setLabel(___('Currency'))->loadOptions($options)->addRule('required');
     $date = $form->addDate('date')->setLabel(___('Date'))->addRule('required')->addRule('callback2', "--wrong date--", array($this, 'checkDate'));
     $rate = $form->addText('rate', array('length' => 8))->setLabel(___("Exchange Rate\nenter cost of 1 (one) %s", Am_Currency::getDefault()))->addRule('required');
     return $form;
 }
 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;
 }
示例#7
0
文件: Abstract.php 项目: grlf/eyedock
 /**
  * @return array of 3-letter ISO currency codes supported by this payment system like array('USD', 'EUR');
  */
 function getSupportedCurrencies()
 {
     return array(Am_Currency::getDefault());
 }
 function renderConditions()
 {
     $ret = array();
     foreach ($this->getConditions() as $conditionType => $vars) {
         switch ($conditionType) {
             case self::COND_AFF_SALES_COUNT:
                 $ret[] = sprintf("affiliate generated %d sales last %d days", $vars['count'], $vars['days']);
             case self::COND_AFF_SALES_AMOUNT:
                 $ret[] = sprintf("affiliate generated %d%s in commissions last %d days", $vars['count'], Am_Currency::getDefault(), $vars['days']);
                 break;
             case self::COND_AFF_GROUP_ID:
                 $v = array();
                 foreach ($this->getDi()->userGroupTable->loadIds((array) $vars) as $group) {
                     $v[] = $group->title;
                 }
                 $ret[] = sprintf("affiliate group IN (%s)", implode(", ", $v));
                 break;
             case self::COND_PRODUCT_ID:
                 $v = array();
                 foreach ($this->getDi()->productTable->loadIds((array) $vars) as $product) {
                     $v[] = $product->title;
                 }
                 $ret[] = sprintf("products IN (%s)", implode(", ", $v));
                 break;
             case self::COND_PRODUCT_CATEGORY_ID:
                 $v = array();
                 foreach ($this->getDi()->productCategoryTable->loadIds((array) $vars) as $product) {
                     $v[] = $product->title;
                 }
                 $ret[] = sprintf("product category IN (%s)", implode(", ", $v));
                 break;
             default:
                 return false;
         }
     }
     return implode(" AND ", $ret);
 }
示例#9
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;
 }
 function doWork()
 {
     foreach ($this->groups as $list) {
         $byDate = array();
         $totals = array();
         // totals by date
         $coupon = null;
         $cancelled = null;
         $invoice = null;
         foreach ($list as $p) {
             $d = date('Y-m-d', strtotime($p['tm_added']));
             $byDate[$d][] = $p;
             @($totals[$d] += $p['amount']);
             if (!empty($p['data'][0]['coupon'])) {
                 $coupon = $p['data'][0]['coupon'];
             }
             if (!empty($p['data']['CANCELLED_AT'])) {
                 $cancelled = date('Y-m-d H:i:s', strtotime($p['data']['CANCELLED_AT']));
             } elseif (@$p['data']['CANCELLED']) {
                 $cancelled = date('Y-m-d H:i:s', time());
             }
         }
         if (count($list) == 1 && !$list[0]['data']['beanstream_rbaccountid'] && ($rbAccountId = $this->findRbAccountId($list[0]))) {
             $invoice = $this->getDi()->invoiceTable->findFirstByData('rb-account-id', $rbAccountId);
         }
         if (!$invoice) {
             $invoice = $this->getDi()->invoiceRecord;
             $invoice->user_id = $this->user->pk();
             $pidItems = array();
             foreach ($list as $p) {
                 $pid = $p['product_id'];
                 if (@$pidItems[$pid]) {
                     continue;
                 }
                 $pidItems[$pid] = 1;
                 $newP = $this->_translateProduct($pid);
                 if ($newP) {
                     $pr = Am_Di::getInstance()->productTable->load($newP);
                     $item = $invoice->createItem($pr);
                     if (empty($invoice->first_period)) {
                         $invoice->first_period = $pr->getBillingPlan()->first_period;
                     }
                 } else {
                     $item = $invoice->createItem(new ImportedProduct($pid));
                     $invoice->first_period = '1d';
                 }
                 $item->add(1);
                 $item->_calculateTotal();
                 $invoice->addItem($item);
             }
             if (!is_null($coupon)) {
                 $invoice->setCouponCode($coupon);
                 $invoice->validateCoupon();
             }
             $invoice->currency = $item->currency ? $item->currency : Am_Currency::getDefault();
             $invoice->calculate();
             $invoice->paysys_id = $this->paysys_id;
             $invoice->tm_added = $list[0]['tm_added'];
             $invoice->tm_started = $list[0]['tm_completed'];
             $invoice->public_id = $list[0]['payment_id'];
             $invoice->first_total = current($totals);
             if ($invoice->rebill_times) {
                 // Recurring
                 if ($cancelled) {
                     $invoice->tm_cancelled = $cancelled;
                     $invoice->status = Invoice::RECURRING_CANCELLED;
                 } else {
                     $invoice->status = Invoice::RECURRING_ACTIVE;
                 }
             } else {
                 $invoice->status = Invoice::PAID;
             }
             foreach ($list as $p) {
                 $pidlist[] = $p['payment_id'];
             }
             $invoice->data()->set('am3:id', implode(',', $pidlist));
             if (empty($invoice->currency)) {
                 $invoice->currency = Am_Currency::getDefault();
             }
             //REQUIRED PART TO IMPORT RECURRING SUBCRIPTIONS
             if (@$p['data']['beanstream_rbaccountid']) {
                 $invoice->data()->set('rb-account-id', $p['data']['beanstream_rbaccountid']);
             }
             $invoice->insert();
         }
         // insert payments and access
         foreach ($list as $p) {
             $newP = $this->_translateProduct($p['product_id']);
             if (empty($p['data']['ORIG_ID'])) {
                 $payment = $this->getDi()->invoicePaymentRecord;
                 $payment->user_id = $this->user->user_id;
                 $payment->currency = $invoice->currency;
                 $payment->invoice_id = $invoice->pk();
                 $payment->invoice_public_id = $invoice->public_id;
                 if (count($list) == 1) {
                     $payment->amount = $p['amount'];
                 } elseif ($p['data']['BASKET_PRICES']) {
                     $payment->amount = array_sum($p['data']['BASKET_PRICES']);
                 } else {
                     $payment->amount = 0;
                     foreach ($list as $pp) {
                         if (@$p['data']['ORIG_ID'] == $p['payment_id']) {
                             $payment->amount += $pp['amount'];
                         }
                     }
                 }
                 $payment->paysys_id = $this->paysys_id;
                 $payment->dattm = $p['tm_completed'];
                 $payment->receipt_id = $p['receipt_id'];
                 $payment->transaction_id = $p['receipt_id'] . '-import-' . mt_rand(10000, 99999) . '-' . intval($p['payment_id']);
                 $payment->insert();
                 $this->getDi()->db->query("INSERT INTO ?_data SET\n                        `table`='invoice_payment',`id`=?d,`key`='am3:id',`value`=?", $payment->pk(), $p['payment_id']);
             }
             if ($newP) {
                 $a = $this->getDi()->accessRecord;
                 $a->setDisableHooks();
                 $a->user_id = $this->user->user_id;
                 $a->begin_date = $p['begin_date'];
                 $a->expire_date = $p['expire_date'];
                 $a->invoice_id = $invoice->pk();
                 $a->invoice_payment_id = $payment->pk();
                 $a->product_id = $newP;
                 $a->insert();
             }
         }
     }
 }
    function init()
    {
        $this->setAttribute('enctype', 'multipart/form-data');
        $this->addDataSource(new HTML_QuickForm2_DataSource_Array(array('_count' => 1, 'use_count' => 10, 'discount' => 10, 'discount_type' => '%', 'user_use_count' => 1, '_code_len' => 8, '_source' => 1)));
        $this->addText('use_count', array('size' => 5))->setLabel(___("Coupons Usage Count\n" . 'how many times coupon can be used'));
        $discountGroup = $this->addGroup()->setLabel(___('Discount'));
        $discountGroup->setSeparator(' ');
        $discountGroup->addText('discount', array('size' => 5));
        $discountGroup->addSelect('discount_type')->loadOptions(array(Coupon::DISCOUNT_PERCENT => '%', Coupon::DISCOUNT_NUMBER => Am_Currency::getDefault()));
        $this->addTextarea('comment', array('class' => 'el-wide'))->setLabel(___("Comment\nfor admin reference"));
        if (!$this->record->isLoaded()) {
            $source = $this->addFieldset('source')->setLabel(___('Coupon Codes'));
            $source->addAdvRadio('_source')->setId('coupon-source')->loadOptions(array(AdminCouponsController::SOURCE_GENERATE => ___('Generate Random Coupon Codes (You will be able to alter codes later if you want)'), AdminCouponsController::SOURCE_FILE => ___('Import Pre-Defined List of Coupon Codes from CSV File (One coupon code per line)')));
            $source->addText('_count', array('size' => 5, 'rel' => 'source-generate'))->setLabel(___("Coupons Count\nhow many coupons need to be generated"))->addRule('gt', ___('Should be greater than 0'), 0);
            $source->addText('_code_len', array('size' => 5, 'rel' => 'source-generate'))->setLabel(___("Code Length\ngenerated coupon code length\nbetween 5 and 32"))->addRule('gt', ___('Should be greater than %d', 4), 4)->addRule('lt', ___('Should be less then %d', 33), 33);
            $source->addFile('file[]', array('class' => 'styled', 'rel' => 'source-file'))->setLabel(___('File'));
            $s_generate = AdminCouponsController::SOURCE_GENERATE;
            $s_file = AdminCouponsController::SOURCE_FILE;
            $this->addScript()->setScript(<<<CUT
\$('[name=_source]').change(function(){
    \$('[rel=source-generate]').closest('.row').toggle(\$('[name=_source]:checked').val() == {$s_generate});
    \$('[rel=source-file]').closest('.row').toggle(\$('[name=_source]:checked').val() == {$s_file});
}).change();
CUT
);
        }
        $fs = $this->addAdvFieldset(null, array('id' => 'coupon-batch'))->setLabel(___('Advanced Settings'));
        $fs->addText('user_use_count', array('size' => 20))->setLabel(___("User Coupon Usage Count\nhow many times a coupon code can be used by customer"));
        $dateGroup = $fs->addGroup()->setLabel(___("Dates\ndate range when coupon can be used"));
        $dateGroup->setSeparator(' ');
        $dateGroup->addCheckbox('_date-enable', array('class' => 'enable_date'));
        $begin = $dateGroup->addDate('begin_date');
        $expire = $dateGroup->addDate('expire_date');
        $fs->addAdvCheckbox('is_recurring')->setLabel(___("Apply to recurring?\n" . "apply coupon discount to recurring rebills?"));
        $fs->addAdvCheckbox('is_disabled')->setLabel(___("Is Disabled?\n" . "If you disable this coupons batch, it will\n" . "not be available for new purchases.\n" . "Existing invoices are not affected.\n"));
        $product_categories = array();
        foreach (Am_Di::getInstance()->productCategoryTable->getAdminSelectOptions() as $id => $title) {
            $product_categories['CATEGORY-' . $id] = $title;
        }
        $fs->addMagicSelect('product_ids')->loadOptions(array(___('Products') => Am_Di::getInstance()->productTable->getOptions(), ___('Product Categories') => $product_categories))->setLabel(___("Products\n" . "coupons can be used with selected products only.\n" . "if nothing selected, coupon can be used with any product"));
        $jsCode = <<<CUT
\$(".enable_date").prop("checked", \$("input[name=expire_date]").val() ? "checked" : "");
\$(document).on("change",".enable_date", function(){
    var dates = \$(this).parent().find("input[type=text]");
    dates.prop('disabled', \$(this).prop("checked") ? '' : 'disabled');
})
\$(".enable_date").change();
CUT;
        $fs->addScript('script')->setScript($jsCode);
        $require_options = $prevent_options = array();
        foreach (Am_Di::getInstance()->productTable->getOptions() as $id => $title) {
            $title = Am_Controller::escape($title);
            $require_options['ACTIVE-' . $id] = ___('ACTIVE subscription for %s', '"' . $title . '"');
            $require_options['EXPIRED-' . $id] = ___('EXPIRED subscription for %s', '"' . $title . '"');
            $prevent_options['ACTIVE-' . $id] = ___('ACTIVE subscription for %s', '"' . $title . '"');
            $prevent_options['EXPIRED-' . $id] = ___('EXPIRED subscription for %s', '"' . $title . '"');
        }
        $require_group_options = $prevent_group_options = array();
        foreach (Am_Di::getInstance()->productCategoryTable->getAdminSelectOptions() as $id => $title) {
            $title = Am_Controller::escape($title);
            $require_group_options['CATEGORY-ACTIVE-' . $id] = ___('ACTIVE subscription for group %s', '"' . $title . '"');
            $require_group_options['CATEGORY-EXPIRED-' . $id] = ___('EXPIRED subscription for group %s', '"' . $title . '"');
            $prevent_group_options['CATEGORY-ACTIVE-' . $id] = ___('ACTIVE subscription for group %s', '"' . $title . '"');
            $prevent_group_options['CATEGORY-EXPIRED-' . $id] = ___('EXPIRED subscription for group %s', '"' . $title . '"');
        }
        if (count($require_group_options)) {
            $rOptions = array(___('Products') => $require_options, ___('Product Categories') => $require_group_options);
            $pOptions = array(___('Products') => $prevent_options, ___('Product Categories') => $prevent_group_options);
        } else {
            $rOptions = $require_options;
            $pOptions = $prevent_options;
        }
        $fs->addMagicSelect('require_product', array('multiple' => 'multiple', 'class' => 'magicselect'))->setLabel(___("To use coupon from this batch user must have an\n" . "when user uses coupon, it will be checked\n" . "that user has one from the following subscriptions"))->loadOptions($rOptions);
        $fs->addMagicSelect('prevent_if_product', array('multiple' => 'multiple', 'class' => 'magicselect'))->setLabel(___("Disallow use of coupon from this batch if user has\n" . "when user uses coupon, it will be checked\n" . "that he has no any from the following subscriptions"))->loadOptions($pOptions);
    }
 function doWork()
 {
     foreach ($this->payments as $p) {
         if (!($amPrId = $this->_translateProduct($p['ps_item_id']))) {
             if ($bp = $this->getDi()->billingPlanTable->findFirstByFirstPrice($p['i_total'])) {
                 $amPrId = $bp->product_id;
             } else {
                 if ($p['i_total'] == 3.0) {
                     $amPrId = $this->_translateProduct(3);
                 } else {
                     $this->getDi()->errorLogTable->log("Not found product #{$p['ps_item_id']} for user #[{$p['i_member']}]");
                     continue;
                 }
             }
         }
         // ivoice + item
         $invoice = $this->getDi()->invoiceRecord;
         $invoice->user_id = $this->user->pk();
         $item = $invoice->createItem(Am_Di::getInstance()->productTable->load($amPrId));
         $item->qty = 1;
         $item->first_discount = 0;
         $item->first_shipping = 0;
         $item->first_tax = 0;
         $item->second_discount = 0;
         $item->second_shipping = 0;
         $item->second_tax = 0;
         $item->_calculateTotal();
         $invoice->addItem($item);
         $invoice->paysys_id = 'ccbill';
         $invoice->tm_added = date('Y-m-d H:i:s', $p['i_date']);
         $invoice->tm_started = date('Y-m-d H:i:s', $p['i_paid']);
         $invoice->currency = Am_Currency::getDefault();
         $invoice->calculate();
         $invoice->status = Invoice::PAID;
         $invoice->data()->set('ibp_nexus:id', $p['i_id']);
         $invoice->insert();
         // insert payments
         $payment = $this->getDi()->invoicePaymentRecord;
         $payment->user_id = $this->user->user_id;
         $payment->invoice_id = $invoice->pk();
         $payment->currency = $invoice->currency;
         $payment->amount = $p['i_total'];
         $payment->paysys_id = $invoice->paysys_id;
         $payment->dattm = $invoice->tm_started;
         $payment->receipt_id = $payment->transaction_id = 'import-ipb-nexus-' . mt_rand(10000, 99999);
         $payment->data()->set('ibp_nexus:id', $p['ps_id']);
         $payment->insert();
         //insert access
         $a = $this->getDi()->accessRecord;
         $a->invoice_id = $invoice->pk();
         $a->invoice_payment_id = $payment->pk();
         $a->user_id = $this->user->user_id;
         $a->product_id = $amPrId;
         $a->transaction_id = $payment->transaction_id;
         $a->begin_date = date('Y-m-d', $p['ps_start']);
         $a->expire_date = $p['ps_expire'] ? date('Y-m-d', $p['ps_expire']) : Am_Period::MAX_SQL_DATE;
         $a->invoice_item_id = $invoice->getItem(0)->pk();
         $a->invoice_public_id = $invoice->public_id;
         $a->setDisableHooks();
         $a->insert();
     }
     $this->user->checkSubscriptions();
 }
示例#13
0
 public function export(AffPayout $payout, Am_Query $details, Zend_Controller_Response_Http $response)
 {
     $q = $details->query();
     while ($d = $payout->getDi()->db->fetchRow($q)) {
         $d = $payout->getDi()->affPayoutDetailTable->createRecord($d);
         /* @var $d AffPayoutDetail */
         $aff = $d->getAff();
         $rows[] = array($aff->data()->get('aff_bitcoin_wallet'), moneyRound($d->amount), Am_Currency::getDefault(), $aff->user_id, "Affiliate commission to " . amDate($payout->thresehold_date));
     }
     $this->sendCsv("bitcoint-commission-" . $payout->payout_id . ".txt", $rows, $response);
 }
 public function getForm()
 {
     if (!$this->form) {
         $id = $this->grid->getId();
         $this->form = new Am_Form_Admin();
         $sel = $this->form->addSelect($id . '_product_id')->setLabel(___('Product'));
         $sel->loadOptions(Am_Di::getInstance()->productTable->getOptions(false));
         $sel->addRule('required');
         $dates = $this->form->addGroup()->setLabel(___('Start and Expiration Dates'));
         $dates->addRule('required');
         $dates->addDate($id . '_start_date')->addRule('required');
         $dates->addDate($id . '_expire_date')->addRule('required');
         $pg = $this->form->addCheckboxedGroup($id . '_add_payment')->setLabel(___('Additionally to "Access", add "Invoice" and "Payment" record with given %s amount, like they have really made a payment', Am_Currency::getDefault()));
         $pg->addStatic()->setContent('Payment Record amount, ex.: 19.99');
         $pg->addText($id . '_amount')->addRule('regex', 'must be a number', '/^(\\d+)(\\.\\d+)?$/');
         $this->form->addSaveButton(___('Mass Subscribe'));
     }
     return $this->form;
 }
示例#15
0
 function getLines()
 {
     return array(new Am_Report_Line("amt", ___('Income') . ', ' . Am_Currency::getDefault(), null, array('Am_Currency', 'render')), new Am_Report_Line("pmt", ___('Payment') . ', ' . Am_Currency::getDefault(), '#488f37', array('Am_Currency', 'render')), new Am_Report_Line("rfd", ___('Refund') . ', ' . Am_Currency::getDefault(), '#BA2727', array('Am_Currency', 'render')));
 }
示例#16
0
 function getLines()
 {
     return array(new Am_Report_Line("amt", "Payments Amount, " . Am_Currency::getDefault(), "#ff00cc"));
 }
 protected function addSub(Am_Record $user, $lineParsed)
 {
     $user_id = $user->pk();
     $product = $this->getDi()->productTable->load($this->getImportField('product_id', self::FIELD_TYPE_SUBSCRIPTION)->getValue($lineParsed), false);
     if (!$product) {
         return;
     }
     $invoice = $this->getDi()->invoiceRecord;
     $invoice->user_id = $user_id;
     $invoice->paysys_id = $this->getImportField('paysys_id', self::FIELD_TYPE_SUBSCRIPTION)->getValue($lineParsed);
     $invoice->currency = Am_Currency::getDefault();
     $invoice->status = Invoice::PAID;
     $invoice->add($product);
     $items = $invoice->getItems();
     $items[0]->first_total = $this->getImportField('amount', self::FIELD_TYPE_SUBSCRIPTION)->getValue($lineParsed);
     $invoice->calculate();
     $invoice->insert();
     if ($external_id = $this->getImportField('invoice_external_id', self::FIELD_TYPE_SUBSCRIPTION)->getValue($lineParsed)) {
         $invoice->data()->set('external_id', $external_id)->update();
     }
     $payment = null;
     if ($amount = $this->getImportField('amount', self::FIELD_TYPE_SUBSCRIPTION)->getValue($lineParsed)) {
         $payment = $this->getDi()->invoicePaymentRecord;
         $payment->amount = $amount;
         $payment->user_id = $user_id;
         $payment->paysys_id = $this->getImportField('paysys_id', self::FIELD_TYPE_SUBSCRIPTION)->getValue($lineParsed);
         $payment->invoice_id = $invoice->pk();
         $payment->receipt_id = $this->getImportField('receipt_id', self::FIELD_TYPE_SUBSCRIPTION)->getValue($lineParsed);
         $payment->transaction_id = $this->getID();
         $payment->currency = $invoice->currency;
         $payment->dattm = $this->getImportField('begin_date', self::FIELD_TYPE_SUBSCRIPTION)->getValue($lineParsed);
         if (empty($payment->dattm)) {
             $payment->dattm = $this->getDi()->sqlDateTime;
             // fallback to import time
         }
         $payment->save();
     }
     $access = $this->getDi()->accessRecord;
     $access->begin_date = $this->getImportField('begin_date', self::FIELD_TYPE_SUBSCRIPTION)->getValue($lineParsed);
     $access->expire_date = $this->getImportField('expire_date', self::FIELD_TYPE_SUBSCRIPTION)->getValue($lineParsed);
     $access->user_id = $user_id;
     $access->product_id = $product->pk();
     $access->invoice_id = $invoice->pk();
     $access->invoice_payment_id = $payment ? $payment->pk() : null;
     $access->transaction_id = $this->getID();
     $access->save();
 }
示例#18
0
 function renderConditions()
 {
     $ret = array();
     foreach ($this->getConditions() as $conditionType => $vars) {
         switch ($conditionType) {
             case self::COND_AFF_ITEMS_COUNT:
                 $ret[] = ___("affiliate generated %d item sales last %d days", $vars['count'], $vars['days']);
                 break;
             case self::COND_AFF_SALES_COUNT:
                 $ret[] = ___("affiliate generated %d sales last %d days", $vars['count'], $vars['days']);
                 break;
             case self::COND_AFF_SALES_AMOUNT:
                 $ret[] = ___("affiliate generated %d%s in commissions last %d days", $vars['count'], Am_Currency::getDefault(), $vars['days']);
                 break;
             case self::COND_AFF_GROUP_ID:
                 $v = array();
                 foreach ($this->getDi()->userGroupTable->loadIds((array) $vars) as $group) {
                     $v[] = $group->title;
                 }
                 $ret[] = ___("affiliate group IN (%s)", implode(", ", $v));
                 break;
             case self::COND_PRODUCT_ID:
                 $v = array();
                 foreach ($this->getDi()->productTable->loadIds((array) $vars) as $product) {
                     $v[] = $product->title;
                 }
                 $ret[] = ___("products IN (%s)", implode(", ", $v));
                 break;
             case self::COND_PRODUCT_CATEGORY_ID:
                 $v = array();
                 foreach ($this->getDi()->productCategoryTable->loadIds((array) $vars) as $product) {
                     $v[] = $product->title;
                 }
                 $ret[] = ___("product category IN (%s)", implode(", ", $v));
                 break;
             case self::COND_COUPON:
                 $txt = '';
                 switch ($vars['type']) {
                     case 'any':
                         $txt = $vars['used'] ? ___('Used Any Coupon') : ___("Did't Use Any Coupon");
                         break;
                     case 'coupon':
                         $text = $vars['used'] ? ___('Used Coupon with Code: %s', $vars['code']) : ___("Did't Use Coupon with Code: %s", $vars['code']);
                         break;
                     case 'batch':
                         $options = $this->getDi()->couponBatchTable->getOptions(false);
                         $txt = $vars['used'] ? ___('Used Coupon from Batch: %s', $options[$vars['batch_id']]) : ___("Did't Use Coupon from Batch: %s", $options[$vars['batch_id']]);
                         break;
                 }
                 $ret[] = $txt;
                 break;
             case self::COND_PAYSYS_ID:
                 $ret[] = ___("paysystem IN (%s)", implode(', ', (array) $vars));
                 break;
             default:
                 return false;
         }
     }
     return implode(" AND ", $ret);
 }
    public function createConfigForm(Am_Grid_Editable $grid)
    {
        $form = new Am_Form_Admin();
        $record = $grid->getRecord($grid->getCurrentAction());
        if (empty($record->type)) {
            $record->type = null;
        }
        if (empty($record->tier)) {
            $record->tier = 0;
        }
        $globalOptions = AffCommissionRule::getTypes();
        $record->type && !isset($globalOptions[$record->type]) && ($globalOptions[$record->type] = $record->getTypeTitle());
        $cb = $form->addSelect('type')->setLabel('Type')->loadOptions($globalOptions);
        if ($record->isGlobal()) {
            $cb->toggleFrozen(true);
        }
        $form->addScript()->setScript(<<<CUT
\$(function(){
    \$("select#type-0").change(function(){
        var val = \$(this).val();
        \$("fieldset#multiplier").toggle(val == 'multi');
        \$("fieldset#commission").toggle(val != 'multi');
        var checked = val.match(/^global-/);
        \$("#conditions").toggle(!checked);
        \$("#sort_order-0").closest(".row").toggle(!checked);
    }).change();

    \$("#condition-select").change(function(){
        var val = \$(this).val();
        \$(this.options[this.selectedIndex]).prop("disabled", true);
        this.selectedIndex = 0;
        \$('input[name="_conditions_status[' + val + ']"]').val(1);
        \$('#row-'+val).show();
    });

    \$("#conditions .row").not("#row-condition-select").each(function(){
        var val = /row-(.*)/i.exec(this.id).pop();
        if (!\$('input[name="_conditions_status[' + val + ']"]').val()) {
            \$(this).hide();
        } else {
            \$("#condition-select option[value='"+val+"']").prop("disabled", true);
        }
        \$(this).find(".element-title").append("&nbsp;<a href='javascript:' class='hide-row'>X</a>&nbsp;");
    });

    \$(document).on('click',"a.hide-row",function(){
        var row = \$(this).closest(".row");
        var id = row.hide().attr("id");
        var val = /row-(.*)/i.exec(id).pop();
        \$('input[name="_conditions_status[' + val + ']"]').val(0);
        \$("#condition-select option[value='"+val+"']").prop("disabled", false);
    });

    \$('#used-type').change(function(){
        \$('#used-batch_id, #used-code').hide();
        switch (\$(this).val()) {
            case 'batch' :
                \$('#used-batch_id').show();
                break;
            case 'coupon' :
                \$('#used-code').show();
                break;
        }

    }).change()
});
CUT
);
        $comment = $form->addText('comment', array('size' => 40))->setLabel('Rule title - for your own reference');
        if ($record->isGlobal()) {
            $comment->toggleFrozen(true);
        } else {
            $comment->addRule('required', 'This field is required');
        }
        if (!$record->isGlobal()) {
            $form->addInteger('sort_order')->setLabel('Sort order - rules with lesser values executed first');
        }
        if (!$record->isGlobal()) {
            $set = $form->addFieldset('', array('id' => 'conditions'))->setLabel('Conditions');
            $set->addSelect('', array('id' => 'condition-select'))->setLabel('Add Condition')->loadOptions(array('' => ___('Select Condition...'), 'first_time' => ___('First Time Purchase of Product'), 'coupon' => ___('By Used Coupon'), 'paysys_id' => ___('By Used Payment System'), 'product_id' => ___('By Product'), 'product_category_id' => ___('By Product Category'), 'aff_group_id' => ___('By Affiliate Group Id'), 'aff_sales_count' => ___('By Affiliate Sales Count'), 'aff_items_count' => ___('By Affiliate Item Sales Count'), 'aff_sales_amount' => ___('By Affiliate Sales Amount'), 'aff_product_id' => ___('By Affiliate Active Product'), 'aff_product_category_id' => ___('By Affiliate Active Product Category')));
            $set->addHidden('_conditions_status[product_id]');
            $set->addMagicSelect('_conditions[product_id]', array('id' => 'product_id'))->setLabel(___("This rule is for particular products\n" . 'if none specified, rule works for all products'))->loadOptions(Am_Di::getInstance()->productTable->getOptions());
            $set->addHidden('_conditions_status[product_category_id]');
            $el = $set->addMagicSelect('_conditions[product_category_id]', array('id' => 'product_category_id'))->setLabel(___("This rule is for particular product categories\n" . "if none specified, rule works for all product categories"));
            $el->loadOptions(Am_Di::getInstance()->productCategoryTable->getAdminSelectOptions());
            $set->addHidden('_conditions_status[aff_group_id]');
            $el = $set->addMagicSelect('_conditions[aff_group_id]', array('id' => 'aff_group_id'))->setLabel(___("This rule is for particular affiliate groups\n" . "you can add user groups and assign it to customers in User editing form"));
            $el->loadOptions(Am_Di::getInstance()->userGroupTable->getSelectOptions());
            $set->addHidden('_conditions_status[aff_sales_count]');
            $gr = $set->addGroup('_conditions[aff_sales_count]', array('id' => 'aff_sales_count'))->setLabel(___("Affiliate sales count\n" . "trigger this commission if affiliate made more than ... sales within ... days before the current date\n" . "(only count of new invoices is calculated)"));
            $gr->addStatic()->setContent('use only if affiliate referred ');
            $gr->addInteger('count', array('size' => 4));
            $gr->addStatic()->setContent(' invoices within last ');
            $gr->addInteger('days', array('size' => 4));
            $gr->addStatic()->setContent(' days');
            $set->addHidden('_conditions_status[aff_items_count]');
            $gr = $set->addGroup('_conditions[aff_items_count]', array('id' => 'aff_items_count'))->setLabel(___("Affiliate items count\n" . "trigger this commission if affiliate made more than ... item sales within ... days before the current date\n" . "(only count of items in new invoices is calculated"));
            $gr->addStatic()->setContent('use only if affiliate made ');
            $gr->addInteger('count', array('size' => 4));
            $gr->addStatic()->setContent(' item sales within last ');
            $gr->addInteger('days', array('size' => 4));
            $gr->addStatic()->setContent(' days');
            $set->addHidden('_conditions_status[aff_sales_amount]');
            $gr = $set->addGroup('_conditions[aff_sales_amount]', array('id' => 'aff_sales_amount'))->setLabel(___("Affiliate sales amount\n" . "trigger this commission if affiliate made more than ... sales within ... days before the current date\n" . "(only new invoices calculated)"));
            $gr->addStatic()->setContent('use only if affiliate made ');
            $gr->addInteger('count', array('size' => 4));
            $gr->addStatic()->setContent(' ' . Am_Currency::getDefault() . ' in commissions within last ');
            $gr->addInteger('days', array('size' => 4));
            $gr->addStatic()->setContent(' days');
            $set->addHidden('_conditions_status[coupon]');
            $gr = $set->addGroup('_conditions[coupon]', array('id' => 'coupon'))->setLabel(___('Used coupon'));
            $gr->setSeparator(' ');
            $gr->addSelect('used')->loadOptions(array('1' => 'Used', '0' => "Didn't Use"));
            $gr->addSelect('type')->setId('used-type')->loadOptions(array('any' => ___('Any Coupon'), 'batch' => ___("Coupon From Batch"), 'coupon' => ___("Specific Coupon")));
            $gr->addSelect('batch_id')->setId('used-batch_id')->loadOptions($this->getDi()->couponBatchTable->getOptions());
            $gr->addText('code', array('size' => 10))->setId('used-code');
            $set->addHidden('_conditions_status[paysys_id]');
            $set->addMagicSelect('_conditions[paysys_id]', array('id' => 'paysys_id'))->setLabel(___('This rule is for particular payment system'))->loadOptions(Am_Di::getInstance()->paysystemList->getOptions());
            $set->addHidden('_conditions_status[first_time]');
            $set->addStatic('_conditions[first_time]', array('id' => 'first_time'))->setLabel(___("First Time Purchase of Product"))->setContent("<div><strong>&#x2713;</strong></div>");
            $set->addHidden('_conditions_status[aff_product_id]');
            $set->addMagicSelect('_conditions[aff_product_id]', array('id' => 'aff_product_id'))->setLabel(___("Apply this rule if affiliate has active access to"))->loadOptions(Am_Di::getInstance()->productTable->getOptions());
            $set->addHidden('_conditions_status[aff_product_category_id]');
            $el = $set->addMagicSelect('_conditions[aff_product_category_id]', array('id' => 'aff_product_category_id'))->setLabel(___("Apply this rule if affiliate has active access to"));
            $el->loadOptions(Am_Di::getInstance()->productCategoryTable->getAdminSelectOptions());
        }
        $set = $form->addFieldset('', array('id' => 'commission'))->setLabel('Commission');
        if ($record->tier == 0) {
            $set->addElement(new Am_Form_Element_AffCommissionSize(null, null, 'first_payment'))->setLabel(___("Commission for First Payment\ncalculated for first payment in each invoice"));
            $set->addElement(new Am_Form_Element_AffCommissionSize(null, null, 'recurring'))->setLabel(___("Commission for Rebills"));
            $group = $set->addGroup('')->setLabel(___("Commission for Free Signup\ncalculated for first customer invoice only"));
            $group->addText('free_signup_c', array('size' => 5));
            $group->addStatic()->setContent('&nbsp;&nbsp;' . Am_Currency::getDefault());
            //->addRule('gte', 'Value must be a valid number > 0, or empty (no text)', 0);
        } else {
            $set->addText('first_payment_c')->setLabel(___("Commission\n% of commission received by referred affiliate"));
        }
        if (!$record->isGlobal()) {
            $set = $form->addFieldset('', array('id' => 'multiplier'))->setLabel('Multipier');
            $set->addText('multi', array('size' => 5, 'placeholder' => '1.0'))->setLabel(___("Multiply commission calculated by the following rules\n" . "to number specified in this field. To keep commission untouched, enter 1 or delete this rule"));
            //->addRule('gt', 'Values must be greater than 0.0', 0.0);
        }
        return $form;
    }
    public function createConfigForm(Am_Grid_Editable $grid)
    {
        $form = new Am_Form_Admin();
        $record = $grid->getRecord($grid->getCurrentAction());
        if (empty($record->type)) {
            $record->type = null;
        }
        $globalOptions = AffCommissionRule::getTypes();
        foreach (Am_Di::getInstance()->db->selectCol("SELECT DISTINCT `type` FROM ?_aff_commission_rule") as $type) {
            if (AffCommissionRule::isGlobalType($type) && $type != $record->type) {
                unset($globalOptions[$type]);
            }
        }
        $cb = $form->addSelect('type')->setLabel('Type')->loadOptions($globalOptions);
        if ($record->isGlobal()) {
            $cb->toggleFrozen(true);
        }
        $form->addScript()->setScript(<<<CUT
\$(function(){
    \$("select#type-0").change(function(){
        var val = \$(this).val();
        \$("fieldset#multiplier").toggle(val == 'multi');
        \$("fieldset#commission").toggle(val != 'multi');
        var checked = val.match(/^global-/);
        \$("#conditions").toggle(!checked);
        \$("#sort_order-0").closest(".row").toggle(!checked);
        \$("#comment-0").closest(".row").toggle(!checked);
    }).change();
    
    \$("#condition-select").change(function(){
        var val = \$(this).val();
        \$(this.options[this.selectedIndex]).prop("disabled", true);
        this.selectedIndex = 0;
        \$('#'+val).show();
    });

    \$("#conditions .row").not("#row-condition-select").each(function(){
        if (!\$(":input:filled", this).not(".magicselect").length && !\$(".magicselect-item", this).length) 
            \$(this).hide();
        else
            \$("#condition-select option[value='"+this.id+"']").prop("disabled", true);
        \$(this).find(".element-title").append("&nbsp;<a href='javascript:' class='hide-row'>X</a>&nbsp;");
    });

    \$("a.hide-row").live('click',function(){
        var row = \$(this).closest(".row");
        row.find("a.hide-row").remove();
        var id = row.hide().attr("id");
        \$("#condition-select option[value='"+id+"']").prop("disabled", false);
    });
});
CUT
);
        $form->addText('comment', array('size' => 40))->setLabel('Rule title - for your own reference')->addRule('required', 'This field is required');
        $form->addInteger('sort_order')->setLabel('Sort order - rules with lesser values executed first');
        if (!$record->isGlobal()) {
            $set = $form->addFieldset('', array('id' => 'conditions'))->setLabel('Conditions');
            $set->addSelect('', array('id' => 'condition-select'))->setLabel('Add Condition')->loadOptions(array('' => 'Select Condition...', 'row-product_id' => 'By Product', 'row-product_category_id' => 'By Product Category', 'row-aff_group_id' => 'By Affiliate Group Id', 'row-aff_sales_count' => 'By Affiliate Sales Count', 'row-aff_sales_amount' => 'By Affiliate Sales Amount'));
            $set->addMagicSelect('_conditions[product_id]', array('id' => 'product_id'))->setLabel(array('This rule is for particular products', 'if none specified, rule works for all products'))->loadOptions(Am_Di::getInstance()->productTable->getOptions());
            $el = $set->addMagicSelect('_conditions[product_category_id]', array('id' => 'product_category_id'))->setLabel(array('This rule is for particular product categories', 'if none specified, rule works for all product categories'));
            $el->loadOptions(Am_Di::getInstance()->productCategoryTable->getAdminSelectOptions());
            $el = $set->addMagicSelect('_conditions[aff_group_id]', array('id' => 'aff_group_id'))->setLabel(array('This rule is for particular affiliate groups', 'you can add user groups and assign it to customers in User editing form'));
            $el->loadOptions(Am_Di::getInstance()->userGroupTable->getSelectOptions());
            $gr = $set->addGroup('_conditions[aff_sales_count]', array('id' => 'aff_sales_count'))->setLabel(array('Affiliate sales count', 'trigger this commission if affiliate made more than ... sales within ... days before the current date' . PHP_EOL . '(recurring: affiliate sales count will be recalculated on each rebill)'));
            $gr->addStatic()->setContent('use only if affiliate made ');
            $gr->addInteger('count', array('size' => 4));
            $gr->addStatic()->setContent(' commissions within last ');
            $gr->addInteger('days', array('size' => 4));
            $gr->addStatic()->setContent(' days');
            $gr = $set->addGroup('_conditions[aff_sales_amount]', array('id' => 'aff_sales_amount'))->setLabel(array('Affiliate sales amount', 'trigger this commission if affiliate made more than ... sales within ... days before the current date' . PHP_EOL . '(recurring: affiliate sales count will be recalculated on each rebill)'));
            $gr->addStatic()->setContent('use only if affiliate made ');
            $gr->addInteger('count', array('size' => 4));
            $gr->addStatic()->setContent(' ' . Am_Currency::getDefault() . ' in commissions within last ');
            $gr->addInteger('days', array('size' => 4));
            $gr->addStatic()->setContent(' days');
        }
        $set = $form->addFieldset('', array('id' => 'commission'))->setLabel('Commission');
        if ($record->type != AffCommissionRule::TYPE_GLOBAL_2) {
            $set->addElement(new Am_Form_Element_AffCommissionSize(null, null, 'first_payment'))->setLabel(___("Commission for First Payment\ncalculated for first payment in each invoice"));
            $set->addElement(new Am_Form_Element_AffCommissionSize(null, null, 'recurring'))->setLabel(___("Commission for Rebills"));
            $set->addText('free_signup_c')->setLabel(___("Commission for Free Signup\ncalculated for first customer invoice only"));
            //->addRule('gte', 'Value must be a valid number > 0, or empty (no text)', 0);
        } else {
            $set->addText('first_payment_c')->setLabel(___("Second Level Commission\n% of commission received by referred affiliate"));
        }
        if (!$record->isGlobal()) {
            $set = $form->addFieldset('', array('id' => 'multiplier'))->setLabel('Multipier');
            $set->addText('multi', array('size' => 5, 'placeholder' => '1.0'))->setLabel(array(___("Multiply commission calculated by the following rules\n                    to number specified in this field. To keep commission untouched, enter 1 or delete this rule")));
            //->addRule('gt', 'Values must be greater than 0.0', 0.0);
        }
        return $form;
    }