FINAL suepr merge step : added all modules to this super repos

This commit is contained in:
Bachir Soussi Chiadmi
2015-04-19 16:46:59 +02:00
7585 changed files with 1723356 additions and 18 deletions

View File

@@ -0,0 +1,339 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.

View File

@@ -0,0 +1,33 @@
=== About Ubercart Coupons ===
This module was created to work with the Ubercart ecommerce module for Drupal.
=== About the Authors ===
Original Author
Blake Lucchesi
blake@boldsource.com
www.boldsource.com
Drupal 5 Maintenance
David Long
dave@longwaveconsulting.com
Drupal 6 Port
Jordan of Cubicle Collective
jordan@gocubeco DAWT com
Coupon Reports Sponsored by: Oasis Day Spa - http://www.oasisdayspanyc.com
Drupal 7 Port
Chris Oden
wodenx@gmail.com
Sponsored by Fishhound - http://www.fishhound.com

View File

@@ -0,0 +1,7 @@
.totals{
font-size: 14px;
padding: 10px;
border: 1px solid #555;
background-color: #CCC;
margin: 10px 0;
}

View File

@@ -0,0 +1,144 @@
<?php
/**
* @file
* Ubercart Discount Coupon Tests.
*/
/**
* SimpleTests for Ubercart Discount Coupons
*/
class UcCouponTestCase extends UbercartTestHelper {
public static function getInfo() {
return array(
'name' => 'Discount Coupons',
'description' => 'Test discount coupons.',
'group' => 'Ubercart',
);
}
/**
* Overrides DrupalWebTestCase::setUp().
*/
function setUp() {
$modules = array('uc_coupon', 'uc_payment', 'uc_payment_pack');
$permissions = array('manage store coupons');
parent::setUp($modules, $permissions);
$this->drupalLogin($this->adminUser);
}
function createCoupon($edit = array()) {
$edit += array(
'code' => $this->randomName(8),
'name' => $this->randomName(20),
'discount' => mt_rand(1, 50) . '%',
'status' => 1,
);
$form_state = array('values' => $edit);
drupal_form_submit('uc_coupon_add_form', $form_state);
$cid = db_query('SELECT cid FROM {uc_coupons} WHERE code = :code', array(':code' => trim(strtoupper($edit['code']))))->fetchField();
$this->assertTrue($cid, 'Coupon was created successfully');
if (!$cid) debug(form_get_errors(), 'Form errors:');
$coupon = uc_coupon_load($cid);
return $coupon;
}
public function applyCoupons($coupons, $products = array(), $total = NULL) {
foreach ($products as $product) {
$this->drupalPost('node/' . $product->nid, array(), t('Add to cart'));
$this->assertRaw($product->title, 'Product appears on cart page');
}
foreach ($coupons as $coupon) {
$this->drupalPost('cart', array('code' => $coupon->code), t('Apply to order'));
if ($total !== FALSE) {
$this->assertRaw('Coupon ' . $coupon->code, 'Applied coupon code appears on cart page.');
}
else {
$this->assertNoRaw('Coupon ' . $coupon->code, 'Invalid coupon code does not appear on cart page.');
}
}
if ($total === FALSE) {
$this->assertNoRaw(uc_currency_format($total), 'Invalid discount was not applied to total.');
}
elseif (!is_null($total)) {
$this->assertRaw(uc_currency_format($total), 'Discounted total is correct on cart page.');
}
}
// Our own version of the checkout sequence, optionally checking for coupons.
function checkout($coupons = array(), $total = FALSE) {
$total = uc_currency_format($total);
$this->drupalPost('cart', array('items[0][qty]' => 1), t('Checkout'));
foreach ($coupons as $coupon) {
$this->assertRaw('Coupon ' . $coupon->code, "Coupon $coupon->code appears on checkout page.");
}
if ($total !== FALSE) {
$this->assertRaw($total, "The order total of $total is correct on the checkout page");
}
$edit = $this->populateCheckoutForm();
$this->drupalPost(NULL, $edit, t('Review order'));
foreach ($coupons as $coupon) {
$this->assertRaw('Coupon ' . $coupon->code, "Coupon $coupon->code appears on review page.");
}
if ($total !== FALSE) {
$this->assertRaw($total, "The order total of $total is correct on the review page");
}
// Complete the review page.
$this->drupalPost(NULL, array(), t('Submit order'));
$order_id = db_query("SELECT order_id FROM {uc_orders} WHERE delivery_first_name = :name", array(':name' => $edit['panes[delivery][delivery_first_name]']))->fetchField();
if ($order_id) {
$order = uc_order_load($order_id);
if ($total !== FALSE) {
$this->assertEqual(uc_currency_format(uc_order_get_total($order)), $total, 'Saved order total is correct');
}
}
else {
$this->fail(t('No order was created.'));
$order = FALSE;
}
return $order;
}
public function testGiftCertificate() {
$coupon = $this->createCoupon(array(
'discount' => '100',
'store_credit' => 1,
));
$product = $this->createProduct(array(
'sell_price' => '75',
));
$this->applyCoupons(array($coupon), array($product), 0);
$this->assertText('Subtotal: $0.00');
$order = $this->checkout();
uc_order_update_status($order->order_id, 'payment_received');
$this->applyCoupons(array($coupon), array($product), 50);
}
public function testCoupon() {
$coupon = $this->createCoupon( array(
'discount' => '100'
));
$product = $this->createProduct(array(
'sell_price' => '150'
));
$total = $product->sell_price - $coupon->value;
$this->applyCoupons(array($coupon), array($product), $total);
$order = $this->checkout(array($coupon), $total);
// Try again to make sure the default usage limit works.
uc_order_update_status($order->order_id, 'payment_received');
$this->applyCoupons(array($coupon), array($product), FALSE);
// Clear the usage limit and try again.
$coupon->max_uses = 0;
uc_coupon_save($coupon);
$this->applyCoupons(array($coupon), array(), $total);
}
}

View File

@@ -0,0 +1,69 @@
<?php
/**
* Basic template for a printed coupon certificate.
*
* Coupon data is available in the following variables:
*
* $coupon - the coupon object
* $code - the specific coupon code to be printed
* $display_name - the name of the coupon (with "purchased by..." stripped)
* $include - an array of the items for which this coupon is valid, if any
* $exclude - an array of the items for which this coupon is not valid, if any
* $valid_from - the formatted date the coupon is valid from, if set
* $valid_until - the formatted date the coupon is valid until, if set
* $not_yet_valid - TRUE if the coupon is not yet valid
* $max_uses_per_user - the number of times this coupon can be used per customer
*
* For purchased coupons, the following is also available:
*
* $coupon->owner - the account object of the purchaser
*
* Also includes global tokens, and thus the global Ubercart store information.
*
* Templates for specific coupons may be created after the following patterns:
* uc-coupon-certificate--[cid].tpl.php
* (where [cid] is the id of the coupon for which the template should be applied)
* uc-coupon-certificate--base-[cid].tpl.php
* (where [cid] is the base cid for the coupon, if it was a purchased coupon)
*/
?>
<div class="uc-coupon-certificate">
<?php if (!empty($site_logo)): ?>
<div class="site-logo"><?php print $site_logo; ?></div>
<?php endif; ?>
<?php if (!empty($store_name)): ?>
<h3 class="store-name"><?php print $store_name;?></h3>
<?php endif; ?>
<?php if (!empty($site_url)): ?>
<div class="store-url"><?php print $site_url;?></div>
<?php endif; ?>
<h2 id="title"><?php print $display_name; ?></h2>
<h1 class="uc-coupon-code"><?php print $code; ?></h1>
<p>This certificate entitles you to a discount of <?php print $value ?> at <?php print $store_name ?>.
<?php if (!empty($site_url)): ?>
Please visit us at <?php print $site_url; ?> and enter the code <strong><?php print $code; ?></strong> at checkout to obtain your discount.
<?php endif; ?>
</p>
<?php if (!empty($valid_until)): ?>
<p>Valid <?php if (!empty($not_yet_valid)) print "from " . $valid_from; ?> until <?php print $valid_until; ?>.</p>
<?php endif; ?>
<?php if (!empty($max_uses_per_user)): ?>
<p><?php print format_plural($max_uses_per_user, 'Maximum one use per customer.', 'Maximum @count uses per customer.'); ?></p>
<?php endif; ?>
<dl>
<?php if (!empty($include)): ?>
<dt>May be used for any of the following:</dt>
<dd><?php print implode(", ", $include); ?>.</dd>
<?php endif; ?>
<?php if (!empty($exclude)): ?>
<dt>Not valid for any of the following:</dt>
<dd><?php print implode(", ", $exclude); ?>.</dd>
<?php endif; ?>
</dl>
</div>

View File

@@ -0,0 +1,10 @@
<!DOCTYPE html>
<html>
<head>
<title>Coupon</title>
<?php print $styles; ?>
</head>
<body onload="window.print();">
<?php print $content ?>
</body>
</html>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,56 @@
(function($) {
Drupal.behaviors.ucCouponAdmin = {
attach: function(context) {
function toggleUsageLimits() {
if ($('#edit-store-credit').is(':checked')) {
$('#edit-usage-limits').hide();
}
else {
$('#edit-usage-limits').show();
}
}
$('#edit-store-credit', context).click(toggleUsageLimits);
$('#edit-discount', context).keyup(function() {
if (this.value.indexOf('%') == -1) {
$(this).siblings('span').show();
}
else {
$(this).siblings('span').hide();
}
if (this.value.indexOf('%') != -1 || this.value.indexOf('=') != -1) {
$('#store-credit-wrapper').hide();
$('#edit-usage-limits').show();
}
else {
$('#store-credit-wrapper').show();
toggleUsageLimits();
}
}).keyup();
$('#edit-store-credit', context).click(function() {
if ($(this).is(':checked')) {
$('#edit-usage-limits').hide();
}
else {
$('#edit-usage-limits').show();
}
});
$('input[name=apply_to]', context).click(function() {
if (this.value == 'cheapest' || this.value == 'expensive') {
$('.form-item-apply-count').show();
}
else {
$('.form-item-apply-count').hide();
}
}).filter(':checked').click();
if ($('input[name=use_validity]', context).change(function() {
$('.form-item-valid-from, .form-item-valid-until').toggle();
}).is(':not(:checked)')) {
$('.form-item-valid-from, .form-item-valid-until').hide();
}
}
};
})(jQuery);

View File

@@ -0,0 +1,212 @@
<?php
/**
* @file
*
* Ubercart Discount Coupon module api/hooks.
* Version 7.x-2.x
*/
/**
* hook_uc_coupon_usage_alter().
*
* Allow modules to alter the usage count for a coupon.
*
* @param $usage
* An associative array consiting of the following keys:
* - 'user' => The number of times this coupon has been used by the specified user.
* - 'codes' => An associative array listing the total number of uses for each code (for all users).
* @param $cid
* The coupon-id of the coupon in question.
* @param $uid
* The user-id whose usage is to be checked.
*/
function hook_uc_coupon_usage_alter(&$usage, $cid, $uid) {
// See if this coupon has been used in our table.
$rows = db_query('SELECT code, uses FROM {extra_coupon_usage} WHERE cid = :cid', array(':cid' => $cid));
foreach ($rows as $row) {
if (isset($usage[$row->code])) {
$usage[$row->code] += $row->uses;
}
else {
$usage[$row->code] = $row->uses;
}
}
}
/**
* hook_uc_coupon_actions().
*
* Allows modules to add to the list of actions available when coupons are listed in a table.
*
* @param $coupon
* The coupon being displayed.
* @return
* An associative array describing the actions available. Must contain the followoing keys:
* - 'url': The url where the action is processed.
* - 'icon': The icon to display for this action.
* - 'title': The text to display as a title for the action (usually as hover text over the icon).
*/
function hook_uc_coupon_actions($coupon) {
$actions = array();
// Provide a "mark coupon as used" action.
if (user_access('mark coupon as used')) {
$actions[] = array(
'url' => 'admin/store/coupons/mark-as-used/' . $coupon->cid,
'icon' => drupal_get_path('module', 'mymodule') . 'mark_as_used.gif',
'title' => t('Mark coupon: @name as used', array('@name' => $coupon->name)),
);
};
return $actions;
}
/**
* hook_uc_coupon_revalidate().
*
* Invoked whenever the coupons added to the current session are about to be validated.
*
* Modules implementing this hook may add or remove coupon codes from the session via calls to
* uc_coupon_session_add() or uc_coupon_session_clear().
*
* @param $order
* The order against which the coupon will be validated.
*/
function hook_uc_coupon_revalidate($order) {
// Add a code if there are both a widget and a doohickey in the cart.
$gotwidget = FALSE;
$gotdoohickey = FALSE;
foreach ($order->products as $product) {
$node = node_load($product->nid);
if ($node) {
if ($node->type == 'widget') {
$gotwidget = TRUE;
}
elseif ($node->type == 'doohickey') {
$gotdoohickey = TRUE;
}
if ($gotwidget && $gotdoohickey) {
uc_coupon_session_add('JACKPOT', 'auto');
return;
}
}
}
}
/**
* hook_uc_coupon_apply().
*
* Invoked whenever a valid coupon is applied to an order. May be invoked than once for the same
* coupon if it becomes invalid due to change in cart contents.
*
* Note that you should not do anything in your hoook implementation which causes the
* current cart contents to be rebuilt. This includes calls to uc_cart_add_item() without
* explicitly setting the $rebuild argument to false. And, since coupons may be submitted
* on the checkout page after the cart contents are frozen, updates to the cart contents
* may fail under some circumstances anyway.
*
* @param $coupon
* The fully validated coupon which was applied.
*/
function hook_uc_coupon_apply($coupon) {
// Grant a role to the active user when a particular coupon is applied.
// This could be used in conjunction with a node access module to expose products
// only when certain coupon codes are entered.
global $user;
if ($coupon->cid == 99 && $user->uid != 0) {
$roles = $user->roles + array(99 => 'My Special Role');
user_save($user, array('roles' => $roles));
}
}
/**
* hook_uc_coupon_remove().
*
* Invoked whenever a previously valid coupon is removed.
*
* Note that you should not do anything in your hoook implementation which causes the
* current cart contents to be rebuilt. This includes calls to uc_cart_add_item() without
* explicitly setting the $rebuild argument to false. And, since coupons may be submitted
* on the checkout page after the cart contents are frozen, updates to the cart contents
* may fail under some circumstances anyway.
*
* @param $coupon
* The coupon which was removed.
*/
function hook_uc_coupon_remove($coupon) {
// Revoke a role for the active user when a particular coupon is removed.
global $user;
if ($coupon->cid == 99 && $user->uid != 0) {
$roles = $user->roles;
$key = array_search('My Special Role', $roles);
if ($key !== FALSE) {
unset($roles[$key]);
user_save($user, array('roles' => $roles));
}
}
}
/**
* Add extra validation to a coupon.
*
* @param $coupon
* The coupon object to validate, with special fields set as follows:
* - $coupon->code: The specific code to be applied (even for bulk coupons).
* - $coupon->amount: If $order !== FALSE, the discount that should be applied.
* - $coupon->usage: Coupon usage data from uc_coupon_count_usage().
* @param $order
* The order against which this coupon is to be applied, or FALSE to bypass order validation.
* @param $account
* The account of the user trying to use the coupon, or FALSE to bypass user validation.
*
* @return
* TRUE if the coupon should be accepted.
* NULL to allow other modules to determine validation.
* Otherwise, a string describing the reason for failure.
*/
function hook_uc_coupon_validate(&$coupon, $order, $account) {
// Check for allowed combinations.
if (!empty($order->data['coupons'])) {
foreach (array_keys($order->data['coupons']) as $code) {
$other = uc_coupon_find($code);
$other_listed = !empty($coupon->data['combinations']) && in_array($other->cid, $coupon->data['combinations']);
$this_ok = (isset($coupon->data['negate_combinations']) xor $other_listed);
$this_listed = !empty($other->data['combinations']) && in_array($coupon->cid, $other->data['combinations']);
$other_ok = (isset($other->data['negate_combinations']) xor $this_listed);
if (!$this_ok || !$other_ok) {
return t('This coupon combination is not allowed.');
}
}
}
// Check maximum usage per code.
if ($coupon->max_uses > 0 && !empty($coupon->usage['codes'][$coupon->code]) && $coupon->usage['codes'][$coupon->code] >= $coupon->max_uses) {
return t('This coupon has reached the maximum redemption limit.');
}
// Check maximum usage per user.
if ($account && isset($coupon->data['max_uses_per_user']) && $coupon->usage['user'] >= $coupon->data['max_uses_per_user']) {
return t('This coupon has reached the maximum redemption limit.');
}
// Check user ID.
if ($account && isset($coupon->data['users'])) {
if (in_array("$account->uid", $coupon->data['users'], TRUE) xor !isset($coupon->data['negate_users'])) {
return t('Your user ID is not allowed to use this coupon.');
}
}
// Check roles.
if ($account && isset($coupon->data['roles'])) {
$role_found = FALSE;
foreach ($coupon->data['roles'] as $role) {
if (in_array($role, $account->roles)) {
$role_found = TRUE;
break;
}
}
if ($role_found xor !isset($coupon->data['negate_roles'])) {
return t('You do not have the correct permission to use this coupon.');
}
}
}

View File

@@ -0,0 +1,34 @@
.view-uc-coupon-purchase-view .uc-coupon-code-used {
text-decoration: line-through;
}
.view-uc-coupon-purchase-view .views-field-base-name {
width: 20%;
}
.view-uc-coupon-purchase-view td {
vertical-align: top;
}
div.uc-coupon-certificate {
page-break-after: always;
background: white;
width: 90%;
margin: auto;
border: 1px solid blue;
padding: 2%;
}
#uc-coupon-add-form #edit-valid-from-wrapper label,
#uc-coupon-add-form #edit-valid-until-wrapper label {
float: left;
width: 8em;
margin-top: 2px;
}
#uc-cart-pane-coupon,
#uc-cart-pane-coupon-automatic {
border: solid 1px #bbb;
margin-top: .5em;
padding: 0 .75em;
}

View File

@@ -0,0 +1,326 @@
<?php
/**
* @file
* Entity Controller and Metadata Controller classes for uc_coupon.
*/
/**
* Controller class for uc_coupon entity.
*/
class UcCouponController extends EntityAPIController {
/**
* @see EntityAPIController::delete()
*/
public function delete($ids, DatabaseTransaction $transaction = NULL) {
parent::delete($ids, $transaction);
db_delete('uc_coupons_orders')
->condition('cid', $ids, 'IN')
->execute();
}
/**
* @see EntityAPIController::save()
*/
public function save($coupon, DatabaseTransaction $transaction = NULL) {
if (empty($coupon->cid)) {
$coupon->created = REQUEST_TIME;
$coupon->bulk_seed = md5(uniqid());
}
parent::save($coupon, $transaction);
}
/**
* @see EntityAPIController::buildContent()
*/
public function buildContent($coupon, $view_mode = 'full', $langcode = NULL, $content = array()) {
$rows = array();
$rows[] = array(t('Name'), check_plain($coupon->name));
if (!$coupon->status) {
$status = t('Inactive');
}
elseif (!$coupon->valid_until) {
$status = t('Active');
}
elseif (REQUEST_TIME < $coupon->valid_from) {
$status = t('Not valid until @date', array('@date' => _uc_coupon_format_date($coupon->valid_from, variable_get('date_format_uc_store', 'm/d/Y H:iT'))));
}
elseif (REQUEST_TIME > $coupon->valid_until) {
$status = t('Expired on @date', array('@date' => _uc_coupon_format_date($coupon->valid_until, variable_get('date_format_uc_store', 'm/d/Y H:iT'))));
}
else {
$status = t('Active until @date', array('@date' => _uc_coupon_format_date($coupon->valid_until, variable_get('date_format_uc_store', 'm/d/Y H:iT'))));
}
$rows[] = array(t('Status'), $status);
if (!$coupon->bulk) {
$rows[] = array(t('Code'), check_plain($coupon->code) . ' (' . l(t('Print'), 'admin/store/coupons/' . $coupon->cid . '/print') . ')');
if ($coupon->max_uses) {
$rows[] = array(t('Maximum uses'), $coupon->max_uses);
}
}
else {
$codes = '<strong>' . check_plain($coupon->code) . ' &times; ' . check_plain($coupon->data['bulk_number']) . '</strong>';
$codes .= ' (' . l(t('Download codes'), 'admin/store/coupons/' . $coupon->cid . '/codes') . ')';
$codes .= ' (' . l(t('Print all'), 'admin/store/coupons/' . $coupon->cid . '/print') . ')';
for ($id = 0; $id < $coupon->data['bulk_number']; $id++) {
$code = uc_coupon_get_bulk_code($coupon, $id);
$codes .= '<br />' . check_plain($code) . ' (' . l(t('Print'), 'admin/store/coupons/' . $coupon->cid . '/print/' . $code) . ')';
}
$rows[] = array(t('Codes'), $codes);
//$rows[] = array(t('Bulk seed'), check_plain($coupon->bulk_seed));
if ($coupon->max_uses) {
$rows[] = array(t('Maximum uses per code'), $coupon->max_uses);
}
}
$rows[] = array(t('Discount value'), theme('uc_coupon_discount', array('coupon' => $coupon)));
switch ($coupon->data['apply_to']) {
case 'subtotal':
$applies = t('Order subtotal');
break;
case 'products_total':
$applies = t('Total of matching products');
break;
case 'products':
$applies = t('Matching products');
break;
case 'cheapest':
$applies = format_plural($coupon->data['apply_count'], 'Cheapest product', '@count cheapest products');
break;
case 'expensive':
$applies = format_plural($coupon->data['apply_count'], 'Most expensive product', '@count most expensive products');
break;
}
$rows[] = array(t('Applied to'), $applies);
if ($coupon->data['apply_to'] != 'subtotal') {
$restrict = array();
if (isset($coupon->data['product_types'])) {
$key = format_plural(count($coupon->data['product_types']), 'All products in class', 'All products in classes');
$restrict[$key] = $coupon->data['product_types'];
}
if (isset($coupon->data['products'])) {
$products = array();
foreach ($coupon->data['products'] as $nid) {
$products[] = check_plain(db_query("SELECT title FROM {node} WHERE nid = :nid", array(':nid' => $nid))->fetchField());
}
if (isset($coupon->data['negate_products'])) {
$restrict[t('All products except')] = $products;
}
else {
$restrict[format_plural(count($products), 'Product', 'Products')] = $products;
}
}
if (isset($coupon->data['skus'])) {
$restrict[format_plural(count($coupon->data['skus']), 'SKU', 'SKUs')] = $coupon->data['skus'];
}
if (isset($coupon->data['terms'])) {
$terms = array();
foreach ($coupon->data['terms'] as $tid) {
$terms[] = check_plain(db_query("SELECT name FROM {taxonomy_term_data} WHERE tid = :tid", array(':tid' => $tid))->fetchField());
}
if (isset($coupon->data['negate_terms'])) {
$restrict[t('All taxonomy terms except')] = $terms;
}
else {
$restrict[format_plural(count($terms), 'Taxonomy term', 'Taxonomy terms')] = $terms;
}
}
if ($restrict) {
$or = FALSE;
foreach ($restrict as $title => &$restriction) {
if ($or) {
$title = t('or') . ' ' . $title;
}
$restriction = $title . ': <em>' . implode('</em>, <em>', $restriction) . '</em>';
$or = TRUE;
}
$rows[] = array(t('Product restrictions'), implode($restrict, '<br />'));
}
}
$restrict = array();
if (isset($coupon->data['users'])) {
$users = array();
foreach ($coupon->data['users'] as $uid) {
$users[] = check_plain(db_query("SELECT name FROM {users} WHERE uid = :uid", array(':uid' => $uid))->fetchField());
}
if (isset($coupon->data['negate_users'])) {
$restrict[t('All users except')] = $users;
}
else {
$restrict[format_plural(count($users), 'User', 'Users')] = $users;
}
}
if (isset($coupon->data['max_uses_per_user'])) {
$restrict['Maximum uses per user'] = array($coupon->data['max_uses_per_user']);
}
if (isset($coupon->data['roles'])) {
if (isset($coupon->data['negate_roles'])) {
$restrict[t('All roles except')] = $coupon->data['roles'];
}
else {
$restrict[format_plural(count($users), 'Role', 'Roles')] = $coupon->data['roles'];
}
}
if ($restrict) {
foreach ($restrict as $title => &$restriction) {
$restriction = $title . ': <em>' . implode('</em>, <em>', $restriction) . '</em>';
}
$rows[] = array(t('User restrictions'), implode($restrict, '<br />'));
}
if ($coupon->minimum_order > 0) {
$rows[] = array(t('Order restrictions'), t('Minimum subtotal') . ': <em>' . uc_currency_format($coupon->minimum_order) . '</em>');
}
$combo_list = array();
if (!empty($coupon->data['combinations'])) {
$combos = db_query('SELECT cid, name FROM {uc_coupons} where cid IN (:cids)', array(':cids' => $coupon->data['combinations']));
foreach ($combos as $combo) {
$combo_list[] = check_plain("$combo->name [cid:$combo->cid]");
}
}
if (isset($coupon->data['negate_combinations'])) {
$ctext = empty($combo_list) ? t('Any.') : t('Any but:') . ' ' . implode(', ', $combo_list);
}
else {
$ctext = empty($combo_list) ? t('None.') : t('Only:') . ' ' . implode(', ', $combo_list);
}
$rows[] = array(t('Allowed Combinations'), $ctext);
foreach ($rows as &$row) {
$row[0] = array(
'header' => TRUE,
'data' => $row[0],
);
}
$content['admin_summary'] = array(
'#title' => t('Administrative Summary'),
'#theme' => 'table',
'#rows' => $rows
);
return parent::buildContent($coupon, $view_mode, $langcode, $content);
}
}
/**
* Metadata Controller for uc_coupon entity
*/
class UcCouponMetadataController extends EntityDefaultMetadataController {
public function entityPropertyInfo() {
$prop_info = parent::entityPropertyInfo();
$props = &$prop_info['uc_coupon']['properties'];
//dpm($prop_info);
// Copy the descriptions from the schema. Drupal discards this information, so we have to
// call uc_order_schema() directly.
module_load_include('install', 'uc_coupon', 'uc_coupon');
$schema = uc_coupon_schema();
foreach ($schema['uc_coupons']['fields'] as $name => $info) {
if (is_array($props[$name]) && !empty($info['description'])) {
$props[$name]['description'] = $info['description'];
}
}
$props['type']['options list'] = '_uc_coupon_type_options';
$props['status']['options list']['type'] = 'boolean';
$props['bulk']['type'] = 'boolean';
// Set the correct type for the date properties.
foreach (array('created', 'valid_from', 'valid_until') as $key) {
$props[$key]['type'] = 'date';
$props[$key]['getter callback'] = 'entity_property_verbatim_date_get';
}
// Unpack some of the 'data' properties.
unset($props['data']);
$props['products'] = array(
'type' => 'list<node>',
'label' => t('Products'),
'description' => t('The applicable products for this coupon.'),
'getter callback' => 'uc_coupon_data_property_get',
'setter callback' => 'uc_coupon_data_property_set',
);
$props['negate_products'] = array(
'type' => 'boolean',
'label' => t('Negate applicable products'),
'description' => t('Whether or not the products list represents allowed or disallowed products'),
'getter callback' => 'uc_coupon_data_property_get',
'setter callback' => 'uc_coupon_data_property_set',
);
$props['base_coupon'] = array(
'type' => 'uc_coupon',
'description' => t('The coupon on which a purchased or assigned coupon is based'),
'label' => t('Base coupon'),
'getter callback' => 'uc_coupon_data_property_get',
'setter callback' => 'uc_coupon_data_property_set'
);
return $prop_info;
}
}
/**
* Generic getter to extract properties from the coupon data array.
*/
function uc_coupon_data_property_get($coupon, array $options, $name, $entity_type) {
switch ($name) {
case 'base_coupon':
return empty($coupon->data['base_cid']) ? FALSE : uc_coupon_load($coupon->data['base_cid']);
break;
default:
if (!isset($coupon->data[$name])) {
return NULL;
}
elseif (is_array($coupon->data[$name])) {
return array_values($coupon->data[$name]);
}
else {
return $coupon->data[$name];
}
}
}
/**
* Generic setter to update properties from the coupon data array.
*/
function uc_coupon_data_property_set($coupon, $name, $value) {
switch ($name) {
case 'base_coupon':
$coupon->data[$name] = $value->cid;
break;
default:
if (is_array($value)) {
$coupon->data[$name] = drupal_map_assoc($value);
}
else {
$coupon->data[$name] = $name;
}
}
}
/**
* Options callback for the coupon type property.
*/
function _uc_coupon_type_options() {
return array(
'price' => t('Fixed discount'),
'percentage' => t('Percentage'),
'set_price' => t('Set product price'),
'credit' => t('Store credit')
);
}
/**
* Options callback for the coupon status property
*/
function _uc_coupon_status_options() {
return array(
0 => t('Inactive'),
1 => t('Active'),
);
}

View File

@@ -0,0 +1,32 @@
name = Discount Coupons
description = Discount Coupons and Gift Certificates for Ubercart 3
dependencies[] = uc_cart
dependencies[] = entity
package = Ubercart - payment
core = 7.x
files[] = uc_coupon.entity.inc
files[] = views/uc_coupon_handler_field_actions.inc
files[] = views/uc_coupon_handler_field_bulk_number.inc
files[] = views/uc_coupon_handler_field_codes.inc
files[] = views/uc_coupon_handler_field_product_type.inc
files[] = views/uc_coupon_handler_field_value.inc
files[] = views/uc_coupon_handler_filter_product_type.inc
files[] = views/uc_coupon_handler_argument_product_type.inc
files[] = views/uc_coupon_handler_field_all_orders_count.inc
files[] = views/uc_coupon_handler_field_all_orders_total.inc
files[] = views/uc_coupon_handler_field_all_orders_gross.inc
files[] = views/uc_coupon_handler_field_all_orders_value.inc
files[] = views/uc_coupon_handler_field_gross.inc
files[] = views/uc_coupon_handler_filter_gross.inc
files[] = tests/uc_coupon.test
; Information added by drupal.org packaging script on 2012-12-02
version = "7.x-3.0-alpha0"
core = "7.x"
project = "uc_coupon"
datestamp = "1354467877"

View File

@@ -0,0 +1,172 @@
<?php
/**
* @file
* Ubercart uc_coupon.module schema
*/
/**
* Implements hook_schema().
*/
function uc_coupon_schema() {
$schema = array();
$schema['uc_coupons'] = array(
'description' => 'Ubercart Coupons',
'fields' => array(
'cid' => array(
'type' => 'serial',
'unsigned' => TRUE,
'not null' => TRUE,
),
'name' => array(
'type' => 'varchar',
'length' => 255,
'not null' => TRUE,
'default' => '',
'description' => 'The coupon name',
),
'code' => array(
'type' => 'varchar',
'length' => 100,
'not null' => TRUE,
'default' => '',
'description' => 'The coupon code (or base code for bulk coupons)',
),
'value' => array(
'type' => 'numeric',
'precision' => 10,
'scale' => 2,
'not null' => TRUE,
'default' => 0,
'description' => 'The value of the coupon as currency or percent',
),
'type' => array(
'type' => 'varchar',
'length' => '12',
'not null' => TRUE,
'default' => 'price',
'description' => 'The type of the coupon (price, percent, set_price or store credit)',
),
'status' => array(
'type' => 'int',
'size' => 'tiny',
'not null' => TRUE,
'default' => 1,
'description' => 'Whether or not the coupon is active',
),
'valid_from' => array(
'type' => 'int',
'description' => 'The date from which the coupon is valid',
),
'valid_until' => array(
'type' => 'int',
'description' => 'The date until which the coupon is valid',
),
'max_uses' => array(
'type' => 'int',
'size' => 'small',
'not null' => TRUE,
'default' => 0,
'description' => 'The maximum number of uses allowed for this coupon',
),
'minimum_order' => array(
'type' => 'numeric',
'precision' => 10,
'scale' => 2,
'not null' => TRUE,
'default' => 0,
'description' => 'The minimum order value to which this coupon will apply',
),
'data' => array(
'type' => 'text',
'serialize' => TRUE,
),
'bulk' => array(
'type' => 'int',
'size' => 'tiny',
'not null' => TRUE,
'default' => 0,
'description' => 'Whether or not this is a bulk coupon',
),
'bulk_seed' => array(
'type' => 'char',
'length' => 32,
'not null' => TRUE,
'default' => '',
'description' => 'The unique seed used to genrerate bulk coupon codes',
),
'created' => array(
'type' => 'int',
'not null' => TRUE,
'default' => 0,
'description' => 'The date when this coupon was created',
),
),
'primary key' => array('cid'),
);
$schema['uc_coupons_orders'] = array(
'description' => 'Ubercart Coupons used on Orders',
'fields' => array(
'cuid' => array(
'type' => 'serial',
'unsigned' => TRUE,
'not null' => TRUE,
),
'cid' => array(
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
'default' => 0,
),
'oid' => array(
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
'default' => 0,
),
'value' => array(
'type' => 'numeric',
'precision' => 10,
'scale' => 2,
'not null' => TRUE,
'default' => 0,
),
'code' => array(
'type' => 'varchar',
'length' => 100,
'not null' => TRUE,
'default' => '',
),
),
'primary key' => array('cuid'),
);
return $schema;
}
/**
* Implements hook_uninstall().
*/
function uc_coupon_uninstall() {
variable_del('uc_coupon_collapse_pane');
variable_del('uc_coupon_default_usage');
variable_del('uc_coupon_pane_description');
variable_del('uc_coupon_purchase_order_status');
variable_del('uc_coupon_querystring');
variable_del('uc_coupon_show_in_cart');
variable_del('uc_coupon_line_item_format');
variable_del('uc_coupon_line_item_weight');
variable_del('uc_coupon_form_components');
variable_del('uc_coupon_allow_multiple');
variable_del('uc_coupon_used_order_status');
}
/**
* Implements hook_update_last_removed().
*
*/
function uc_coupon_update_last_removed() {
return 6006;
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,140 @@
<?php
/**
* @file
* Discount Coupons reports pages.
*/
/**
* Coupon report options form.
*/
function uc_coupon_reports_form($form, &$form_state, $start = NULL, $end = NULL, $statuses = NULL) {
module_load_include('inc', 'uc_coupon', 'uc_coupon.admin');
if (is_null($start)) {
$start = REQUEST_TIME;
}
if (is_null($end)) {
$end = REQUEST_TIME;
}
if (is_null($statuses)) {
$statuses = variable_get('uc_reports_reported_statuses', array('completed'));
}
$options = array();
foreach (uc_order_status_list() as $status) {
$options[$status['id']] = $status['title'];
}
$form['start'] = array(
'#type' => 'date',
'#title' => t('Start date'),
'#default_value' => array(
'year' => format_date($start, 'custom', 'Y'),
'month' => format_date($start, 'custom', 'n'),
'day' => format_date($start, 'custom', 'j'),
),
'#after_build' => array('_uc_coupon_date_range'),
);
$form['end'] = array(
'#type' => 'date',
'#title' => t('End date'),
'#default_value' => array(
'year' => format_date($end, 'custom', 'Y'),
'month' => format_date($end, 'custom', 'n'),
'day' => format_date($end, 'custom', 'j'),
),
'#after_build' => array('_uc_coupon_date_range'),
);
$form['status'] = array(
'#type' => 'select',
'#title' => t('Order statuses'),
'#description' => t('Only orders with selected statuses will be included in the report.') . '<br />' . t('Hold Ctrl + click to select multiple statuses.'),
'#options' => $options,
'#default_value' => $statuses,
'#multiple' => TRUE,
'#size' => 5,
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Display report'),
);
return $form;
}
/**
* Submit handler for uc_coupon_reports form.
*/
function uc_coupon_reports_form_submit($form, &$form_state) {
$start = gmmktime(0, 0, 0, $form_state['values']['start']['month'], $form_state['values']['start']['day'], $form_state['values']['start']['year']);
$end = gmmktime(23, 59, 59, $form_state['values']['end']['month'], $form_state['values']['end']['day'], $form_state['values']['end']['year']);
$statuses = implode(',', array_keys($form_state['values']['status']));
$form_state['redirect'] = 'admin/store/reports/coupon/' . $start . '/' . $end . '/' . $statuses;
}
/**
* Output coupon report.
*/
function uc_coupon_reports($start = NULL, $end = NULL, $statuses = NULL) {
drupal_add_css(drupal_get_path('module', 'uc_coupon') . '/reports.css', array('type' => 'uc_coupon'));
if (is_null($statuses)) {
$statuses = variable_get('uc_reports_reported_statuses', array('completed'));
}
else {
$statuses = explode(',', $statuses);
}
$output = drupal_render(drupal_get_form('uc_coupon_reports_form', $start, $end, $statuses));
if (isset($start) && isset($end)) {
$result = db_query("SELECT co.cid, co.oid, co.value, co.code, o.order_total, o.created FROM {uc_coupons_orders} AS co
LEFT JOIN {uc_orders} AS o ON (co.oid = o.order_id)
WHERE o.created > :start AND o.created < :end AND o.order_status IN (:statuses)
ORDER BY co.cid, o.created ASC",
array(':start' => $start, ':end' => $end, ':statuses' => $statuses));
$total = 0;
$row_header = array(t('Order #'), t('Purchase date'), t('Total'), t('Coupon value'));
$last_cid = $orders_total = $coupons_total = 0;
$data = '';
$num_uses = 0;
$coupon_sale_amount = 0;
$coupon_amount = 0;
foreach ($result as $row) {
// Display the table of coupons if this is the next set of coupons
if ($row->cid != $last_cid) {
if ($last_cid != 0) {
$td[] = array('', '<b>' . t('Uses: @total', array('@total' => $num_uses)) . '</b>', '<b>' . uc_currency_format($coupon_sale_amount) . '</b>', '<b>' . uc_currency_format($coupon_amount) . '</b>');
$data .= theme('table', array('header' => $row_header, 'rows' => $td, 'attributes' => array('width' => '100%')));
}
$td = array();
$num_uses = 0;
$coupon_amount = 0;
$coupon_sale_amount = 0;
}
// if this is the first coupon of the set display the header first
if ($row->cid != $last_cid || $last_cid = 0) {
$data .= '<div class="totals">' . t('Coupon code: !link', array('!link' => l($row->code, 'admin/store/coupons/' . $row->cid . '/edit'))) . '</div>';
}
$td[] = array(l('#' . $row->oid, 'admin/store/orders/' . $row->oid), format_date($row->created, 'custom', variable_get('date_format_uc_store', 'm/d/Y')), uc_currency_format($row->order_total), uc_currency_format($row->value));
$num_uses++;
$coupon_amount += $row->value;
$coupon_sale_amount += $row->order_total;
$last_cid = $row->cid;
$orders_total += $row->order_total;
$coupons_total += $row->value;
$total++;
}
$td[] = array('', '<b>' . t('Uses: @total', array('@total' => $num_uses)) . '</b>', '<b>' . uc_currency_format($coupon_sale_amount) . '</b>', '<b>' . uc_currency_format($coupon_amount) . '</b>');
$data .= theme('table', array('header' => $row_header, 'rows' => $td, 'attributes' => array('width' => '100%')));
$output .= '<h2>' . t('Coupon usage report') . '</h2>';
$output .= $data;
$output .= '<br /><table width="100%"><tr>';
$output .= '<td>' . t('Coupons used: @total', array('@total' => $total)) . '</td>';
$output .= '<td>' . t('Orders total: @total', array('@total' => uc_currency_format($orders_total))) . '</td>';
$output .= '<td>' . t('Coupons total: @total', array('@total' => uc_currency_format($coupons_total))) . '</td>';
$output .= '</tr></table>';
}
return $output;
}

View File

@@ -0,0 +1,100 @@
<?php
/**
* @file
* Rules integration for uc_coupon
*/
/**
* Implements hook_rules_data_info().
*/
function uc_coupon_rules_data_info() {
$types['uc_coupon'] = array(
'label' => t('Ubercart discount coupon'),
'wrap' => FALSE,
'group' => t('Ubercart'),
);
}
/**
* Implements hook_rules_condition_info().
*/
function uc_coupon_rules_condition_info() {
$conditions['uc_coupon_condition_order_has_coupon'] = array(
'label' => t('Check if an order has a coupon applied'),
'group' => t('Order'),
'parameter' => array(
'order' => array(
'type' => 'uc_order',
'label' => t('Order'),
'optional' => TRUE,
'default value' => NULL,
'allow null' => TRUE
),
'codes' => array(
'type' => 'list<text>',
'label' => t('Codes'),
'description' => t('Enter coupon codes that this condition will apply to, one per line. Wildcards are allowed, e.g. COUPON* will match all codes beginning with COUPON. Leave blank to apply to any order with a coupon.'),
'restriction' => 'input',
),
),
);
$conditions['uc_coupon_condition_is_bulk'] = array(
'label' => t('Check if a coupon is a bulk coupon'),
'group' => t('Coupon'),
'parameter' => array(
'coupon' => array(
'type' => 'uc_coupon',
'label' => t('Coupon'),
),
),
);
return $conditions;
}
/**
* Check if an order has a coupon applied.
*/
function uc_coupon_condition_order_has_coupon($order, $codes=array()) {
$check_codes = array();
// If the order is in checkout by the current user, use the current session coupons.
if (_uc_coupon_is_checkout_order($order)) {
$coupons = uc_coupon_session_validate();
foreach ($coupons as $coupon) {
$check_codes[$coupon->code] = $coupon->code;
}
}
// Now add any codes alreay in the order object (these take precedence).
elseif (isset($order->data['coupons'])) {
$check_codes = drupal_map_assoc(array_keys($order->data['coupons']));
}
if (count($check_codes) > 0) {
$codes = array_filter($codes);
// If no codes specified, match any coupon.
if (count($codes)==0) {
return TRUE;
}
// Check codes for exact or wildcard matches.
foreach ($codes as $code) {
foreach (array_keys($check_codes) as $check_code) {
if (preg_match('/^' . str_replace('\*', '.*?', preg_quote(strtoupper(trim($code)), '/')) . '$/', $check_code)) {
return TRUE;
}
}
}
}
return FALSE;
}
/**
* Check that a coupon is a bulk coupon.
*/
function uc_coupon_condition_is_bulk($coupon) {
return $coupon->bulk;
}

View File

@@ -0,0 +1,121 @@
<?php
/**
* @file
* Token support for uc_coupon.
*/
/**
* Implements hook_token_info().
*/
function uc_coupon_token_info() {
$types = array(
'uc_coupon' => array(
'name' => t('Coupon'),
'description' => t('Tokens related to Ubercart discount coupons.'),
'needs-data' => 'uc_coupon',
),
);
$tokens = array(
'uc_coupon' => array(
'name' => array(
'name' => t('Name'),
'description' => t('The name of the coupon.'),
),
'code' => array(
'name' => t('Code'),
'description' => t('The coupon code. For bulk coupons this will be the actual code applied, or the code
prefix if the coupon has not yet been applied.'),
),
'codes' => array(
'name' => t('All Codes'),
'description' => t('The coupon codes. For bulk coupons, this will be a comma separated list of codes.'),
),
'value' => array(
'name' => t('Value'),
'description' => t('The value of the coupon. If the coupon has already been applied to an order, this will be
the actual currency value of the coupon. Otherwise, it will be the nominal discount.'),
),
'credit' => array(
'name' => t('Remaining credit'),
'description' => t('For store credit/gift certificate type coupons which have been applied to an order, the unused credit remaining.'),
),
),
'uc_order' => array(
'coupon-code' => array(
'name' => t('Coupon Code'),
'description' => t('The coupon code used in the order.'),
),
),
);
return array('types' => $types, 'tokens' => $tokens);
}
/**
* Implements hook_tokens().
*/
function uc_coupon_tokens($type, $tokens, $data = array(), $options = array()) {
$sanitize = !empty($options['sanitize']);
$values = array();
switch ($type) {
case 'uc_order':
if (array_key_exists('coupon-code', $tokens) && !empty($data['uc_order']) && isset($data['uc_order']->data['coupon'])) {
$values[$tokens['coupon-code']] = $sanitize ? check_plain($data['uc_order']->data['coupon']) : $data['uc_order']->data['coupon'];
}
break;
case 'uc_coupon':
if (!empty($data['uc_coupon'])) {
$coupon = $data['uc_coupon'];
if (array_key_exists('name', $tokens)) {
$values[$tokens['name']] = $sanitize ? check_plain($coupon->name) : $coupon->name;
}
if (array_key_exists('code', $tokens)) {
$values[$tokens['code']] = $sanitize ? check_plain($coupon->code) : $coupon->code;
}
if (array_key_exists('codes', $tokens)) {
$codes = array();
if ($coupon->bulk) {
for ($id = 0; $id < $coupon->data['bulk_number']; $id++) {
$codes[] = uc_coupon_get_bulk_code($coupon, $id);
}
}
else {
$codes[] = $coupon->code;
}
$values[$tokens['codes']] = implode("\n", $sanitize ? array_walk($codes, 'check_plain') : $codes);
}
if (array_key_exists('value', $tokens)) {
$values[$tokens['value']] = isset($coupon->amount) ?
theme('uc_price', array('price' => $coupon->amount)) : theme('uc_coupon_discount', array('coupon' => $coupon));
}
if (array_key_exists('credit', $tokens)) {
if ($coupon->type !== 'credit') {
if ($coupon->bulk && !$coupon->valid) {
$values[$tokens['credit']] = t('n/a');
}
else {
$amt = $coupon->value;
$usage = isset($coupon->usage) ? $coupon->usage : uc_coupon_count_usage($coupon->cid);
if (isset($usage['value'][$coupon->code])) {
$amt -= $usage['value'][$coupon->code];
}
if (isset($coupon->amount)) {
$amt -= $coupon->amount;
}
$values[$tokens['credit']] = uc_currency_format($amt);
}
}
else {
$values[$tokens['credit']] = t('n/a');
}
}
}
break;
}
return $values;
}

View File

@@ -0,0 +1,20 @@
name = Discount Coupon Purchase
description = Allows coupons to be purchased as a product feature.
dependencies[] = uc_coupon
dependencies[] = uc_coupon_workflow
package = Ubercart - payment
core = 7.x
files[] = uc_coupon_purchase.ca.inc
files[] = uc_coupon_purchase.install
files[] = uc_coupon_purchase.module
files[] = uc_coupon_purchase.pages.inc
files[] = views/uc_coupon_purchase.views.inc
files[] = views/uc_coupon_purchase_handler_field_base_name.inc
; Information added by drupal.org packaging script on 2012-12-02
version = "7.x-3.0-alpha0"
core = "7.x"
project = "uc_coupon"
datestamp = "1354467877"

View File

@@ -0,0 +1,92 @@
<?php
/**
* @file
* Install, update and uninstall functions for the uc_coupon_purchase module.
*
*/
/**
* Implements hook_schema()
*/
function uc_coupon_purchase_schema() {
$schema = array();
$schema['uc_coupon_purchase'] = array(
'description' => 'Ubercart Purchased Coupons',
'fields' => array(
'pfid' => array(
'description' => 'The product feature id.',
'type' => 'serial',
'unsigned' => TRUE,
'not null' => TRUE,
),
'nid' => array(
'description' => 'The identifier of the node that has a feature.',
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
'default' => 0,
),
'model' => array(
'description' => 'The SKU of the product that has a feature.',
'type' => 'varchar',
'length' => 30,
'not null' => TRUE,
'default' => '',
),
'base_cid' => array(
'description' => 'The base coupon ID to use when purchasing this feature.',
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
'default' => 0,
),
),
'indexes' => array(
'nid' => array('nid'),
'model' => array('model'),
),
'primary key' => array('pfid'),
);
$schema['uc_coupon_purchase_users'] = array(
'description' => 'Ubercart Purchased Coupons Per Purchaser',
'fields' => array(
'cpuid' => array(
'type' => 'serial',
'unsigned' => TRUE,
'not null' => TRUE,
),
'uid' => array(
'description' => 'The user id.',
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
),
'cid' => array(
'description' => 'The coupon id.',
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
),
),
'primary key' => array('cpuid'),
);
return $schema;
}
/**
* Implements hook_uninstall().
*/
function uc_coupon_purchase_uninstall() {
variable_del('uc_coupon_purchase_order_status');
}
/**
* Implements hook_update_last_removed().
*/
function uc_coupon_purchase_update_last_removed() {
return 6000;
}

View File

@@ -0,0 +1,605 @@
<?php
define('UC_COUPON_PURCHASE_RECIPIENT_ATTRIBUTE', 'uc_coupon_purchase_recipient');
/**
* Implements hook_permission().
*/
function uc_coupon_purchase_permission() {
return array(
'view purchased coupons' => array(
'title' => t('view purchased coupons'),
'description' => t('View list of the coupons a user has purchased.'),
),
);
}
/**
* Implements hook_menu().
*/
function uc_coupon_purchase_menu() {
$items = array();
$items['user/%user/coupons'] = array(
'title' => 'Coupons & Credits',
'description' => 'View your discount coupons and credits.',
'page callback' => 'uc_coupon_purchase_view',
'access callback' => 'uc_coupon_purchase_can_view',
'page arguments' => array(1),
'access arguments' => array(1),
'type' => MENU_LOCAL_TASK,
'file' => 'uc_coupon_purchase.pages.inc',
'weight' => 5,
);
$items['user/%user/coupons/%uc_coupon'] = array(
'title' => 'Print preview',
'page callback' => 'uc_coupon_purchase_print',
'access callback' => 'uc_coupon_purchase_can_view',
'page arguments' => array(1, 3),
'access arguments' => array(1, 3),
'type' => MENU_LOCAL_TASK,
'file' => 'uc_coupon_purchase.pages.inc',
'weight' => 5,
);
$items['user/%user/coupons/%uc_coupon/codes'] = array(
'title' => 'Download codes',
'page callback' => 'uc_coupon_codes_csv',
'access callback' => 'uc_coupon_purchase_can_view',
'page arguments' => array(3),
'access arguments' => array(1, 3),
'type' => MENU_CALLBACK,
'file' => 'uc_coupon.admin.inc',
'file path' => drupal_get_path('module', 'uc_coupon'),
'weight' => 5,
);
return $items;
}
/**
* Access callback for user/%/coupons.
*
* User must have "view purchased coupons" permission, current user must have a
* coupon to view, other users must have "administer users" permission.
*
* If a coupon is specified, user must have purchased that coupon.
*/
function uc_coupon_purchase_can_view($account, $coupon = NULL) {
global $user;
if (user_access('view purchased coupons')) {
if (user_access('administer users') || ($account->uid == $user->uid && uc_coupon_purchase_has_coupon($account, $coupon))) {
return TRUE;
}
}
return FALSE;
}
/**
* Implementation of hook_uc_coupon_actions for purchased coupons
*/
function uc_coupon_purchase_uc_coupon_actions($coupon) {
$actions = array();
if (!user_access('manage store coupons')) {
global $user;
$account = (arg(0) == 'user') ? user_load(arg(1)) : $user;
if (uc_coupon_purchase_can_view($account, $coupon)) {
$actions[] = array(
'url' => "user/$account->uid/coupons/$coupon->cid/view",
'icon' => drupal_get_path('module', 'uc_store') . '/images/order_view.gif',
'title' => t('View coupon: @name', array('@name' => $coupon->name)),
);
$actions[] = array(
'url' => "user/$account->uid/coupons/$coupon->cid/print",
'icon' => drupal_get_path('module', 'uc_store') . '/images/print.gif',
'title' => t('Print coupon: @name', array('@name' => $coupon->name)),
);
if ($coupon->bulk) {
$actions[] = array(
'url' => 'admin/store/coupons/' . $coupon->cid . '/codes',
'icon' => drupal_get_path('module', 'uc_store') . '/images/menu_reports_small.gif',
'title' => t('Download codes as CSV: @name', array('@name' => $coupon->name)),
);
}
}
}
return $actions;
}
/**
* Check whether a given user has purchased any coupon, or the specific supplied coupon.
*/
function uc_coupon_purchase_has_coupon($account, $coupon = NULL) {
$query = db_select('uc_coupon_purchase_users', 'u')->condition('u.uid', $account->uid);
$query->addExpression('COUNT(*)');
// Make sure coupon is valid before looking for it.
if (!empty($coupon) && !empty($coupon->cid)) {
$query->condition('u.cid', $coupon->cid, 'AND');
}
return $query->execute()->fetchField();
}
/**
* Implements hook_uc_product_feature().
*/
function uc_coupon_purchase_uc_product_feature() {
$features[] = array(
'id' => 'coupon',
'title' => t('Coupon creation'),
'callback' => 'uc_coupon_purchase_feature_form',
'delete' => 'uc_coupon_purchase_feature_delete',
'settings' => 'uc_coupon_purchase_feature_settings',
);
return $features;
}
/**
* Form builder for hook_uc_product_feature().
*/
function uc_coupon_purchase_feature_form($form, $form_state, $node, $feature) {
$models = array(
NULL => t('Any'),
$node->model => $node->model,
);
if (module_exists('uc_attribute')) {
$adjustments = db_query("SELECT model FROM {uc_product_adjustments} WHERE nid = :nid", array(':nid' => $node->nid));
foreach ($adjustments as $adjustment) {
if (!in_array($adjustment->model, $models)) {
$models[$adjustment->model] = $adjustment->model;
}
}
}
if (!empty($feature)) {
$data = db_query("SELECT * FROM {uc_coupon_purchase} WHERE pfid = :pfid", array(':pfid' => $feature['pfid']))->fetchObject();
$form['pfid'] = array(
'#type' => 'value',
'#value' => $feature['pfid'],
);
if (!$data) {
$data = new stdClass();
}
}
else {
$data = new stdClass();
}
$coupons = array();
$result = db_query("SELECT cid, name, code FROM {uc_coupons} WHERE status = :status", array(':status' => 0));
foreach ($result as $coupon) {
$coupons[$coupon->cid] = $coupon->name . ' (' . $coupon->code . ')';
}
if (!$coupons) {
drupal_set_message(t('No inactive coupons found. Please <a href="!url">create an inactive coupon</a> to use as a base coupon for purchases.', array('!url' => url('admin/store/coupons/add'))), 'error');
drupal_goto('node/' . arg(1) . '/edit/features');
}
$form['title'] = array(
'#type' => 'markup',
'#markup' => '<h2>' . t('Coupon creation') . '</h2>',
);
$form['nid'] = array(
'#type' => 'value',
'#value' => $node->nid,
);
$form['model'] = array(
'#type' => 'select',
'#title' => t('Model/SKU'),
'#default_value' => isset($data->model) ? $data->model : NULL,
'#description' => t('Select the model/SKU of the product that cause a coupon to be created.'),
'#options' => $models,
);
$form['base_cid'] = array(
'#type' => 'select',
'#title' => t('Base coupon'),
'#default_value' => isset($data->base_cid) ? $data->base_cid : reset(array_keys($coupons)),
'#description' => t('Select the coupon that will be cloned when a user purchases this product. Only inactive coupons are listed; the purchased coupon will automatically be activated.'),
'#options' => $coupons,
);
return uc_product_feature_form($form, $form_state, $node, $feature);
}
/**
* Submit handler for uc_coupon_purchase_feature form.
*/
function uc_coupon_purchase_feature_form_submit($form, &$form_state) {
$coupon = uc_coupon_load($form_state['values']['base_cid']);
$description = (empty($form_state['values']['model'])) ? t('<strong>SKU:</strong> Any<br/>') : t('<strong>SKU:</strong> !sku<br/>', array('!sku' => $form_state['values']['model']));
$description .= t('<strong>Base coupon:</strong> !coupon<br/>', array('!coupon' => $coupon->name . ' (' . $coupon->code . ')'));
$data = array(
'pfid' => !empty($form_state['values']['pfid']) ? $form_state['values']['pfid'] : 0,
'nid' => $form_state['values']['nid'],
'fid' => 'coupon',
'description' => $description,
);
$form_state['redirect'] = uc_product_feature_save($data);
if (!empty($form_state['values']['pfid'])) {
db_delete('uc_coupon_purchase')
->condition('pfid', $form_state['values']['pfid'])
->execute();
}
$id = db_insert('uc_coupon_purchase')
->fields(array(
'pfid' => $data['pfid'],
'nid' => $form_state['values']['nid'],
'model' => $form_state['values']['model'],
'base_cid' => $form_state['values']['base_cid'],
))
->execute();
}
/**
* Delete callback for product feature.
*/
function uc_coupon_purchase_feature_delete($pfid) {
db_delete('uc_coupon_purchase')
->condition('pfid', $pfid)
->execute();
}
/**
* Form builder for feature settings.
*/
function uc_coupon_purchase_feature_settings() {
foreach (uc_order_status_list('general') as $status) {
$statuses[$status['id']] = $status['title'];
}
$form['uc_coupon_purchase_order_status'] = array(
'#type' => 'select',
'#title' => t('Order status'),
'#default_value' => variable_get('uc_coupon_purchase_order_status', 'completed'),
'#description' => t('Select the order status that will cause the coupon to be created. Be aware that if payments are processed automatically, this happens before anonymous customers have an account created. This order status should not be reached before the user account exists.'),
'#options' => $statuses,
);
return $form;
}
/**
* Implements hook_form_FORM_ID_alter() for uc_coupon_add_form().
*
* Modify the coupon add form to include coupon purchase options.
*/
function uc_coupon_purchase_form_uc_coupon_add_form_alter(&$form) {
$value = isset($form['#uc_coupon']) ? $form['#uc_coupon'] : new stdClass();
$form['uc_coupon_purchase'] = array(
'#type' => 'fieldset',
'#title' => t('Coupon purchase options'),
'#description' => t('These settings alter the generation of purchased coupons based on this coupon.'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
'#weight' => -1,
);
$form['uc_coupon_purchase']['purchase_suffix_length'] = array(
'#type' => 'select',
'#title' => t('Purchased coupon code suffix length'),
'#default_value' => isset($value->data['purchase_suffix_length']) ? $value->data['purchase_suffix_length'] : 12,
'#description' => t('A random string of at least this many characters will be appended to the base coupon code to ensure uniqueness.'),
'#options' => drupal_map_assoc(range(4, 30)),
);
$form['uc_coupon_purchase']['purchase_relative'] = array(
'#type' => 'checkbox',
'#title' => t('Alter coupon date restrictions relative to the purchase date.'),
'#description' => t('Checking this box will make purchased coupons valid for the same time span as the base coupon, otherwise coupons will always be valid between the same dates.'),
'#default_value' => isset($value->data['purchase_relative']) ? $value->data['purchase_relative'] : FALSE,
);
$form['status']['#description'] .= '<br />' . t('Only inactive coupons can be selected as the base for a purchased coupon, subsequent purchased coupons will automatically be activated.');
$form['#validate'][] = 'uc_coupon_purchase_uc_coupon_add_form_validate';
$form['#entity_builders'][] = 'uc_coupon_purchase_build_coupon';
}
/**
* Extra validation for uc_coupon_add_form.
*/
function uc_coupon_purchase_uc_coupon_add_form_validate($form, &$form_state) {
if ($form_state['values']['purchase_relative'] && !$form_state['values']['use_validity']) {
form_set_error('purchase_relative', t('You must specify date restrictions to use the relative date feature with purchased coupons.'));
}
}
/**
* Entity builder callback for the uc_coupon edit form.
*/
function uc_coupon_purchase_build_coupon($type, $coupon, $form, $form_state) {
if ($type == 'uc_coupon') {
$edit = $form_state['values'];
if (isset($edit['purchase_suffix_length'])) {
$coupon->data['purchase_suffix_length'] = $edit['purchase_suffix_length'];
}
if (isset($edit['purchase_relative']) && $edit['purchase_relative']) {
$coupon->data['purchase_relative'] = TRUE;
}
}
}
/**
* Implements hook_uc_coupon_delete().
*/
function uc_coupon_purchase_uc_coupon_delete($coupon) {
db_delete('uc_coupon_purchase_users')
->condition('cid', $coupon->cid)
->execute();
}
/**
* Implements hook_uc_order().
*/
function uc_coupon_purchase_uc_order($op, $order, $status) {
switch ($op) {
case 'update':
if ($status == variable_get('uc_coupon_purchase_order_status', 'completed') &&
$order->order_status != $status &&
$order->uid > 0 &&
($order_user = user_load($order->uid)) !== FALSE) {
foreach ($order->products as $product) {
$result = db_query("SELECT * FROM {uc_coupon_purchase} WHERE nid = :nid", array(':nid' => $product->nid));
foreach ($result as $row) {
if ($row->model == $product->model || empty($row->model)) {
$coupon = uc_coupon_load($row->base_cid);
// Append purchaser data to the coupon name.
$purchaser = trim(!empty($order->billing_company) ? $order->billing_company : ($order->billing_first_name . ' ' . $order->billing_last_name));
if (empty($purchaser)) {
$purchaser = "Anonymous";
}
$coupon->name .= ' ' . t('purchased by !name', array('!name' => $purchaser));
$coupon->data['order_id'] = $order->order_id;
// Create new coupon and link to purchaser.
$new_coupon = uc_coupon_purchase_create($coupon, $product->qty, $order->uid);
uc_order_comment_save($order->order_id, 0, t('Coupon created with code %code.', array('%code' => $new_coupon->code)));
// Fire hook and conditional actions to send emails for this coupon purchase.
module_invoke_all('uc_coupon_purchase', $order, $new_coupon, $product);
rules_invoke_event('uc_coupon_purchase', $order, $new_coupon, $product);
}
}
}
}
break;
}
}
/**
* Create newly purchased coupons, based on the supplied coupon object.
*/
function uc_coupon_purchase_create($coupon, $qty, $uid = NULL) {
$suffix_length = isset($coupon->data['purchase_suffix_length']) ? $coupon->data['purchase_suffix_length'] : 12;
// If more than one coupon will be generated, ensure it is a bulk coupon.
if ($qty > 1 || $coupon->bulk) {
$coupon->bulk = TRUE;
if (!isset($coupon->data['bulk_number'])) {
$coupon->data['bulk_number'] = 1;
}
$coupon->data['bulk_number'] *= $qty;
if (!isset($coupon->data['bulk_length'])) {
$coupon->data['bulk_length'] = 8;
}
// Adjust the suffix so single and bulk coupons are the same length where possible.
$suffix_length = max($suffix_length - $coupon->data['bulk_length'], 4);
}
// Adjust the validity dates.
if (isset($coupon->data['purchase_relative'])) {
$diff = $coupon->valid_until - $coupon->valid_from;
$coupon->valid_from = gmmktime();
$coupon->valid_until = $coupon->valid_from + $diff;
}
// Create a new, active coupon with the suffix applied.
$coupon->data['base_cid'] = $coupon->cid;
unset($coupon->cid);
$coupon->code .= strtoupper(user_password($suffix_length));
$coupon->status = TRUE;
uc_coupon_save($coupon);
// Associate this coupon with its owner.
if (!is_null($uid)) {
$record = array('uid' => $uid, 'cid' => $coupon->cid);
drupal_write_record('uc_coupon_purchase_users', $record);
}
return $coupon;
}
/**
* Implements hook_views_api().
*/
function uc_coupon_purchase_views_api() {
return array(
'api' => '2.0',
'path' => drupal_get_path('module', 'uc_coupon_purchase') . '/views',
);
}
/**
* Helper function to create the product attribute specifying gift certificate
* recipients. Will only create the attribute if it does not already exist.
*
* @return
* The recipient attribute.
*/
function _uc_coupon_purchase_create_recipient_attribute() {
if (!$attribute = _uc_coupon_purchase_load_recipient_attribute()) {
$attribute = array(
'name' => UC_COUPON_PURCHASE_RECIPIENT_ATTRIBUTE,
'label' => t('Gift Certificate Recipient'),
'description' => t('The e-mail address of the recipient of this gift certificate'),
'required' => FALSE,
'display' => 0,
'ordering' => 0,
);
$attribute = (object) $attribute;
uc_attribute_save($attribute);
// Flush the cache.
$attribute = _uc_coupon_purchase_load_recipient_attribute(TRUE);
}
return $attribute;
}
/**
* Helper function to load the attribute which we use for gift certificate recipients.
*
* @reset
* TRUE to flush the cache.
* @return
* The loaded attribute object, or FALSE if not found.
*/
function _uc_coupon_purchase_load_recipient_attribute($reset = FALSE) {
static $attribute = NULL;
if (!module_exists('uc_attribute')) {
return FALSE;
}
elseif (is_null($attribute) || $reset) {
$aid = db_query('SELECT aid FROM {uc_attributes} WHERE name = :name', array(':name' => UC_COUPON_PURCHASE_RECIPIENT_ATTRIBUTE))->fetchField(0);
$attribute = $aid ? uc_attribute_load($aid) : FALSE;
}
return $attribute;
}
/**
* Implements hook_form_FORM_ID_alter() for uc_attribute_form.
*/
function uc_coupon_purchase_form_uc_attribute_form_alter(&$form, &$form_state) {
// If our reserved attribute is being edited, prevent the name from being changed.
if (!empty($form['aid']['#value'])
&& ($attribute = uc_attribute_load($form['aid']['#value']))
&& $attribute->name === UC_COUPON_PURCHASE_RECIPIENT_ATTRIBUTE) {
$form['name']['#disabled'] = TRUE;
$form['name']['#description'] .= ' ' . t('This attribute is used by uc_coupon_purchase to send additional notifications to purchased coupon recipients. The name cannot be altered.');
}
$form['#validate'][] = 'uc_coupon_purchase_attribute_form_validate';
}
/**
* Extra validation callback for uc_attribute_form.
*/
function uc_coupon_purchase_attribute_form_validate($form, $form_state) {
// For a new attribute, prevent use of the reserved name.
if (empty($form['aid']) && $form_state['values']['name'] === UC_COUPON_PURCHASE_RECIPIENT_ATTRIBUTE) {
form_set_error('name', t('The name is reserved for use by uc_coupon_purchase.'));
}
}
/**
* Implements hook_form_FORM_ID_alter() for uc_prodcut_add_to_cart_form.
*/
function uc_coupon_purchase_form_uc_product_add_to_cart_form_alter(&$form, &$form_state) {
$form['#validate'][] = 'uc_coupon_purchase_add_to_cart_form_validate';
}
/**
* Extra validation callback for uc_product_add_to_cart_form.
*/
function uc_coupon_purchase_add_to_cart_form_validate($form, $form_state) {
// Ensure that the recipient (if specified) is a valid e-mail address.
$attribute = _uc_coupon_purchase_load_recipient_attribute();
if ($attribute && !empty($form['attributes'][$attribute->aid])) {
$email = trim($form_state['values']['attributes'][$attribute->aid]);
if (!empty($email) && !valid_email_address($email)) {
form_set_error("attributes][{$attribute->aid}", t('You must specify a valid e-mail address.'));
}
}
}
/**
* Implements hook_form_FORM_ID_alter() for uc_coupon_settings_form.
*/
function uc_coupon_purchase_form_uc_coupon_settings_form_alter(&$form, &$form_state) {
$form['uc_coupon_purchase'] = array(
'#type' => 'fieldset',
'#title' => t('Coupon purchase settings'),
);
$form['uc_coupon_purchase']['uc_coupon_purchase_recipient'] = array(
'#type' => 'item',
'#title' => t('Gift coupon recipient field'),
'uc_coupon_purchase_recipient_enabled' => array(
'#type' => 'checkbox',
'#title' => t('Enable the "uc_coupon_purchase_recipient" product attribute.'),
'#description' => t('When checked, a "uc_coupon_purchase_recipient" product attribute wil be created.
When you attach this attribute to a product with the "create coupon" feature, customers will be able
to enter the e-mail address of a recipient. You can then configure a rule to send a customized
e-mail notification to the recipient.'),
'#default_value' => variable_get('uc_coupon_purchase_recipient_enabled', FALSE),
'#access' => module_exists('uc_attribute'),
),
'#description' => module_exists('uc_attribute') ? NULL : t('You must enable the uc_attribute module to activate this feature.'),
);
$form['#submit'][] = 'uc_coupon_purchase_coupon_settings_form_submit';
}
/**
* Submit handler for uc_coupon_settings_form.
*/
function uc_coupon_purchase_coupon_settings_form_submit($form, $form_state) {
// Create the recipient attribute.
if (!empty($form_state['values']['uc_coupon_purchase_recipient_enabled'])) {
if (module_exists('uc_attribute')) {
if (!$attribute = _uc_coupon_purchase_load_recipient_attribute()) {
$attribute = _uc_coupon_purchase_create_recipient_attribute();
drupal_set_message(t('The "@name" attribute has been created', array('@name' => $attribute->name)));
}
}
}
}
// ****** NOTE THE FOLLOWING CAN HOPEFULLY BE REMOVED ONCE THIS FUNCTIONALITY
// IS INCLUDED IN UBERCART CORE. See http://drupal.org/node/1632540.
function uc_coupon_purchase_entity_property_info_alter(&$info) {
$r = db_query('SELECT name, label from {uc_attributes}');
foreach ($r as $row) {
$entry = array(
'type' => 'text',
'label' => $row->name, // Use the name, because the label can differ among products.
'description' => $row->label,
'getter callback' => 'uc_coupon_purchase_attribute_property_getter',
);
foreach (array('uc_order_product', 'uc_cart_item') as $type) {
if (isset($info[$type]) && !isset($info[$type]['properties'][$row->name])) {
$info[$type]['properties'][$row->name] = $entry;
}
}
}
}
function uc_coupon_purchase_attribute_property_getter($product, $options, $name, $type, $info) {
if (!empty($product->data['attributes'])) {
if ($type == 'uc_cart_item') {
$product = clone $product;
uc_attribute_uc_order_product_alter($product, NULL);
}
$attributes = uc_attribute_load_product_attributes($product->nid);
$key = FALSE;
foreach ($attributes as $aid => $attribute) {
if ($attribute->name == $name) {
$key = $attribute->label;
break;
}
}
return ($key && !empty($product->data['attributes'][$key])) ? implode(',', $product->data['attributes'][$key]) : NULL;
}
}

View File

@@ -0,0 +1,98 @@
<?php
/**
* @file
* Page callbacks for uc_coupon.
*/
/**
* Display a list of purchased coupons.
*/
function uc_coupon_purchase_view($account) {
drupal_set_title(t('My coupons and credits'));
$result = db_query('SELECT c.* FROM {uc_coupon_purchase_users} u INNER JOIN {uc_coupons} c ON u.cid = c.cid WHERE u.uid = :uid ORDER BY valid_until ASC, code ASC', array(':uid' => $account->uid));
$header = array(t('Code'), t('Value'), t('Validity'), t('Used'), t('Remaining'));
$rows = array();
foreach ($result as $coupon) {
if ($coupon->bulk) {
$coupon->data = unserialize($coupon->data);
$codes = array();
for ($id = 0; $id < $coupon->data['bulk_number']; $id++) {
$codes[] = uc_coupon_get_bulk_code($coupon, $id);
}
}
else {
$codes = array($coupon->code);
}
$value = theme('uc_coupon_discount', array('coupon' => $coupon));
if (!$coupon->status) {
$valid = t('Inactive');
}
elseif (!$coupon->valid_until) {
$valid = t('Unlimited');
}
else {
$valid_from = format_date($coupon->valid_from, 'custom', variable_get('date_format_uc_store', 'm/d/Y'));
$valid_until = format_date($coupon->valid_until, 'custom', variable_get('date_format_uc_store', 'm/d/Y'));
$valid = $valid_from . ' - ' . $valid_until;
}
$usage = uc_coupon_count_usage($coupon->cid);
$icon = theme('image', array('path' => drupal_get_path('module', 'uc_store') . '/images/print.gif', 'width' => t('Print')));
foreach ($codes as $code) {
if (substr($code, -1) == '*') {
// For the base code of bulk coupons, just give a link to print all.
$title = t('All %code', array('%code' => $code));
$link = l($title, 'user/' . $account->uid . '/coupons/' . $coupon->cid);
$link .= ' ' . l($icon, 'user/' . $account->uid . '/coupons/' . $coupon->cid . '/print', array('html' => TRUE));
$rows[] = array($link, '', '', '', '');
}
else {
$link = l($code, 'user/' . $account->uid . '/coupons/' . $coupon->cid . '/view/' . $code);
$link .= ' ' . l($icon, 'user/' . $account->uid . '/coupons/' . $coupon->cid . '/print/' . $code, array('html' => TRUE));
if ($coupon->type === 'credit') {
$used = empty($usage['value']['codes'][$code]) ? 0 : $usage['value']['codes'][$code];
$remaining = uc_currency_format($coupon->value - $used);
$used = uc_currency_format($used);
}
else {
$used = empty($usage['codes'][$code]) ? 0 : $usage['codes'][$code];
$remaining = $coupon->max_uses > 0 ? $coupon->max_uses - $used : t('Unlimited');
}
$rows[] = array($link, $value, $valid, $used, $remaining);
}
}
}
if (count($rows)) {
$output = "<p>" . t("The table below lists the discount coupons and credits available to you.") . "</p>";
$output .= theme('table', array('header' => $header, 'rows' => $rows));
}
else {
$output = "<p>" . t('You currently have no coupons or credits available.') . "</p>";
}
return $output;
}
/**
* Print a purchased coupon.
*/
function uc_coupon_purchase_print($account, $coupon, $op = 'view', $code = NULL) {
drupal_set_title(t('Coupon #@cid', array('@cid' => $coupon->cid)), PASS_THROUGH);
module_load_include('inc', 'uc_coupon', 'uc_coupon.admin');
$url = 'user/' . $account->uid . '/coupons/' . $coupon->cid . '/print' . ($code ? "/$code" : '');
$output = '<p>' . l($coupon->bulk && !$code ? t('Print coupons') : t('Print coupon'), $url) . '</p>';
// Add the owner account object to the coupon.
$coupon->owner = $account;
// Does not return if op = 'print'
$output .= uc_coupon_print($coupon, $code, $op);
return $output;
}

View File

@@ -0,0 +1,285 @@
<?php
/**
* @file
* Rules integration for uc_coupon_purchase
*/
/**
* Implements hook_rules_event_info().
*/
function uc_coupon_purchase_rules_event_info() {
$events = array();
$events['uc_coupon_purchase'] = array(
'label' => t('Customer purchases a coupon'),
'group' => t('Coupon'),
'variables' => array(
'order' => array(
'type' => 'uc_order',
'label' => t('Order'),
),
'coupon' => array(
'type' => 'uc_coupon',
'label' => t('Coupon'),
),
'product' => array(
'type' => 'uc_order_product',
'label' => t('The purchased product of which the coupon is a feature.'),
),
),
);
return $events;
}
/**
* Implements hook_rules_action_info().
*/
function uc_coupon_purchase_rules_action_info() {
$actions = array();
$actions['uc_coupon_purchase_email'] = array(
'label' => t('Send an order email regarding coupon purchase.'),
'group' => t('Coupon'),
'parameter' => array(
'order' => array(
'type' => 'uc_order',
'label' => t('Order'),
'optional' => TRUE,
),
'coupon' => array(
'type' => 'uc_coupon',
'label' => t('Coupon'),
),
'from' => array(
'type' => 'text',
'label' => t('Sender'),
),
'addresses' => array(
'type' => 'text',
'label' => t('Recipients'),
'description' => t('Enter the email addresses to receive the notifications, one on each line. You may use order tokens for dynamic email addresses.'),
),
'subject' => array(
'type' => 'text',
'label' => t('Subject'),
),
'message' => array(
'type' => 'text',
'label' => t('Message'),
),
'format' => array(
'type' => 'text',
'label' => t('Message format'),
'options list' => 'uc_coupon_purchase_message_formats',
),
),
);
$actions['uc_coupon_purchase_assign_action'] = array(
'label' => t('Assign a coupon to a user'),
'group' => t('Coupon'),
'provides' => array(
'coupon' => array(
'type' => 'uc_coupon',
'label' => t('Coupon'),
),
),
'named parameter' => TRUE,
'parameter' => array(
'cid' => array(
'type' => 'integer',
'label' => t('Coupon'),
'description' => t('Select the base coupon to be assigned.'),
'options list' => 'uc_coupon_purchase_cid_options',
),
'account' => array(
'type' => 'user',
'label' => t('Account'),
'description' => t('Select the user to whom the coupon should be assigned.'),
),
'restrict' => array(
'type' => 'boolean',
'label' => t('Restrict coupon usage to assigned users.'),
'description' => t('When selected, the assignee will be added to the list of authorized
users for this coupon. Only authorized users will be able to use the coupon.'),
'default value' => FALSE,
'allow null' => TRUE,
'restriction' => 'input',
'optional' => TRUE,
),
'sole' => array(
'type' => 'boolean',
'label' => t('Make this user the sole owner.'),
'description' => t('When selected, all other assigned users will be removed.
If you check "%r" above, this user will become the only person authorized to use this coupon.', array(
'%r' => t('Restrict coupon usage to assigned users.')
)),
'default value' => FALSE,
'allow null' => TRUE,
'restriction' => 'input',
'optional' => TRUE,
),
'clone' => array(
'type' => 'boolean',
'label' => t('Clone the base coupon before assigning.'),
'description' => t('When checked, the base coupon will be cloned and a copy assigned to the specified user,
exactly as if the user had purchased the coupon. If unchecked, the base coupon will be assigned to the
user directly'),
'default value' => FALSE,
'allow null' => TRUE,
'restriction' => 'input',
'optional' => TRUE,
),
'quantity' => array(
'type' => 'integer',
'label' => t('Quantity.'),
'description' => t('The number of copies of the base coupon to assign. If the base coupon is a bulk coupon,
this will be multiplied by the base coupon\'s bulk number. Only meaningful if you select "%c" above.', array(
'%c' => t('Clone the base coupon before assigning.'),
)),
'default value' => 1,
'allow null' => TRUE,
'restriction' => 'input',
'optional' => TRUE,
),
),
);
return $actions;
}
/**
* Rules form_alter callback for the uc_coupon_purchase_assign_action.
*/
function uc_coupon_purchase_assign_action_form_alter(&$form, &$form_state) {
if (isset($form['parameter']['cid']['settings']['cid'])) {
// Add a set of radio buttons to limit the choice of coupons by status.
$form['parameter']['cid']['settings']['cid']['#prefix'] = '<div id="uc-coupon-purchase-assign-cid">';
$form['parameter']['cid']['settings']['cid']['#suffix'] = '</div>';
//$cid_type = empty($form_state['values']['parameter']['cid']['settings']['cid_type']) ?
// 0 : $form_state['values']['parameter']['cid']['settings']['cid_type'];
//$form['parameter']['cid']['settings']['cid']['#options'] = uc_coupon_purchase_cid_options($cid_type);
$form['parameter']['cid']['settings']['cid_type'] = array(
'#type' => 'radios',
'#title' => t('Choose from'),
'#options' => array(
0 => t('All coupons'),
1 => t('Inactive coupons'),
2 => t('Active coupons'),
),
'#default_value' => 0,
'#ajax' => array(
'callback' => 'uc_coupon_purchase_assign_action_form_ajax',
'wrapper' => 'uc-coupon-purchase-assign-cid',
),
);
}
elseif (isset($form['parameter']['cid']['settings']['cid:select'])) {
$form['parameter']['cid']['#description'] = t('Select the base coupon to be assigned. Note, you must choose the
ID of the coupon (i.e. "%selector")', array('%selector' => 'coupon:cid'));
}
// Hide the "quantity" ofield when not applicable.
$form['parameter']['quantity']['#states'] = array(
'invisible' => array(
'input[name="parameter[clone][settings][clone]"]' => array('checked' => FALSE),
)
);
}
/**
* Ajax callback for the uc_coupon_purchase_assign action.
*/
function uc_coupon_purchase_assign_action_form_ajax($form, $form_state) {
return $form['parameter']['cid']['settings']['cid'];
}
/**
* Options list callback for message formats.
*/
function uc_coupon_purchase_message_formats() {
global $user;
$options = array();
$formats = filter_formats($user);
foreach ($formats as $format) {
$options[$format->format] = $format->name;
}
return $options;
}
/**
* Action callback to send an e-mail regarding coupon purchase.
*/
function uc_coupon_purchase_email($order, $coupon, $from, $addresses, $subject, $message, $format) {
$settings = array(
'from' => $from,
'subject' => $subject,
'message' => $message,
'format' => $format,
'replacements' => array(), // Replacements are handled directly by Rules.
);
// Split up our recipient e-mail addresses.
$recipients = array();
foreach (explode("\n", $addresses) as $address) {
$recipients[] = trim($address);
}
// Send the e-mails.
foreach ($recipients as $email) {
$sent = drupal_mail('uc_order', 'action-mail', $email, uc_store_mail_recipient_language($email), $settings, empty($settings['from']) ? uc_store_email_from() : $settings['from']);
if (!$sent['result']) {
watchdog('uc_order', 'Attempt to e-mail @email concerning order @order_id failed.', array('@email' => $email, '@order_id' => $order->order_id), WATCHDOG_ERROR);
}
}
}
/**
* Action callback to assign a coupon to a user.
*/
function uc_coupon_purchase_assign_action($params) {
$coupon = uc_coupon_load($params['cid']);
if ($coupon->cid) {
if (!empty($params['clone'])) {
$coupon = uc_coupon_purchase_create($coupon, $params['quantity'], $params['account']->uid);
}
elseif (!db_query('SELECT cpuid FROM {uc_coupon_purchase_users} where uid = :uid AND cid = :cid',
array(':uid' => $params['account']->uid, ':cid' => $coupon->cid))->fetchField(0)) {
$record = array('uid' => $params['account']->uid, 'cid' => $coupon->cid);
drupal_write_record('uc_coupon_purchase_users', $record);
}
if (!empty($params['sole'])) {
db_delete('uc_coupon_purchase_users')
->condition('cid', $coupon->cid)
->condition('uid', $params['account']->uid, '!=')
->execute();
}
if (!empty($params['restrict'])) {
if (!empty($params['sole'])) {
$coupon->data['users'] = array();
}
$coupon->data['users'][$params['account']->uid] = $params['account']->uid;
uc_coupon_save($coupon);
}
return array('coupon' => $coupon);
}
else {
return array('coupon' => NULL);
}
}
/**
* Options list callback for list of coupons to assign.
*/
function uc_coupon_purchase_cid_options($action) {
if (empty($action->settings['cid_type'])) {
return db_query('SELECT cid, name FROM {uc_coupons}')->fetchAllKeyed();
}
else {
$status = $action->settings['cid_type'] - 1;
return db_query('SELECT cid, name FROM {uc_coupons} where status = :status', array(':status' => $status))->fetchAllKeyed();
}
}

View File

@@ -0,0 +1,116 @@
<?php
/**
* @file
* Default Rules configurations for uc_coupon_purchase.
*/
/**
* Implements hook_default_rules_configuration().
*/
function uc_coupon_purchase_default_rules_configuration() {
$rule = rules_reaction_rule();
$rule->label = t('Notify customer when a single coupon is purchased.');
$rule->active = TRUE;
$rule->event('uc_coupon_purchase')
->condition(rules_condition('uc_coupon_condition_is_bulk', array('coupon:select' => 'coupon'))->negate())
->action('uc_coupon_purchase_email', array(
'order:select' => 'order',
'coupon:select' => 'coupon',
'from' => uc_store_email_from(),
'addresses' => '[order:email]',
'subject' => t('[store:name]: coupon purchase'),
'message' => t("[order:first-name] [order:last-name], \n\nThanks to your order, [order:link], at [store:name] you now have a new coupon available to use with the code [coupon:codes].\n\nThanks again, \n\n[store:name]\n[site:slogan]"),
'format' => filter_default_format(),
));
$configs['uc_coupon_purchase_single'] = $rule;
$rule = rules_reaction_rule();
$rule->label = t('Notify customer when a bulk coupon is purchased.');
$rule->active = TRUE;
$rule->event('uc_coupon_purchase')
->condition(rules_condition('uc_coupon_condition_is_bulk', array('coupon:select' => 'coupon')))
->action('uc_coupon_purchase_email', array(
'order:select' => 'order',
'coupon:select' => 'coupon',
'from' => uc_store_email_from(),
'addresses' => '[order:email]',
'subject' => t('[store:name]: bulk coupon purchase'),
'message' => t("[order:first-name] [order:last-name], \n\nThanks to your order, [order:link], at [store:name] you now have a new set of coupons available to use with the following codes:\n\n[coupon:codes]\n\nThanks again, \n\n[store:name]\n[site:slogan]"),
'format' => filter_default_format(),
));
$configs['uc_coupon_purchase_bulk'] = $rule;
$configs['uc_coupon_gift_single'] = rules_import('{ "uc_coupon_gift_single" : {
"LABEL" : "Notify recipient when a single coupon is purchased as a gift.",
"PLUGIN" : "reaction rule",
"REQUIRES" : [ "uc_coupon", "rules", "uc_coupon_purchase" ],
"ON" : [ "uc_coupon_purchase" ],
"IF" : [
{ "NOT uc_coupon_condition_is_bulk" : { "coupon" : [ "coupon" ] } },
{ "NOT data_is_empty" : { "data" : [ "product:uc-coupon-purchase-recipient" ] } }
],
"DO" : [
{ "uc_coupon_purchase_email" : {
"order" : [ "order" ],
"coupon" : [ "coupon" ],
"from" : [ "order:primary-email" ],
"addresses" : [ "product:uc-coupon-purchase-recipient" ],
"subject" : "[store:name]: Gift Certificate",
"message" : "Hello!\r\n\r\n[order:first-name] [order:last-name] has sent you a gift certificate worth [coupon:value] for use at [store:name].\r\n\r\nJust enter the code [coupon:code] at checkout to receive your discount.\r\n\r\nThanks,\r\n\r\n[store:name]\r\n[site:slogan]",
"format" : "filtered_html"
}
}
]
}
}');
$configs['uc_coupon_gift_multiple'] = rules_import('{ "uc_coupon_gift_multiple" : {
"LABEL" : "Notify recipient when a bulk coupon is purchased as a gift.",
"PLUGIN" : "reaction rule",
"REQUIRES" : [ "uc_coupon", "rules", "uc_coupon_purchase" ],
"ON" : [ "uc_coupon_purchase" ],
"IF" : [
{ "uc_coupon_condition_is_bulk" : { "coupon" : [ "coupon" ] } },
{ "NOT data_is_empty" : { "data" : [ "product:uc-coupon-purchase-recipient" ] } }
],
"DO" : [
{ "uc_coupon_purchase_email" : {
"order" : [ "order" ],
"coupon" : [ "coupon" ],
"from" : [ "order:primary-email" ],
"addresses" : [ "product:uc-coupon-purchase-recipient" ],
"subject" : "[store:name]: Gift Certificate",
"message" : "Hello!\r\n\r\n[order:first-name] [order:last-name] has sent you a set of gift certificates, each worth [coupon:value], for use at [store:name].\r\n\r\nJust enter one of the codes below at checkout to receive your discount.\r\n\r\n[coupon:codes]\r\n\r\nThanks,\r\n\r\n[store:name]\r\n[site:slogan]",
"format" : "filtered_html"
}
}
]
}
}');
$configs['uc_coupon_assign_on_checkout'] = rules_import('{ "uc_coupon_assign_on_checkout" : {
"LABEL" : "Assign a store-credit coupon to its user on checkout",
"PLUGIN" : "reaction rule",
"ACTIVE" : false,
"REQUIRES" : [ "rules", "uc_coupon_purchase", "uc_coupon_workflow" ],
"ON" : [ "uc_coupon_workflow_checkout" ],
"IF" : [ { "data_is" : { "data" : [ "coupon:type" ], "value" : "credit" } } ],
"DO" : [
{ "uc_coupon_purchase_assign_action" : {
"USING" : {
"cid" : [ "coupon:cid" ],
"account" : [ "order:customer" ],
"restrict" : 1,
"sole" : 1
},
"PROVIDE" : { "coupon" : { "assigned_coupon" : "Coupon" } }
}
}
]
}
}');
return $configs;
}

View File

@@ -0,0 +1,79 @@
<?php
/**
* @file
* Views 2 hooks and callback registries.
*/
/**
* Implements hook_views_data().
*/
function uc_coupon_purchase_views_data() {
$data['uc_coupon_purchase_users']['table']['join']['users'] = array(
'left_field' => 'uid',
'field' => 'uid',
);
$data['uc_coupon_purchase_users']['table']['join']['uc_coupons'] = array(
'left_field' => 'cid',
'field' => 'cid',
);
return $data;
}
/**
* Implements hook_views_data_alter().
*/
function uc_coupon_purchase_views_data_alter(&$data) {
$data['uc_coupons']['table']['join']['users'] = array(
'left_table' => 'uc_coupon_purchase_users',
'left_field' => 'cid',
'field' => 'cid',
);
$data['users']['table']['join']['uc_coupons'] = array(
'left_table' => 'uc_coupon_purchase_users',
'left_field' => 'uid',
'field' => 'uid',
);
$data['uc_coupons']['base_name'] = array(
'title' => t('Purchase base name'),
'help' => t('The name of the coupon this purchased coupon is based on.'),
'field' => array(
'field' => 'name',
'handler' => 'uc_coupon_purchase_handler_field_base_name',
'click sortable' => TRUE,
),
'sort' => array(
'field' => 'name',
'handler' => 'views_handler_sort',
),
'filter' => array(
'field' => 'name',
'handler' => 'views_handler_filter_string',
),
'argument' => array(
'field' => 'name',
'handler' => 'views_handler_argument_string',
),
);
}
/**
* Implements hook_views_handlers().
*/
function uc_coupon_purchase_views_handlers() {
return array(
'info' => array(
'path' => drupal_get_path('module', 'uc_coupon_purchase') . '/views',
),
'handlers' => array(
'uc_coupon_purchase_handler_field_base_name' => array(
'parent' => 'views_handler_field',
),
),
);
}

View File

@@ -0,0 +1,20 @@
<?php
/**
* @file
* Views handler: Coupon base name
*/
/**
* Return base name of purchased coupon (strip off "purchased by...")
*/
class uc_coupon_purchase_handler_field_base_name extends views_handler_field {
function render($values) {
$s = $values->{$this->field_alias};
$n = stripos($s, "purchased by");
if ($n) {
$s = substr($s, 0, $n -1);
}
return $s;
}
}

View File

@@ -0,0 +1,13 @@
name = Discount Coupon Recurring Payment Integration
description = Allows discounts to apply to recurring payments.
dependencies[] = uc_coupon
dependencies[] = uc_recurring
package = Ubercart - payment
core = 7.x
; Information added by drupal.org packaging script on 2012-12-02
version = "7.x-3.0-alpha0"
core = "7.x"
project = "uc_coupon"
datestamp = "1354467877"

View File

@@ -0,0 +1,77 @@
<?php
/**
* @file
* Discount coupon recurring payment integration.
*
* Allows coupons to apply to recurring payments
*/
/**
* Implements hook_module_implements_alter().
*
* Ensures that coupons are applied to recurring orders last.
*/
function uc_coupon_recurring_module_implements_alter(&$implementations, $hook) {
if ($hook == 'recurring_renewal_pending') {
$group = $implementations['uc_coupon_recurring'];
unset($implementations['uc_coupon_recurring']);
$implementations['uc_coupon_recurring'] = $group;
}
}
/**
* Implements hook_form_FORM_ID_alter() for the uc_coupon_add_form.
*/
function uc_coupon_recurring_form_uc_coupon_add_form_alter(&$form, &$form_state) {
$active = !empty($form['#uc_coupon']->data['recurring_payments']);
$form['uc_coupon_recurring'] = array(
'#type' => 'fieldset',
'#title' => t('Recurring payment settings'),
'#description' => t('Controls the way this coupon is applied to recurring payments.'),
'#collapsible' => TRUE,
'#collapsed' => !$active,
);
$form['uc_coupon_recurring']['recurring_payments'] = array(
'#type' => 'textfield',
'#title' => t('Maximum number of recurring payments to discount'),
'#description' => t('Specify the maximum number of payments (after the initial order) to which the discount should be applied. Leave blank (or enter 0) to apply only to the initial order. Enter -1 to apply to all recurring payments. Please note this will be ignored if recurring payments are processed via Paypal WPS.'),
'#default_value' => !empty($form['#uc_coupon']->data['recurring_payments']) ? $form['#uc_coupon']->data['recurring_payments'] : '',
);
$form['#entity_builders'][] = 'uc_coupon_recurring_build_coupon';
}
/**
* Entity builder callback.
*/
function uc_coupon_recurring_build_coupon($type, $coupon, $form, $form_state) {
if ($type == 'uc_coupon') {
if (!empty($form_state['values']['recurring_payments'])) {
$coupon->data['recurring_payments'] = $form_state['values']['recurring_payments'];
}
}
}
/**
* Implements hook_recurring_renewal_pending().
*
* Reapplies any coupons that were originally valid for this order.
*/
function uc_coupon_recurring_recurring_renewal_pending(&$order, $fee) {
$coupons = array();
if (!empty($order->data['coupons'])) {
$codes = array_keys($order->data['coupons']);
$order->data['coupons'] = array();
foreach ($codes as $code) {
$coupon = uc_coupon_find($code);
$limit = empty($coupon->data['recurring_payments']) ? 0 : $coupon->data['recurring_payments'];
if ($coupon && ($limit < 0 || $limit > $fee->charged_intervals)) {
uc_coupon_prepare($coupon, $code, uc_coupon_calculate_discounts($coupon, $order));
$coupons[] = $coupon;
$order->data['coupons'][$code] = $coupon->discounts;
}
}
if (!empty($coupons)) {
uc_coupon_apply_to_order($order, $coupons);
}
}
}

View File

@@ -0,0 +1,13 @@
name = Discount Coupon Extended Workflow
description = Provides extended rules support for Ubercart Discount Coupons
dependencies[] = uc_coupon
dependencies[] = rules
package = Ubercart - payment
core = 7.x
; Information added by drupal.org packaging script on 2012-12-02
version = "7.x-3.0-alpha0"
core = "7.x"
project = "uc_coupon"
datestamp = "1354467877"

View File

@@ -0,0 +1,140 @@
<?php
/**
* @file
* Discount coupon workflow.
*
* Provides rules-based workflow enhancements to uc_coupon.
*/
/**
* Implements hook_permission().
*/
function uc_coupon_workflow_permission() {
$perms = array(
'suspend coupon workflow' => array(
'title' => t('suspend coupon workflow'),
'description' => t('Prevent configured coupon workflow rules from being executed.'),
),
);
return $perms;
}
/**
* Implements hook_uc_coupon_revalidate().
*
* @param $order
* The order to valiate against.
*/
function uc_coupon_workflow_uc_coupon_revalidate($order) {
rules_invoke_event('uc_coupon_workflow_automatic', $order);
}
/**
* Implements hook_uc_coupon_apply().
*/
function uc_coupon_workflow_uc_coupon_apply($coupon) {
rules_invoke_event('uc_coupon_workflow_applied', $coupon);
}
/**
* Implements hook_uc_coupon_remove().
*/
function uc_coupon_workflow_uc_coupon_remove($coupon) {
rules_invoke_event('uc_coupon_workflow_removed', $coupon);
}
/**
* Implements hook_form_user_register_form_alter().
*
* Gives administrators the option of preventing any coupon workflow rules from being executed
* when a new user is created.
*/
function uc_coupon_workflow_form_user_register_form_alter(&$form, &$form_state) {
$element = uc_coupon_workflow_suspend_element('user_insert');
if (isset($element)) {
// Decide which part of the form to modify.
if ($form['account']) {
$use_form = &$form['account'];
}
else {
$use_form = &$form;
}
$use_form['uc_coupon_workflow'] = $element;
}
}
/**
* Implements hook_user_insert().
*
* If the creator of this user has suspended coupon workflow, then set the static variable accordingly.
*/
function uc_coupon_workflow_user_insert(&$edit, $account, $category) {
if (user_access('suspend coupon workflow') && isset($edit['uc_coupon_workflow_suspended']) && $edit['uc_coupon_workflow_suspended'] == TRUE) {
$var = &drupal_static('uc_coupon_workflow_suspended');
$var = TRUE;
}
else {
drupal_static_reset('uc_coupon_workflow_suspended');
}
}
/**
* Builds a form element allowing an administrator to suspend coupon workflow.
* @param $events
* An array of event names. If specified, the listed rules will be limited to these events.
*/
function uc_coupon_workflow_suspend_element($events = FALSE) {
if ($events && !is_array($events)) {
$events = array($events);
}
if (user_access('suspend coupon workflow')) {
// Examine all rules to see if there are any which depend on our condition,
// so we can list them for the administrator.
$found = array();
$rules = rules_config_load_multiple(FALSE);
foreach ($rules as $name => $rule) {
if ($rule instanceof RulesReactionRule && $rule->active) {
foreach ($rule->conditions() as $condition) {
if (method_exists($condition, 'getElementName') && $condition->getElementName() == 'uc_coupon_workflow_suspended' && (!$events || count(array_intersect($rule->events(), $events)))) {
$found[] = $rule->label;
}
}
}
}
// If we've found some applicable rules, then list them and offer to suspend.
if (count($found)) {
$element = array(
'#type' => 'fieldset',
'#title' => t('Discount coupon workflow'),
'#description' => t('Some automatic discount coupon actions are configured to be executed when this form is submitted.
You can suspend these actions by checking the box below.'),
);
$element['actions'] = array(
'#type' => 'item',
'#title' => t('The following actions are enabled:'),
'list' => array(
'#theme' => 'item_list',
'#items' => $found,
'#type' => 'ul',
),
);
$element['uc_coupon_workflow_suspended'] = array(
'#type' => 'checkbox',
'#title' => t('Prevent these actions from being executed this time.'),
);
return $element;
}
}
}
/**
* Implements hook uc_checkout_complete().
*/
function uc_coupon_workflow_uc_checkout_complete($order, $account) {
foreach (uc_coupon_get_order_coupons($order) as $coupon) {
rules_invoke_event('uc_coupon_workflow_checkout', $coupon, $order);
}
}

View File

@@ -0,0 +1,334 @@
<?php
/**
* @file
* Rules integration for uc_coupon_workflow
*/
/**
* Implements hook_rules_condition_info().
*/
/**
* Implements hook_rules_event_info().
*
*/
function uc_coupon_workflow_rules_event_info() {
// Event invoked when a valid coupon is applied.
$events['uc_coupon_workflow_applied'] = array(
'label' => t('A valid discount coupon is applied'),
'group' => t('Coupon'),
'variables' => array(
'coupon' => array(
'type' => 'uc_coupon',
'label' => t('Coupon'),
),
),
);
// Event invoked when a valid coupon is applied.
$events['uc_coupon_workflow_removed'] = array(
'label' => t('A valid discount coupon is removed'),
'group' => t('Coupon'),
'variables' => array(
'coupon' => array(
'type' => 'uc_coupon',
'label' => t('Coupon'),
),
),
);
// Event invoked when checking for automatic coupons.
$events['uc_coupon_workflow_automatic'] = array(
'label' => t('Check for automatic discounts.'),
'group' => t('Coupon'),
'variables' => array(
'current_order' => array(
'type' => 'uc_order',
'label' => t('Current Order'),
),
),
);
// Event invoked when a coupon is submitted with an order.
// !TODO This functionality would be better implemented by some sort of conditional
// loop processing. See http://drupal.org/node/821986
$events['uc_coupon_workflow_checkout'] = array(
'label' => t('A customer checks out with a valid discount coupon'),
'group' => t('Coupon'),
'variables' => array(
'coupon' => array(
'type' => 'uc_coupon',
'label' => t('Coupon'),
),
'order' => array(
'type' => 'uc_order',
'label' => t('Order'),
),
),
);
return $events;
}
/**
* Implements hook_rules_condition_info().
*/
function uc_coupon_workflow_rules_condition_info() {
$conditions['uc_coupon_workflow_suspended'] = array(
'label' => t('Check if an administrator has suspended automatic coupon workflow for this request.'),
'group' => t('Coupon'),
);
return $conditions;
}
/**
* Implements hook_rules_action_info().
*/
function uc_coupon_workflow_rules_action_info() {
$actions = array();
// Assign a coupon to a user.
$actions['uc_coupon_workflow_assign'] = array(
'label' => t('Authorize a user to use a coupon.'),
'group' => t('Coupon'),
'provides' => array(
'coupon' => array(
'type' => 'uc_coupon',
'label' => t('Coupon'),
),
),
'parameter' => array(
'account' => array(
'type' => 'user',
'label' => t('Account'),
'description' => t('Select the user account you wish to authorize.'),
),
'cid' => array(
'type' => 'integer',
'label' => t('Coupon'),
'description' => t('Select the base coupon to be assigned.
The new user will be added to the list of authorized users for the selected coupon.'),
'options list' => 'uc_coupon_workflow_cid_options',
'restriction' => 'input',
),
),
);
// Send an e-mail regarding a coupon.
$actions['uc_coupon_workflow_email'] = array(
'label' => t('Send an email regarding a coupon.'),
'group' => t('Coupon'),
'parameter' => array(
'coupon' => array(
'type' => 'uc_coupon',
'label' => t('Coupon'),
),
'from' => array(
'type' => 'text',
'label' => t('Sender'),
'restriction' => 'input',
),
'addresses' => array(
'type' => 'text',
'label' => t('Recipients'),
'description' => t('Enter the email addresses to receive the notifications, one per line.'),
'restriction' => 'input',
),
'subject' => array(
'type' => 'text',
'label' => t('Subject'),
'description' => t('Enter the subject line for the notifications.'),
'restriction' => 'input',
),
'message' => array(
'type' => 'text',
'label' => t('Message'),
'description' => t('Enter the message body for the notifications.'),
'restriction' => 'input',
),
'format' => array(
'type' => 'text',
'label' => t('Message format'),
'options list' => 'uc_coupon_workflow_message_formats',
),
),
);
// Apply an automatic coupon.
$actions['uc_coupon_workflow_apply'] = array(
'label' => t('Apply a coupon to the current order.'),
'group' => t('Coupon'),
'provides' => array(
'coupon' => array(
'type' => 'uc_coupon',
'label' => t('Coupon'),
),
),
'parameter' => array(
'cid' => array(
'type' => 'integer',
'label' => t('Coupon'),
'description' => t('Select the coupon to apply. The coupon will only be
applied if and when all of its restrictions are satisfied.'),
'options list' => 'uc_coupon_workflow_apply_options',
'restriction' => 'input',
),
'mode' => array(
'type' => 'text',
'label' => t('Mode'),
'description' => t('Choose the way this coupon should be applied.'),
'options list' => 'uc_coupon_workflow_apply_modes',
'default value' => 'retain',
'restriction' => 'input',
),
),
);
return $actions;
}
/**
* Options list callback for list of coupons to assign.
*/
function uc_coupon_workflow_cid_options() {
return db_query('SELECT cid, name FROM {uc_coupons} WHERE status = 1')->fetchAllKeyed();
}
/**
* Options list callback for message formats.
*/
function uc_coupon_workflow_message_formats() {
global $user;
$options = array();
$formats = filter_formats($user);
foreach ($formats as $format) {
$options[$format->format] = $format->name;
}
return $options;
}
/**
* For certain events (e.g. new user creation), administrators are provided
* with an interface which allows them to prevent execution of coupon actions
* based on those events.
*/
function uc_coupon_workflow_suspended($settings) {
$auth = drupal_static('uc_coupon_workflow_suspended');
return !empty($auth);
}
/**
* Action callback to assign a coupon to a user.
*/
function uc_coupon_workflow_assign($account, $cid) {
$coupon = uc_coupon_load($cid);
if ($coupon->cid) {
// Grant access to the coupon.
$coupon->data['users'][$account->uid] = $account->uid;
uc_coupon_save($coupon);
return array('coupon' => $coupon);
}
else {
return array('coupon' => NULL);
}
}
/**
* Action callback to send an e-mail regarding a coupon.
*/
function uc_coupon_workflow_email($coupon, $from, $addresses, $subject, $message, $format) {
// Build the e-mail parameters.
$params = array(
'from' => $from,
'subject' => $subject,
'message' => $message,
'format' => $format,
'replacements' => array(), // The replacements are already handled by Rules.
);
// Split up our recipient e-mail addresses.
$recipients = array();
foreach (explode("\n", $addresses) as $address) {
$recipients[] = trim($address);
}
// Send the e-mails.
foreach ($recipients as $email) {
$sent = drupal_mail('uc_order', 'action-mail', $email, uc_store_mail_recipient_language($email), $params, $from);
if (!$sent['result']) {
watchdog('uc_coupon', 'Attempt to e-mail @email concerning coupon @cid failed.', array('@email' => $email, '@cid' => $coupon->cid), WATCHDOG_ERROR);
}
}
}
/**
* Action callback to apply a coupon.
* This simply adds the coupon to the session; it is validated later.
*/
function uc_coupon_workflow_apply($cid, $mode) {
$coupon = uc_coupon_load($cid);
if ($coupon->cid) {
uc_coupon_session_add($coupon->code, $mode);
return array('coupon' => $coupon);
}
else {
return array('coupon' => NULL);
}
}
function uc_coupon_workflow_apply_help() {
return '<p>' .
t('This action can be used in two ways: to apply a coupon normally in response to a discrete event
(for example, when a particular user logs in), or to apply an automatic discount in response to the
"%event" event, which occurs every time the current cart contents are updated (for example, to
apply a discount if a particular combination of products is ordered).',
array('%event' => t('Check for automatic discounts'))) .
'</p><p>' .
t('Automatic discounts are treated differently than normal coupons: they are listed in separate panes
on the checkout and cart pages, and they may not be removed by the customer. Unlike normal coupons,
they are automatically removed if the rule\'s conditions are not met.') .
'</p><p>' .
t('Note that a coupon specified in this action will only apply to an order if its restrictions
(as specified on the coupon add/edit page) are met. That is, both the conditions of this rule
and the coupon\'s restrictions must be satisfied. Note also that normal coupons always take
precedence over automatic discounts, so if a customer enters a code for a coupon which has not
been configured combine with a particular automatic discount, that automatic discount will
be pre-empted.') .
'</p>';
}
/**
* Generate list of coupon options for auto apply action.
*/
function uc_coupon_workflow_apply_options() {
// Only non-bulk coupons may be applied automatically to avoid ambiguity regarding which code to apply.
$rows = db_query('SELECT cid, name, code FROM {uc_coupons} WHERE status = :status AND bulk = :bulk',
array(':status' => 1, ':bulk' => 0, ));
$ops = array();
foreach ($rows as $row) {
$ops[$row->cid] = t("@name (Code: @code)", array('@name' => $row->name, '@code' => $row->code));
}
return $ops;
}
function uc_coupon_workflow_apply_modes() {
return array(
'retain' => t('Apply this coupon normally. It will added to the session for the current customer, and when its
restrictions are satisfied, it will be applied exactly as if the code had been submitted manually.'),
'auto' => t('Apply this coupon as an automatic discount.') . ' <strong>' . t('Only select this option if this rule
reacts to the "%event" event.', array('%event' => t('Check for automatic discounts'))) . '</strong>. ' .
t('Then, this rule will be evaluated whenever the cart contents are updated, and the coupon applied
only if all conditions and restrictions are satisfied.'),
);
}
/**
* Implementatino of 'form_alter' callback for the apply action.
* Change the select list to radio buttons.
*/
function uc_coupon_workflow_apply_form_alter(&$form, $form_state) {
$form['parameter']['mode']['settings']['mode']['#type'] = 'radios';
}

View File

@@ -0,0 +1,35 @@
<?php
/**
* @file
* Default Rules configurations for uc_coupon_workflow.
*/
/**
* Implements hook_default_rules_configuration().
*/
function uc_coupon_workflow_default_rules_configuration() {
// An example of issuing a coupon on user registration.
$rule = rules_reaction_rule();
$rule->label = t('Assign coupon #1 when a new user registers (template).');
$rule->active = FALSE;
$rule->event('user_insert')
->condition(rules_condition('uc_coupon_workflow_suspended')->negate())
->action('uc_coupon_workflow_assign', array(
'account:select' => 'account',
'cid' => 1
))
->action('uc_coupon_workflow_email', array(
'coupon:select' => 'coupon',
'from' => '[site:mail]',
'addresses' => '[account:mail]',
'subject' => t('Coupon at [site:name]'),
'message' => t("[account:name],\n\nThank you for registering at [site:name].\n\nYou may use the following coupon code(s) during checkout:\n\n[coupon:codes]\n\nPlease ensure you are logged in to your account, or you will not be able to use the coupon.\n\n\n-- The [site:name] team"),
'format' => filter_default_format(),
));
$configs['uc_coupon_workflow_register'] = $rule;
return $configs;
}

View File

@@ -0,0 +1,468 @@
<?php
/**
* @file
* Views 2 hooks and callback registries.
*/
/**
* Implements hook_views_data().
*/
function uc_coupon_views_data() {
$data['uc_coupons']['table']['group'] = t('Coupon');
$data['uc_coupons']['table']['base'] = array(
'field' => 'cid',
'title' => t('Coupon'),
'help' => t("Ubercart discount coupons."),
);
$data['uc_coupons']['cid'] = array(
'title' => t('ID'),
'help' => t('The unique ID of the coupon.'),
'field' => array(
'handler' => 'views_handler_field',
'click sortable' => TRUE,
),
'sort' => array(
'handler' => 'views_handler_sort',
),
'filter' => array(
'handler' => 'views_handler_filter_numeric',
),
'argument' => array(
'handler' => 'views_handler_argument_numeric',
),
);
$data['uc_coupons']['name'] = array(
'title' => t('Name'),
'help' => t('The name of the coupon.'),
'field' => array(
'handler' => 'views_handler_field',
'click sortable' => TRUE,
),
'sort' => array(
'handler' => 'views_handler_sort',
),
'filter' => array(
'handler' => 'views_handler_filter_string',
),
'argument' => array(
'handler' => 'views_handler_argument_string',
),
);
$data['uc_coupons']['code'] = array(
'title' => t('Code'),
'help' => t('The coupon code, or prefix for bulk coupons.'),
'field' => array(
'handler' => 'views_handler_field',
'click sortable' => TRUE,
),
'sort' => array(
'handler' => 'views_handler_sort',
),
'filter' => array(
'handler' => 'views_handler_filter_string',
),
'argument' => array(
'handler' => 'views_handler_argument_string',
),
);
$data['uc_coupons']['bulk_codes'] = array(
'title' => t('Codes'),
'help' => t('All codes associated with this coupon.'),
'field' => array(
'handler' => 'uc_coupon_handler_field_codes',
'field' => 'cid',
),
);
$data['uc_coupons']['bulk'] = array(
'title' => t('Bulk'),
'help' => t('Whether the coupon is a bulk coupon with multiple suffixes.'),
'field' => array(
'handler' => 'views_handler_field_boolean',
'click sortable' => TRUE,
),
'filter' => array(
'handler' => 'views_handler_filter_boolean_operator',
'label' => t('Is a bulk coupon'),
'type' => 'yes-no',
),
'sort' => array(
'handler' => 'views_handler_sort',
),
);
$data['uc_coupons']['created'] = array(
'title' => t('Creation date'),
'help' => t('The date the coupon was created.'),
'field' => array(
'handler' => 'views_handler_field_date',
'click sortable' => TRUE,
),
'sort' => array(
'handler' => 'views_handler_sort_date',
),
'filter' => array(
'handler' => 'views_handler_filter_date',
),
);
$data['uc_coupons']['valid_from'] = array(
'title' => t('Valid from'),
'help' => t('The date the coupon becomes valid.'),
'field' => array(
'handler' => 'views_handler_field_date',
'click sortable' => TRUE,
),
'sort' => array(
'handler' => 'views_handler_sort_date',
),
'filter' => array(
'handler' => 'views_handler_filter_date',
),
);
$data['uc_coupons']['valid_until'] = array(
'title' => t('Valid until'),
'help' => t('The date the coupon expires.'),
'field' => array(
'handler' => 'views_handler_field_date',
'click sortable' => TRUE,
),
'sort' => array(
'handler' => 'views_handler_sort_date',
),
'filter' => array(
'handler' => 'views_handler_filter_date',
),
);
$data['uc_coupons']['status'] = array(
'title' => 'Active',
'help' => t('Whether the coupon is available to use.'),
'field' => array(
'handler' => 'views_handler_field_boolean',
'click sortable' => TRUE,
),
'filter' => array(
'handler' => 'views_handler_filter_boolean_operator',
'label' => t('Active'),
'type' => 'yes-no',
),
'sort' => array(
'handler' => 'views_handler_sort',
),
);
$data['uc_coupons']['type'] = array(
'title' => 'Type',
'help' => t('The discount type of the coupon.'),
'field' => array(
'handler' => 'views_handler_field',
'click sortable' => TRUE,
),
'sort' => array(
'handler' => 'views_handler_sort',
),
'filter' => array(
'handler' => 'views_handler_filter_string',
),
'argument' => array(
'handler' => 'views_handler_argument_string',
),
);
$data['uc_coupons']['value'] = array(
'title' => t('Value'),
'help' => t('The value of the coupon.'),
'field' => array(
'handler' => 'uc_coupon_handler_field_value',
'click sortable' => TRUE,
'float' => TRUE,
'additional fields' => array(
'type' => 'type',
),
),
'sort' => array(
'handler' => 'views_handler_sort',
),
'filter' => array(
'handler' => 'views_handler_filter_numeric',
),
'argument' => array(
'handler' => 'views_handler_argument_numeric',
),
);
$data['uc_coupons']['minimum_order'] = array(
'title' => t('Minimum order total'),
'help' => t('The minimum order total that applies to the coupon.'),
'field' => array(
'handler' => 'views_handler_field_numeric',
'click sortable' => TRUE,
'float' => TRUE,
),
'sort' => array(
'handler' => 'views_handler_sort',
),
'filter' => array(
'handler' => 'views_handler_filter_numeric',
),
'argument' => array(
'handler' => 'views_handler_argument_numeric',
),
);
$data['uc_coupons']['max_uses'] = array(
'title' => t('Max uses per code'),
'help' => t('The maximum number of times this coupon can be redeemed.'),
'field' => array(
'handler' => 'views_handler_field',
'click sortable' => TRUE,
),
'sort' => array(
'handler' => 'views_handler_sort',
),
'filter' => array(
'handler' => 'views_handler_filter_numeric',
),
'argument' => array(
'handler' => 'views_handler_argument_numeric',
),
);
$data['uc_coupons']['actions'] = array(
'title' => t('Actions'),
'help' => t('A set of actions the current user can perform on the coupon.'),
'field' => array(
'handler' => 'uc_coupon_handler_field_actions',
'field' => 'cid',
'additional fields' => array(
'name' => 'name',
'bulk' => 'bulk',
),
),
);
$data['uc_coupons']['product_type'] = array(
'title' => t('Product classes'),
'help' => t('Product classes for which this coupon is valid.'),
'field' => array(
'field' => 'cid',
'handler' => 'uc_coupon_handler_field_product_type',
'label' => t('Product types'),
'additional fields' => array(
'data' => 'data',
),
),
'filter' => array(
'handler' => 'uc_coupon_handler_filter_product_type',
'label' => 'Is a product type',
),
'argument' => array(
'handler' => 'uc_coupon_handler_argument_product_type',
'label' => 'Is a product type',
),
);
$data['uc_coupons']['bulk_number'] = array(
'title' => t('Bulk number'),
'help' => t('Number of bulk codes based on this coupon.'),
'field' => array(
'handler' => 'uc_coupon_handler_field_bulk_number',
'field' => 'data',
),
);
$data['uc_coupons']['all_orders_count'] = array(
'title' => t('All orders count'),
'help' => t('The number of orders to which this coupon was applied.'),
'field' => array(
'handler' => 'uc_coupon_handler_field_all_orders_count',
),
);
$data['uc_coupons']['table']['join']['uc_orders'] = array(
'left_table' => 'uc_coupons_orders',
'left_field' => 'oid',
'field' => 'order_id',
);
$data['uc_coupons']['all_orders_total'] = array(
'title' => t('All orders total'),
'help' => t('The total bottom-line for all orders to which this coupon was applied.'),
'field' => array(
'handler' => 'uc_coupon_handler_field_all_orders_total',
'float' => TRUE,
),
);
$data['uc_coupons']['all_orders_value'] = array(
'title' => t('All orders total value'),
'help' => t('The total value of this coupon for all orders to which it was applied.'),
'field' => array(
'handler' => 'uc_coupon_handler_field_all_orders_value',
'float' => TRUE,
),
);
$data['uc_coupons']['all_orders_gross'] = array(
'title' => t('All orders gross total'),
'help' => t('The pre-discount total for all orders to which this coupon was applied.'),
'field' => array(
'handler' => 'uc_coupon_handler_field_all_orders_gross',
'float' => TRUE,
),
);
//
// Table: uc_coupons_orders
//
$data['uc_coupons_orders']['table']['group'] = t('Coupon order');
$data['uc_coupons_orders']['table']['join']['uc_coupons'] = array(
'left_field' => 'cid',
'field' => 'cid',
);
// Join to the uc_orders table.
$data['uc_coupons_orders']['table']['join']['uc_orders'] = array(
'left_field' => 'order_id',
'field' => 'oid',
);
$data['uc_orders']['table']['join']['uc_coupons'] = array(
'left_table' => 'uc_coupons_orders',
'left_field' => 'oid',
'field' => 'order_id',
);
$data['uc_coupons_orders']['code'] = array(
'title' => t('Code'),
'help' => t('The coupon code used for this order'),
'field' => array(
'handler' => 'views_handler_field',
'click sortable' => TRUE,
),
'sort' => array(
'handler' => 'views_handler_sort',
),
'filter' => array(
'handler' => 'views_handler_filter_string',
),
'argument' => array(
'handler' => 'views_handler_argument_string',
),
);
$data['uc_coupons_orders']['value'] = array(
'title' => t('Value'),
'help' => t('The value of the coupon used for this order'),
'field' => array(
'handler' => 'uc_order_handler_field_money_amount',
'click sortable' => TRUE,
'float' => TRUE,
),
'sort' => array(
'handler' => 'views_handler_sort',
),
'filter' => array(
'handler' => 'views_handler_filter_string',
),
'argument' => array(
'handler' => 'views_handler_argument_string',
),
);
$data['uc_coupons_orders']['gross'] = array(
'title' => t('Gross'),
'help' => t('The pre-discount bottom-line for this order'),
'field' => array(
'handler' => 'uc_coupon_handler_field_gross',
'float' => TRUE,
'click sortable' => TRUE,
),
'sort' => array(
'handler' => 'views_handler_sort',
),
'filter' => array(
'handler' => 'uc_coupon_handler_filter_gross'
),
);
$data['uc_coupons_orders']['oid'] = array(
'title' => t('Order ID'),
'help' => t('The order ID of this coupon order'),
'field' => array(
'handler' => 'views_handler_field',
'click sortable' => TRUE,
),
'sort' => array(
'handler' => 'views_handler_sort',
),
'filter' => array(
'handler' => 'views_handler_filter_string',
),
'argument' => array(
'handler' => 'views_handler_argument_string',
),
);
return $data;
}
/**
* Implements hook_views_handlers().
*/
function uc_coupon_views_handlers() {
return array(
'info' => array(
'path' => drupal_get_path('module', 'uc_coupon') . '/views',
),
'handlers' => array(
'uc_coupon_handler_field_value' => array(
'parent' => 'views_handler_field_numeric',
),
'uc_coupon_handler_field_actions' => array(
'parent' => 'views_handler_field',
),
'uc_coupon_handler_field_bulk_number' => array(
'parent' => 'views_handler_field_numeric',
),
'uc_coupon_handler_field_codes' => array(
'parent' => 'views_handler_field_prerender_list',
),
'uc_coupon_handler_filter_product_type' => array(
'parent' => 'views_handler_filter_in_operator',
),
'uc_coupon_handler_argument_product_type' => array(
'parent' => 'views_handler_argument',
),
'uc_coupon_handler_field_product_type' => array(
'parent' => 'views_handler_field_prerender_list',
),
'uc_coupon_handler_field_all_orders_count' => array(
'parent' => 'views_handler_field_numeric',
),
'uc_coupon_handler_field_all_orders_total' => array(
'parent' => 'uc_order_handler_field_money_amount',
),
'uc_coupon_handler_field_all_orders_value' => array(
'parent' => 'uc_coupon_handler_field_all_orders_total',
),
'uc_coupon_handler_field_all_orders_gross' => array(
'parent' => 'uc_coupon_handler_field_all_orders_total',
),
'uc_coupon_handler_field_gross' => array(
'parent' => 'uc_order_handler_field_money_amount',
),
'uc_coupon_handler_filter_gross' => array(
'parent' => 'views_handler_filter_numeric',
),
),
);
}

View File

@@ -0,0 +1,281 @@
<?php
/**
* @file
* Default views for uc_coupon.
*/
/**
* Implements hook_views_default_views().
*/
function uc_coupon_views_default_views() {
$view = new view;
$view->name = 'uc_coupon';
$view->description = 'Ubercart discount coupons.';
$view->tag = 'Ubercart';
$view->view_php = '';
$view->base_table = 'uc_coupons';
$view->is_cacheable = FALSE;
$view->api_version = 2;
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */
$handler = $view->new_display('default', 'Defaults', 'default');
$handler->override_option('fields', array(
'actions' => array(
'label' => 'Actions',
'alter' => array(
'alter_text' => 0,
'text' => '',
'make_link' => 0,
'path' => '',
'link_class' => '',
'alt' => '',
'prefix' => '',
'suffix' => '',
'target' => '',
'help' => '',
'trim' => 0,
'max_length' => '',
'word_boundary' => 1,
'ellipsis' => 1,
'html' => 0,
'strip_tags' => 0,
),
'empty' => '',
'hide_empty' => 0,
'empty_zero' => 0,
'exclude' => 0,
'id' => 'actions',
'table' => 'uc_coupons',
'field' => 'actions',
'relationship' => 'none',
),
'name' => array(
'id' => 'name',
'table' => 'uc_coupons',
'field' => 'name',
),
'code' => array(
'id' => 'code',
'table' => 'uc_coupons',
'field' => 'code',
),
'bulk' => array(
'label' => 'Bulk',
'alter' => array(
'alter_text' => 0,
'text' => '',
'make_link' => 0,
'path' => '',
'link_class' => '',
'alt' => '',
'prefix' => '',
'suffix' => '',
'target' => '',
'help' => '',
'trim' => 0,
'max_length' => '',
'word_boundary' => 1,
'ellipsis' => 1,
'html' => 0,
'strip_tags' => 0,
),
'empty' => '',
'hide_empty' => 0,
'empty_zero' => 0,
'type' => 'yes-no',
'not' => 0,
'exclude' => 0,
'id' => 'bulk',
'table' => 'uc_coupons',
'field' => 'bulk',
'relationship' => 'none',
),
'value' => array(
'id' => 'value',
'table' => 'uc_coupons',
'field' => 'value',
),
'created' => array(
'id' => 'created',
'table' => 'uc_coupons',
'field' => 'created',
),
'valid_from' => array(
'id' => 'valid_from',
'table' => 'uc_coupons',
'field' => 'valid_from',
),
'valid_until' => array(
'id' => 'valid_until',
'table' => 'uc_coupons',
'field' => 'valid_until',
),
));
$handler->override_option('filters', array(
'status' => array(
'operator' => '=',
'value' => '1',
'group' => '0',
'exposed' => TRUE,
'expose' => array(
'operator' => '',
'identifier' => 'status',
'label' => 'Active',
'optional' => 1,
'remember' => 1,
),
'id' => 'status',
'table' => 'uc_coupons',
'field' => 'status',
'relationship' => 'none',
),
'bulk' => array(
'operator' => '=',
'value' => 'All',
'group' => '0',
'exposed' => TRUE,
'expose' => array(
'operator' => '',
'identifier' => 'bulk',
'label' => 'Bulk',
'optional' => 1,
'remember' => 0,
),
'id' => 'bulk',
'table' => 'uc_coupons',
'field' => 'bulk',
'relationship' => 'none',
),
'code' => array(
'operator' => '=',
'value' => '',
'group' => '0',
'exposed' => TRUE,
'expose' => array(
'use_operator' => 1,
'operator' => 'code_op',
'identifier' => 'code',
'label' => 'Code',
'optional' => 1,
'remember' => 0,
),
'case' => 0,
'id' => 'code',
'table' => 'uc_coupons',
'field' => 'code',
'relationship' => 'none',
),
'name' => array(
'operator' => '=',
'value' => '',
'group' => '0',
'exposed' => TRUE,
'expose' => array(
'use_operator' => 1,
'operator' => 'name_op',
'identifier' => 'name',
'label' => 'Name',
'optional' => 1,
'remember' => 0,
),
'case' => 1,
'id' => 'name',
'table' => 'uc_coupons',
'field' => 'name',
'relationship' => 'none',
),
'value' => array(
'operator' => 'between',
'value' => array(
'value' => '',
'min' => '',
'max' => '',
),
'group' => '0',
'exposed' => TRUE,
'expose' => array(
'use_operator' => 1,
'operator' => 'coupon_value_op',
'identifier' => 'coupon_value',
'label' => 'Value',
'optional' => 1,
'remember' => 0,
),
'id' => 'value',
'table' => 'uc_coupons',
'field' => 'value',
'relationship' => 'none',
),
));
$handler->override_option('access', array(
'type' => 'perm',
'perm' => 'view store coupons',
));
$handler->override_option('cache', array(
'type' => 'none',
));
$handler->override_option('title', 'Coupons');
$handler->override_option('empty', 'No matching coupons found.');
$handler->override_option('empty_format', '1');
$handler->override_option('items_per_page', 20);
$handler->override_option('use_pager', '1');
$handler->override_option('style_plugin', 'table');
$handler->override_option('style_options', array(
'grouping' => '',
'override' => 1,
'sticky' => 0,
'order' => 'asc',
'columns' => array(
'name' => 'name',
'code' => 'code',
'value' => 'value',
'created' => 'created',
'valid_from' => 'valid_from',
'valid_until' => 'valid_until',
),
'info' => array(
'name' => array(
'sortable' => 0,
'separator' => '',
),
'code' => array(
'sortable' => 0,
'separator' => '',
),
'value' => array(
'sortable' => 0,
'separator' => '',
),
'created' => array(
'sortable' => 0,
'separator' => '',
),
'valid_from' => array(
'sortable' => 0,
'separator' => '',
),
'valid_until' => array(
'sortable' => 0,
'separator' => '',
),
),
'default' => 'code',
));
$handler = $view->new_display('page', 'Page', 'page_1');
$handler->override_option('path', 'coupons');
$handler->override_option('menu', array(
'type' => 'none',
'title' => '',
'description' => '',
'weight' => 0,
'name' => 'navigation',
));
$handler->override_option('tab_options', array(
'type' => 'none',
'title' => '',
'description' => '',
'weight' => 0,
'name' => 'navigation',
));
$views[$view->name] = $view;
return $views;
}

View File

@@ -0,0 +1,25 @@
<?php
/**
* @file
* Views handler: Coupon filter on "product-type".
*/
/**
* Filter coupons based on what product types they apply to
*/
class uc_coupon_handler_argument_product_type extends views_handler_argument {
function query() {
$this->ensure_my_table();
$this->query->add_field('uc_coupons', 'data');
if (!empty($this->argument)) {
$regexp = '.*product_types.*{[^}]*(' . $this->argument . ').*}';
$this->query->add_where_expression(0,
'uc_coupons.data ' . 'REGEXP :re',
array(':re' => $regexp)
);
}
//. ($this->options['operator'] !== 'in' ? "NOT " : "")
}
}

View File

@@ -0,0 +1,20 @@
<?php
/**
* @file
* Views handler: Coupon actions field.
*/
/**
* Return a coupon value as price or percentage.
*/
class uc_coupon_handler_field_actions extends views_handler_field {
function render($values) {
$coupon = new stdClass;
$coupon->cid = $values->{$this->field_alias};
$coupon->name = $values->{$this->aliases['name']};
$coupon->bulk = $values->{$this->aliases['bulk']};
return theme('uc_coupon_actions', array('coupon' => $coupon));
}
}

View File

@@ -0,0 +1,75 @@
<?php
// $Id$
/**
* @file
* Coupon order total field handler
*/
class uc_coupon_handler_field_all_orders_count extends views_handler_field_numeric {
/**
* Add the 'cid' field
*/
function construct() {
parent::construct();
$this->additional_fields['cid'] = 'cid';
}
/**
* Set default value for order_status option.
*/
function option_definition() {
$options = parent::option_definition();
$options['statuses'] = array('default' => array());
return $options;
}
/**
* Create order status option.
*/
function options_form(&$form, &$form_state) {
parent::options_form($form, $form_state);
$statuses = array();
foreach (uc_order_status_list() as $status) {
$statuses[$status['id']] = $status['title'];
}
$form['statuses'] = array(
'#title' => t('Order statuses'),
'#type' => 'select',
'#description' => t('Only orders with selected statuses will be counted.
If you do not select any statuses, then all orders will be counted.')
. '<br />' . t('Hold Ctrl + click to select multiple statuses.'),
'#options' => $statuses,
'#default_value' => $this->options['statuses'],
'#multiple' => TRUE,
'#size' => 5,
);
}
/**
* Here we create the aggregate field that will count the orders.
*/
function query() {
$this->ensure_my_table();
$uco = $this->query->ensure_table('uc_coupons_orders');
$uo = $this->query->ensure_table('uc_orders');
$this->add_additional_fields();
if (empty($this->options['statuses'])) {
// If no status specified, then we show all.
$in_status = "1";
}
else {
// An array of statuses was specified.
$in_status = "$uo.order_status IN('" . implode("', '", $this->options['statuses']) . "')";
}
$this->field_alias = $this->query->add_field(
NULL,
"CASE WHEN $in_status THEN 1 ELSE 0 END",
$this->table_alias . '_' . $this->field . '_' . implode('_', $this->options['statuses']),
array('function' => 'sum')
);
}
}

View File

@@ -0,0 +1,34 @@
<?php
// $Id$
/**
* @file
* Coupon order total field handler
*/
class uc_coupon_handler_field_all_orders_gross extends uc_coupon_handler_field_all_orders_total {
/**
* Add the aggregate field that will sum total+value
*
*/
function query() {
$this->ensure_my_table();
$uco = $this->query->ensure_table('uc_coupons_orders');
$uo = $this->query->ensure_table('uc_orders');
$this->add_additional_fields();
if (empty($this->options['statuses'])) {
// If no status specified, then we show all.
$in_status = "1";
}
else {
// An array of statuses was specified.
$in_status = "$uo.order_status IN('" . implode("', '", $this->options['statuses']) . "')";
}
$this->field_alias = $this->query->add_field(
NULL,
"CASE WHEN $in_status THEN ($uo.order_total+$uco.value) ELSE 0 END",
$this->table_alias . '_' . $this->field . '_' . implode('_', $this->options['statuses']),
array('function' => 'sum')
);
}
}

View File

@@ -0,0 +1,76 @@
<?php
// $Id$
/**
* @file
* Coupon order total field handler
*/
class uc_coupon_handler_field_all_orders_total extends uc_order_handler_field_money_amount {
/**
* Add 'cid' field.
*/
function construct() {
parent::construct();
$this->additional_fields['cid'] = 'cid';
}
/**
* Define option default values.
*/
function option_definition() {
$options = parent::option_definition();
$options['statuses'] = array('default' => array());
return $options;
}
/**
* Add option for order status.
*/
function options_form(&$form, &$form_state) {
parent::options_form($form, $form_state);
$statuses = array();
foreach (uc_order_status_list() as $status) {
$statuses[$status['id']] = $status['title'];
}
$form['statuses'] = array(
'#title' => t('Order statuses'),
'#type' => 'select',
'#description' => t('Only orders with selected statuses will be counted.
If you do not select any statuses, then all orders will be counted.')
. '<br />' . t('Hold Ctrl + click to select multiple statuses.'),
'#options' => $statuses,
'#default_value' => $this->options['statuses'],
'#multiple' => TRUE,
'#size' => 8,
);
}
/**
* Here we add the aggregate field that will sum the orders.
*/
function query() {
$this->ensure_my_table();
$uco = $this->query->ensure_table('uc_coupons_orders');
$uo = $this->query->ensure_table('uc_orders');
$this->add_additional_fields();
if (empty($this->options['statuses'])) {
// If no status specified, then we show all.
$in_status = "1";
}
else {
// An array of statuses was specified.
$in_status = "$uo.order_status IN('" . implode("', '", $this->options['statuses']) . "')";
}
$this->field_alias = $this->query->add_field(
NULL,
"CASE WHEN $in_status THEN $uo.order_total ELSE 0 END",
$this->table_alias . '_' . $this->field . '_' . implode('_', $this->options['statuses']),
array('function' => 'sum')
);
}
}

View File

@@ -0,0 +1,33 @@
<?php
// $Id$
/**
* @file
* Coupon order total field handler
*/
class uc_coupon_handler_field_all_orders_value extends uc_coupon_handler_field_all_orders_total {
/**
* Here we add the aggregate field that will sum the value.
*/
function query() {
$this->ensure_my_table();
$uco = $this->query->ensure_table('uc_coupons_orders');
$uo = $this->query->ensure_table('uc_orders');
$this->add_additional_fields();
if (empty($this->options['statuses'])) {
// If no status specified, then we show all.
$in_status = "1";
}
else {
// An array of statuses was specified.
$in_status = "$uo.order_status IN('" . implode("', '", $this->options['statuses']) . "')";
}
$this->field_alias = $this->query->add_field(
NULL,
"CASE WHEN $in_status THEN $uco.value ELSE 0 END",
$this->table_alias . '_' . $this->field . '_' . implode('_', $this->options['statuses']),
array('function' => 'sum')
);
}
}

View File

@@ -0,0 +1,16 @@
<?php
/**
* @file
* Views handler: Coupon bulk number.
*/
/**
* Return number of bulk codes based on this field
*/
class uc_coupon_handler_field_bulk_number extends views_handler_field_numeric {
function render($values) {
$data = unserialize($values->{$this->field_alias});
return $data['bulk_number'];
}
}

View File

@@ -0,0 +1,97 @@
<?php
/**
* @file
* Views handler for a list of bulk codes based on a coupon
*/
/**
* Generate a list of the codes associated with this coupon
*/
class uc_coupon_handler_field_codes extends views_handler_field_prerender_list {
/**
* Define option default values.
*/
function option_definition() {
$options = parent::option_definition();
$options['max_num'] = array('default' => 0);
$options['scope'] = array('default' => 'all');
return $options;
}
/**
* Provide options to limit number of codes, and to limit to coupons which still have uses remaining (or which don't)
*/
function options_form(&$form, &$form_state) {
parent::options_form($form, $form_state);
$form['max_num'] = array(
'#title' => t('Maximum number of codes to list (or 0 for unlimited)'),
'#type' => 'textfield',
'#default_value' => $this->options['max_num'],
);
$form['scope'] = array(
'#type' => 'radios',
'#title' => t('Codes to display'),
'#options' => array(
'all' => t('All'),
'avail' => t('Available codes'),
'used' => t('Unavailable codes'),
),
'#default_value' => $this->options['scope'],
);
}
/**
* Expand the coupon codes for each coupon in the result set.
*
* @see views_handler_field::pre_render()
*/
function pre_render($values) {
foreach ($values as $value) {
$cid = $value->{$this->field_alias};
$coupon = uc_coupon_load($cid);
// Find the maximum number of codes to display.
$limit = $coupon->bulk ? $coupon->data['bulk_number'] : 1;
if ($this->options['max_num'] && $this->options['max_num'] < $limit) {
$limit = $this->options['max_num'];
}
$coupon->usage = uc_coupon_count_usage($cid);
// List selected coupons.
for ($i = 0; $i < $limit; $i++) {
$icoupon = $limit > 1 ? clone $coupon : $coupon;
if ($coupon->bulk) {
$icoupon->code = uc_coupon_get_bulk_code($coupon, $i);
}
if ($this->include_coupon($icoupon)) {
$this->items[$cid][] = array('coupon' => $icoupon);
}
}
}
}
function include_coupon($coupon) {
if ($this->options['scope'] == 'all') {
return TRUE;
}
else {
$uses = $coupon->usage['codes'][$coupon->code];
$unused = $coupon->max_uses == 0 || $coupon->max_uses > $uses;
return $unused xor $this->options['scope'] == 'used';
}
}
/**
* Render a single coupon code.
*/
function render_item($count, $item) {
return theme('uc_coupon_code', array('coupon' => $item['coupon']));
}
}

View File

@@ -0,0 +1,17 @@
<?php
// $Id$
/**
* @file
* Coupon order total field handler
*/
class uc_coupon_handler_field_gross extends uc_views_handler_field_money_amount {
function query() {
$this->ensure_my_table();
$this->query->ensure_table('uc_orders');
$this->field_alias = $this->query->add_field(NULL, '(uc_orders.order_total + uc_coupons_orders.value)',
$this->table_alias .'_'. $this->field
);
}
}

View File

@@ -0,0 +1,24 @@
<?php
/**
* @file
* Views handler for coupon applicable product type
*/
/**
* List the product types applicable to this coupon
*/
class uc_coupon_handler_field_product_type extends views_handler_field_prerender_list {
function pre_render($values) {
$this->items = array();
foreach ($values as $value) {
$cid = $value->{$this->field_alias};
$data = unserialize($value->{$this->aliases['data']});
if (isset($data['product_types'])) {
$this->items[$cid] = $data['product_types'];
}
else {
$this->items[$cid] = array(t('Any'));
}
}
}
}

View File

@@ -0,0 +1,18 @@
<?php
/**
* @file
* Views handler: Coupon value field.
*/
/**
* Return a coupon value as price or percentage.
*/
class uc_coupon_handler_field_value extends views_handler_field_numeric {
function render($values) {
$coupon = new stdClass;
$coupon->value = $values->{$this->field_alias};
$coupon->type = $values->{$this->aliases['type']};
return theme('uc_coupon_discount', array('coupon' => $coupon));
}
}

View File

@@ -0,0 +1,23 @@
<?php
// $Id$
/**
* @file
* Filter based on coupon order gross (total+value)
*/
class uc_coupon_handler_filter_gross extends views_handler_filter_numeric {
function query() {
$this->ensure_my_table();
$uco = $this->query->ensure_table('uc_orders');
$uc = $this->table_alias;
$field = "($uco.order_total + $uc.value)";
$info = $this->operators();
if (!empty($info[$this->operator]['method'])) {
$this->{$info[$this->operator]['method']}($field);
}
}
}

View File

@@ -0,0 +1,30 @@
<?php
/**
* @file
* Views handler: Coupon filter on "product-type".
*/
/**
* Filter coupons based on what product types they apply to
*/
class uc_coupon_handler_filter_product_type extends views_handler_filter_in_operator {
function get_value_options() {
$this->value_options = array();
foreach (module_invoke_all('uc_product_types') as $type) {
$this->value_options[$type] = $type;
}
}
function query() {
$this->query->add_field('uc_coupons', 'data');
if (is_array($this->value) && count($this->value)) {
$search = implode("|", $this->value);
$regexp = ".*product_types.*{[^}]*($search).*}";
$this->query->add_where_expression($this->options['group'],
"uc_coupons.data " . ($this->options['operator'] !== 'in' ? "NOT " : "") . "REGEXP :re",
array(':re' => $regexp)
);
}
}
}