public function renderOut(&$out) { $titles = array(); $this->ds->clearFields()->clearOrder()->toggleAutoGroupBy(false); foreach ($this->fields as $field) { /* @var $field Am_Grid_Field */ $name = $field->getFieldName(); $stm = $this->stms[$name]; $this->ds->addField(sprintf("SUM({$stm})", $name), '_' . $name); $titles['_' . $name] = $field->getFieldTitle(); } $totals = array(); foreach (Am_Di::getInstance()->db->selectRow($this->ds->getSql()) as $key => $val) { $totals[] = sprintf('%s %s: <strong>%s</strong>', ___('Total'), $titles[$key], Am_Currency::render($val)); } $count = count($this->grid->getFields()); $tr = sprintf('<tr><td class="grid-total" colspan="%d">%s</td></td>', $count, implode(',', $totals)); $out = preg_replace('|(<tr>\\s*<th>)|', str_replace('$', '\\$', $tr) . '\\1', $out); }
public function renderCommAmount($record, $field, $grid) { return sprintf('<td style="text-align:right"><strong>%s</strong></td>', ($record->record_type == AffCommission::VOID ? '- ' : '') . Am_Currency::render($record->amount)); }
public function renderOut(&$out) { $titles = array(); $sql = $this->ds->getSql(); $totals = array(); foreach ($this->fields as $field) { /* @var $field Am_Grid_Field */ $name = $field->getFieldName(); $stm = $this->stms[$name]; $titles['_' . $name] = $field->getFieldTitle(); $totals[] = sprintf('%s %s: <strong>%s</strong>', ___('Total'), $field->getFieldTitle(), Am_Currency::render(Am_Di::getInstance()->db->selectCell("select sum(total_qry.{$name}) from ({$sql} ) as total_qry"))); } $count = count($this->grid->getFields()); $tr = sprintf('<tr><td class="grid-total" colspan="%d">%s</td></td>', $count, implode(',', $totals)); $out = preg_replace('|(<tr>\\s*<th>)|', str_replace('$', '\\$', $tr) . '\\1', $out); }
function _getTax(InvoicePayment $p) { return Am_Currency::render($p->tax, $p->currency); }
function process(Am_Form $f) { $vars = $f->getValue(); $user = Am_Di::getInstance()->userTable->findFirstByLogin($vars['user']); if (!$user) { list($el) = $f->getElementsByName('user'); $el->setError(___('User %s not found', $vars['user'])); return false; } $aff = Am_Di::getInstance()->userTable->findFirstByLogin($vars['aff']); if (!$aff) { list($el) = $f->getElementsByName('aff'); $el->setError(___('Affiliate %s not found', $vars['user'])); return false; } $couponAff = null; if ($vars['coupon']) { $coupon = Am_DI::getInstance()->couponTable->findFirstByCode($vars['coupon']); if ($coupon && ($coupon->aff_id || $coupon->getBatch()->aff_id)) { $couponAff = Am_Di::getInstance()->userTable->load($coupon->aff_id ? $coupon->aff_id : $coupon->getBatch()->aff_id, false); } } /* @var $invoice Invoice */ $invoice = Am_Di::getInstance()->invoiceTable->createRecord(); $invoice->setUser($user); if ($vars['coupon']) { $invoice->setCouponCode($vars['coupon']); $error = $invoice->validateCoupon(); if ($error) { throw new Am_Exception_InputError($error); } } $user->aff_id = $aff->pk(); foreach ($vars['product_id'] as $plan_id => $qty) { $p = Am_Di::getInstance()->billingPlanTable->load($plan_id); $pr = $p->getProduct(); $invoice->add($pr, $qty); } $invoice->calculate(); $invoice->setPaysystem($vars['paysys_id'], false); $invoice->invoice_id = '00000'; $invoice->public_id = 'TEST'; $invoice->tm_added = sqlTime('now'); echo "<pre>"; echo $invoice->render(); echo "\nBilling Terms: " . $invoice->getTerms() . "\n" . str_repeat("-", 70) . "\n"; $helper = new Am_View_Helper_UserUrl(); $helper->setView(new Am_View()); printf("User Ordering the subscription: <a target='_blank' class='link' href='%s'>%d/%s "%s" <%s></a>\n", $helper->userUrl($user->pk()), $user->pk(), Am_Controller::escape($user->login), Am_Controller::escape($user->name_f . ' ' . $user->name_l), Am_Controller::escape($user->email)); printf("Reffered Affiliate: <a target='_blank' class='link' href='%s'>%d/%s "%s" <%s></a>\n", $helper->userUrl($aff->pk()), $aff->pk(), Am_Controller::escape($aff->login), Am_Controller::escape($aff->name_f . ' ' . $aff->name_l), Am_Controller::escape($aff->email)); if ($couponAff) { printf("Affiliate Detected by Coupon (will get commision): <a target='_blank' class='link' href='%s'>%d/%s "%s" <%s></a>\n", $helper->userUrl($couponAff->pk()), $couponAff->pk(), Am_Controller::escape($couponAff->login), Am_Controller::escape($couponAff->name_f . ' ' . $couponAff->name_l), Am_Controller::escape($couponAff->email)); } $max_tier = Am_Di::getInstance()->affCommissionRuleTable->getMaxTier(); //COMMISSION FOR FREE SIGNUP if (!(double) $invoice->first_total && !(double) $invoice->second_total && $vars['is_first']) { echo "\n<strong>FREE SIGNUP</strong>:\n"; list($item, ) = $invoice->getItems(); echo sprintf("* ITEM: %s\n", Am_Controller::escape($item->item_title)); foreach (Am_Di::getInstance()->affCommissionRuleTable->findRules($invoice, $item, $aff, 0, 0) as $rule) { echo $rule->render('* '); } $to_pay = Am_Di::getInstance()->affCommissionRuleTable->calculate($invoice, $item, $aff, 0, 0); echo "* AFFILIATE WILL GET FOR THIS ITEM: " . Am_Currency::render($to_pay) . "\n"; for ($i = 1; $i <= $max_tier; $i++) { $to_pay = Am_Di::getInstance()->affCommissionRuleTable->calculate($invoice, $item, $aff, 0, $i, $to_pay); $tier = $i + 1; echo "* {$tier}-TIER AFFILIATE WILL GET FOR THIS ITEM: " . Am_Currency::render($to_pay) . "\n"; } echo str_repeat("-", 70) . "\n"; } //COMMISSION FOR FIRST PAYMENT $price_field = (double) $invoice->first_total ? 'first_total' : 'second_total'; if ((double) $invoice->{$price_field}) { echo "\n<strong>FIRST PAYMENT ({$invoice->currency} {$invoice->{$price_field}})</strong>:\n"; $payment = Am_Di::getInstance()->invoicePaymentTable->createRecord(); $payment->invoice_id = @$invoice->invoice_id; $payment->dattm = sqlTime('now'); $payment->amount = $invoice->{$price_field}; echo str_repeat("-", 70) . "\n"; foreach ($invoice->getItems() as $item) { if (!(double) $item->{$price_field}) { continue; } //do not calculate commission for free items within invoice echo sprintf("* ITEM: %s ({$invoice->currency} {$item->{$price_field}})\n", Am_Controller::escape($item->item_title)); foreach (Am_Di::getInstance()->affCommissionRuleTable->findRules($invoice, $item, $aff, 1, 0, $payment->dattm) as $rule) { echo $rule->render('* '); } $to_pay = Am_Di::getInstance()->affCommissionRuleTable->calculate($invoice, $item, $aff, 1, 0, $payment->amount, $payment->dattm); echo "* AFFILIATE WILL GET FOR THIS ITEM: <strong>" . Am_Currency::render($to_pay) . "</strong>\n"; for ($i = 1; $i <= $max_tier; $i++) { $to_pay = Am_Di::getInstance()->affCommissionRuleTable->calculate($invoice, $item, $aff, 1, $i, $to_pay, $payment->dattm); $tier = $i + 1; echo "* {$tier}-TIER AFFILIATE WILL GET FOR THIS ITEM: <strong>" . Am_Currency::render($to_pay) . "</strong>\n"; } echo str_repeat("-", 70) . "\n"; } } //COMMISSION FOR SECOND AND SUBSEQUENT PAYMENTS if ((double) $invoice->second_total) { echo "\n<strong>SECOND AND SUBSEQUENT PAYMENTS ({$invoice->second_total} {$invoice->currency})</strong>:\n"; $payment = Am_Di::getInstance()->invoicePaymentTable->createRecord(); $payment->invoice_id = @$invoice->invoice_id; $payment->dattm = sqlTime('now'); $payment->amount = $invoice->second_total; echo str_repeat("-", 70) . "\n"; foreach ($invoice->getItems() as $item) { if (!(double) $item->second_total) { continue; } //do not calculate commission for free items within invoice echo sprintf("* ITEM: %s ({$item->second_total} {$invoice->currency})\n", Am_Controller::escape($item->item_title)); foreach (Am_Di::getInstance()->affCommissionRuleTable->findRules($invoice, $item, $aff, 2, 0, $payment->dattm) as $rule) { echo $rule->render('* '); } $to_pay = Am_Di::getInstance()->affCommissionRuleTable->calculate($invoice, $item, $aff, 2, 0, $payment->amount, $payment->dattm); echo "* AFFILIATE WILL GET FOR THIS ITEM: <strong>" . Am_Currency::render($to_pay) . "</strong>\n"; for ($i = 1; $i <= $max_tier; $i++) { $to_pay = Am_Di::getInstance()->affCommissionRuleTable->calculate($invoice, $item, $aff, 2, $i, $to_pay, $payment->dattm); $tier = $i + 1; echo "* {$tier}-TIER AFFILIATE WILL GET FOR THIS ITEM: <strong>" . Am_Currency::render($to_pay) . "</strong>\n"; } echo str_repeat("-", 70) . "\n"; } } echo "</pre>"; return true; }
public function renderOut(&$out) { $totals = array(); $totals[] = sprintf('%s %s: <strong>%s</strong>', ___('Total'), ___('To Pay'), Am_Currency::render(Am_Di::getInstance()->db->selectCell("SELECT SUM(amount) from ?_aff_payout_detail"))); $totals[] = sprintf('%s %s: <strong>%s</strong>', ___('Total'), ___('Paid'), Am_Currency::render(Am_Di::getInstance()->db->selectCell("SELECT SUM(amount) from ?_aff_payout_detail where is_paid > 0"))); $count = count($this->grid->getFields()); $tr = sprintf('<tr><td class="grid-total" colspan="%d">%s</td></td>', $count, implode(',', $totals)); $out = preg_replace('|(<tr>\\s*<th>)|', str_replace('$', '\\$', $tr) . '\\1', $out); }
public function getDescription() { return ___('spent %s %s', $this->op, Am_Currency::render($this->val)); }
function render($indent = "", InvoicePayment $payment = null) { $prefix = !is_null($payment) && !$payment->isFirst() ? 'second' : 'first'; $tm_added = is_null($payment) ? $this->tm_added : $payment->dattm; $newline = "\r\n"; $price_width = max(mb_strlen(Am_Currency::render($this->{$prefix . '_total'}, $this->currency)), 8); $column_padding = 1; $column_title_max = 60; $column_title_min = 20; $column_qty = 4 + $price_width; $column_num = 3; $column_amount = $price_width; $space = str_repeat(' ', $column_padding); $max_length = 0; foreach ($this->getItems() as $item) { $max_length = max(mb_strlen(___($item->item_title)), $max_length); } $column_title = max(min($max_length, $column_title_max), $column_title_min); $row_width = $column_num + $column_padding + $column_title + $column_padding + $column_qty + $column_padding + $column_amount + $column_padding; $column_total = $column_title + $column_qty + $column_padding; $total_space = str_repeat(' ', $column_padding + $column_num + $column_padding); $border = $indent . str_repeat('-', $row_width) . "{$newline}"; $out = $indent . ___("Invoice") . ' #' . $this->public_id . " / " . amDate($tm_added) . "{$newline}"; $out .= $border; $num = 1; foreach ($this->getItems() as $item) { $title = explode("\n", $this->wordWrap(___($item->item_title), $column_title, "\n", true)); $out .= $indent . sprintf("{$space}%{$column_num}s{$space}%-{$column_title}s{$space}%{$column_qty}s{$space}%{$price_width}s{$newline}", $num . '.', $title[0], $item->qty . 'x' . Am_Currency::render($item->{$prefix . '_price'}, $this->currency), Am_Currency::render($item->{$prefix . '_total'}, $this->currency)); for ($i = 1; $i < count($title); $i++) { $out .= $indent . sprintf("{$space}%{$column_num}s{$space}%-{$column_title}s{$newline}", ' ', $title[$i]); } $num++; } $out .= $border; if ($this->{$prefix . '_subtotal'} != $this->{$prefix . '_total'}) { $out .= $indent . sprintf("{$total_space}%-{$column_total}s{$space}%{$price_width}s{$newline}", ___('Subtotal'), Am_Currency::render($this->{$prefix . '_subtotal'}, $this->currency)); } if ($this->{$prefix . '_discount'} > 0) { $out .= $indent . sprintf("{$total_space}%-{$column_total}s{$space}%{$price_width}s{$newline}", ___('Discount'), Am_Currency::render($this->{$prefix . '_discount'}, $this->currency)); } if ($this->{$prefix . '_shipping'} > 0) { $out .= $indent . sprintf("{$total_space}%-{$column_total}s{$space}%{$price_width}s{$newline}", ___('Shipping'), Am_Currency::render($this->{$prefix . '_shipping'}, $this->currency)); } if ($this->{$prefix . '_tax'} > 0) { $out .= $indent . sprintf("{$total_space}%-{$column_total}s{$space}%{$price_width}s{$newline}", ___('Tax') . sprintf(' (%d%s)', $this->tax_rate, '%'), Am_Currency::render($this->{$prefix . '_tax'}, $this->currency)); } $out .= $indent . sprintf("{$total_space}%-{$column_total}s{$space}%{$price_width}s{$newline}", ___('Total'), Am_Currency::render($this->{$prefix . '_total'}, $this->currency)); $out .= $border; if ($this->rebill_times) { $terms = explode("\n", $this->wordWrap(___($this->getTerms()), $row_width, "\n", true)); foreach ($terms as $term_part) { $out .= $indent . $term_part . $newline; } $out .= $border; } return $out; }
public function keywordsAction() { $ds = new Am_Query($this->getDi()->affKeywordTable); $ds->addField('t.`value`', 'keyword'); $ds->addField('count(clicks.log_id)', 'clicks_count'); $ds->addField('count(distinct leads.user_id)', 'leads_count'); $ds->addField('sum(if(commissions.record_type="commission", 1, 0))', 'sales_count'); $ds->addField('sum(if(commissions.record_type="commission", amount, -amount))', 'sales_amount'); $ds->addWhere('t.aff_id=?', $this->getDi()->auth->getUserId()); $ds->leftJoin('?_aff_click', 'clicks', 't.keyword_id = clicks.keyword_id'); $ds->leftJoin('?_aff_commission', 'commissions', 't.keyword_id = commissions.keyword_id'); $ds->leftJoin('?_aff_lead', 'leads', 't.keyword_id = leads.keyword_id'); $ds->groupBy('keyword_id'); $grid = new Am_Grid_ReadOnly('_aff_keywords', 'Keywords', $ds, $this->getRequest(), $this->getView()); $grid->addField('keyword', ___('Keyword')); $grid->addField('clicks_count', ___('Clicks')); $grid->addField('leads_count', ___('Leads')); $grid->addField('sales_count', ___('Sales')); $grid->addField('sales_amount', ___('Commissions'))->setRenderFunction(function ($record) { return "<td>" . Am_Currency::render($record->sales_amount) . "</td>"; }); $grid->runWithLayout('aff/keywords.phtml'); }
public function keywordsAction() { $uid = $this->getDi()->auth->getUserId(); $db = $this->getDi()->db; $db->query('DROP TEMPORARY TABLE IF EXISTS ?_aff_keywords_tmp'); $db->query("CREATE TEMPORARY TABLE ?_aff_keywords_tmp (\n keyword_id int not null DEFAULT 0,\n keyword varchar(64) not null DEFAULT '',\n clicks_count int not null DEFAULT 0,\n leads_count int not null DEFAULT 0,\n sales_count int not null DEFAULT 0,\n sales_amount int not null DEFAULT 0,\n PRIMARY KEY (`keyword_id`)\n )"); //clicks $db->query("INSERT into ?_aff_keywords_tmp (keyword_id, clicks_count) \n SELECT keyword_id, count(*) from ?_aff_click where keyword_id is not null and aff_id = ? group by keyword_id", $uid); //leads $db->query("INSERT into ?_aff_keywords_tmp (keyword_id, leads_count) \n SELECT keyword_id, cnt from (SELECT keyword_id, count(*) as cnt from ?_aff_lead \n where keyword_id is not null and aff_id = ? group by keyword_id) s\n ON DUPLICATE KEY UPDATE leads_count = s.cnt", $uid); //sales_count $db->query("INSERT into ?_aff_keywords_tmp (keyword_id, sales_count) \n SELECT keyword_id, cnt from (SELECT keyword_id, sum(if(record_type='commission', 1, 0)) as cnt from ?_aff_commission \n where keyword_id is not null and aff_id = ? group by keyword_id) s\n ON DUPLICATE KEY UPDATE sales_count = s.cnt", $uid); //sales_amount $db->query("INSERT into ?_aff_keywords_tmp (keyword_id, sales_amount) \n SELECT keyword_id, cnt from (SELECT keyword_id, sum(if(record_type='commission', amount, -amount)) as cnt from ?_aff_commission \n where keyword_id is not null and aff_id = ? group by keyword_id) s\n ON DUPLICATE KEY UPDATE sales_amount = s.cnt", $uid); //keyword $db->query("UPDATE ?_aff_keywords_tmp t set keyword = (SELECT value from ?_aff_keyword s where s.keyword_id = t.keyword_id)"); $ds = new Am_Query(new Am_Table($db, '?_aff_keywords_tmp', 't')); $grid = new Am_Grid_ReadOnly('_aff_keywords', 'Keywords', $ds, $this->getRequest(), $this->getView()); $grid->addField('keyword', ___('Keyword')); $grid->addField('clicks_count', ___('Clicks')); $grid->addField('leads_count', ___('Leads')); $grid->addField('sales_count', ___('Sales')); $grid->addField('sales_amount', ___('Commissions'))->setRenderFunction(function ($record) { return "<td>" . Am_Currency::render($record->sales_amount) . "</td>"; }); $grid->runWithLayout('aff/keywords.phtml'); }
public function getUsedCount($obj) { $invoices = Am_Di::getInstance()->invoiceTable->findByCouponId($obj->coupon_id); if (!$invoices) { return ''; } $ret = array(); $out = ''; $wrap = '<strong>' . ___('Transactions with this coupon:') . '</strong>' . '<div><table class="grid">' . '<tr><th>' . ___('User') . '</th><th>' . ___('Invoice') . '</th><th>' . ___('Date/Time') . '</th><th>' . ___('Receipt#') . '</th><th>' . ___('Amount') . '</th><th>' . ___('Discount') . '</th></tr>' . '%s</table></div>'; $tpl = '<tr><td>%s (%s %s)</td><td>%d/%s</td><td>%s</td><td>%s</td><td>%s</td><td><strong>%s</strong></td></tr>'; foreach ($invoices as $invoice) { if ($invoice->getStatus() == Invoice::PENDING) { continue; } $payments = $this->getDi()->invoicePaymentTable->findBy(array('invoice_id' => $invoice->invoice_id, 'discount' => '<>0'), null, null, "invoice_payment_id"); foreach ($payments as $payment) { $user = Am_Di::getInstance()->userTable->load($payment->user_id); $ret[] = sprintf($tpl, $this->getDi()->view->escape($user->login), $this->getDi()->view->escape($user->name_f), $this->getDi()->view->escape($user->name_l), $invoice->pk(), $invoice->public_id, amDatetime($payment->dattm), $this->getDi()->view->escape($payment->receipt_id), $this->getDi()->view->escape(Am_Currency::render($payment->amount)), $this->getDi()->view->escape(Am_Currency::render($payment->discount))); } //100% discount if (!$payments) { try { $user = Am_Di::getInstance()->userTable->load($invoice->user_id); $ret[] = sprintf($tpl, $this->getDi()->view->escape($user->login), $this->getDi()->view->escape($user->name_f), $this->getDi()->view->escape($user->name_l), $invoice->pk(), $invoice->public_id, amDatetime($invoice->tm_started), '–', $this->getDi()->view->escape(Am_Currency::render(0)), ___('100% discount')); } catch (Am_Exception_Db_NotFound $e) { $this->getDi()->errorLogTable->logException($e); } } } $out .= implode("\n", $ret); return $out ? sprintf($wrap, $out) : $out; }
function statsAction() { require_once 'Am/Report.php'; require_once 'Am/Report/Standard.php'; include_once APPLICATION_PATH . '/aff/library/Reports.php'; if ($this->getDi()->config->get('aff.affiliate_can_view_details') && ($detailDate = $this->getFiltered('detailDate'))) { if (!preg_match('/^\\d{4}-\\d{2}-\\d{2}$/', $detailDate)) { throw new Am_Exception_InputError("Wrong date passed"); } $c = 0; foreach ($this->getDi()->affCommissionTable->fetchByDate($detailDate, $this->user->user_id) as $c) { $c++; $p = $c->getPayment(); if (!$p) { continue; } $u = $p->getUser(); $i = $p->getInvoice(); $product = $c->getProduct(); $s = sprintf('%s (%s) – <strong>%s</strong>%s', $this->escape($u->name_f . ' ' . $u->name_l), ___($product->title), Am_Currency::render($c->amount), $c->tier ? sprintf(' (%d-tier)', $c->tier + 1) : ''); if ($c->record_type == AffCommission::VOID) { $s = "<div style='color: red'>{$s} (void)</div>"; } echo $s . "<br />\n"; } if (!$c) { echo ___('No commissions on this date'); } return; } $rs = new Am_Report_AffStats(); $rs->setAffId($this->user->user_id); $rc = new Am_Report_AffClicks(); $rc->setAffId($this->user->user_id); if (!$this->getInt('monthyear')) { $firstDate[] = $this->getDi()->db->selectCell("SELECT MIN(date) FROM ?_aff_commission WHERE aff_id=?d", $this->user->user_id); $firstDate[] = current(explode(' ', $this->getDi()->db->selectCell("SELECT MIN(`time`) FROM ?_aff_click WHERE aff_id=?d", $this->user->user_id))); $rs->setInterval(min($firstDate), 'now')->setQuantity(new Am_Report_Quant_Month()); } else { $ym = $this->getInt('monthyear'); if (!$ym || strlen($ym) != 6) { $ym = date('Ym'); } $start = mktime(0, 0, 0, substr($ym, 4, 2), 1, substr($ym, 0, 4)); $rs->setInterval(date('Y-m-d 00:00:00', $start), date('Y-m-t 23:59:59', $start))->setQuantity(new Am_Report_Quant_Day()); $this->view->period = array(date('Y-m-d 00:00:00', $start), date('Y-m-t 23:59:59', $start)); } $rc->setInterval($rs->getStart(), $rs->getStop())->setQuantity(clone $rs->getQuantity()); $result = $rs->getReport(); $rc->getReport($result); $output = new Am_Report_Graph_Line($result); $output->setSize('100%', 300); $this->view->report = $output->render(); /* extract data from report to show it in view */ $rows = array(); $totals = array(); $lines = $result->getLines(); foreach ($result->getPointsWithValues() as $r) { /* @var $r Am_Report_Point */ if ($result->getQuantity()->getId() == 'month') { $hasValue = false; foreach ($lines as $line) { if ($r->getValue($line->getKey())) { $hasValue = true; break; } } $href = $hasValue ? $this->view->url(array("monthyear" => $r->getKey())) : ''; } elseif ($this->getModule()->getConfig('affiliate_can_view_details')) { $href = "javascript: showAffDetails('{$r->getKey()}')"; } else { $href = ""; } $rows[$r->getKey()]['date'] = $r->getLabel(); $rows[$r->getKey()]['date_href'] = $href; foreach ($lines as $i => $line) { list($start, $stop) = $result->getQuantity()->getStartStop($r->getKey()); $href = $r->getValue($line->getKey()) > 0 ? sprintf("javascript:affDetail('%s', '%s', '%s')", $start, $stop, $r->getLabel()) : null; $rows[$r->getKey()][$line->getKey() . '_href'] = $href; $rows[$r->getKey()][$line->getKey()] = $r->getValue($line->getKey()); $totals[$line->getKey()] = @$totals[$line->getKey()] + $r->getValue($line->getKey()); } } $this->view->totals = $totals; $this->view->rows = $rows; $this->view->result = $result; $this->view->display('aff/stats.phtml'); }