function __construct($controller, $name)
 {
     Requirements::javascript(ECOMMERCE_DIR . '/javascript/OrderFormWithShippingAddress.js');
     parent::__construct($controller, $name);
     if (self::$fixed_country_code) {
         $defaultCountry = self::$fixed_country_code;
     } else {
         $defaultCountry = EcommerceRole::find_country();
     }
     $countryField = new DropdownField('ShippingCountry', 'Country', Geoip::getCountryDropDown(), $defaultCountry, $this);
     $shippingFields = new Tab("ShippingDetails", new HeaderField('Delivery Address', 3, $this), new LiteralField('ShippingNote', '<p class="warningMessage"><em>Your goods will be sent to the address below.</em></p>'), new TextField('ShippingName', 'Name', null, 100, $this), new TextField('ShippingAddress', 'Address', null, 100, $this), new TextField('ShippingAddress2', '', null, 100, $this), new TextField('ShippingCity', 'City', null, 100, $this), $countryField);
     //$this->fields->push($shippingFields);
     $this->fields->addFieldToTab("", new CheckboxField("UseShippingAddress", "Use Alternative Delivery Address"));
     $this->fields->addFieldToTab("", $shippingFields);
     foreach ($this->fields->dataFields() as $i => $child) {
         if (is_object($child)) {
             $name = $child->Name();
             switch ($name) {
                 case "Address":
                     $child->setTitle('Address');
                     break;
                 default:
                     break;
             }
         }
     }
 }
 function run($request)
 {
     $customerGroup = EcommerceRole::get_customer_group();
     if ($customerGroup) {
         $allCombos = DB::query("\n\t\t\t\tSELECT \"Group_Members\".\"ID\", \"Group_Members\".\"MemberID\", \"Group_Members\".\"GroupID\"\n\t\t\t\tFROM \"Group_Members\"\n\t\t\t\tWHERE \"Group_Members\".\"GroupID\" = " . $customerGroup->ID . ";");
         //make an array of all combos
         $alreadyAdded = array();
         $alreadyAdded[-1] = -1;
         if ($allCombos) {
             foreach ($allCombos as $combo) {
                 $alreadyAdded[$combo["MemberID"]] = $combo["MemberID"];
             }
         }
         $unlistedMembers = DataObject::get("Member", $where = "\"Member\".\"ID\" NOT IN (" . implode(",", $alreadyAdded) . ")", $sort = "", $join = "INNER JOIN \"Order\" ON \"Order\".\"MemberID\" = \"Member\".\"ID\"");
         //add combos
         if ($unlistedMembers) {
             $existingMembers = $customerGroup->Members();
             foreach ($unlistedMembers as $member) {
                 $existingMembers->add($member);
                 DB::alteration_message("Added member to customers: " . $member->Email, "created");
             }
         }
     } else {
         DB::alteration_message("NO customer group found", "deleted");
     }
 }
 function testEcommerceRoleCreateOrMerge()
 {
     $member = $this->objFromFixture('Member', 'member1');
     $this->session()->inst_set('loggedInAs', $member->ID);
     $uniqueField = Member::get_unique_identifier_field();
     $this->assertEquals('*****@*****.**', $member->getField($uniqueField), 'The unique field is the email address');
     $this->assertEquals('US', $member->getField('Country'), 'The country is US');
     /* Change the email address to a new one (doesn't exist) */
     $member = EcommerceRole::createOrMerge(array('Country' => 'AU', $uniqueField => '*****@*****.**'));
     $this->assertType('object', $member, 'The member is an object, not FALSE');
     $this->assertEquals('*****@*****.**', $member->getField($uniqueField), 'The unique field is changed (no member with that email)');
     $this->assertEquals('AU', $member->getField('Country'), 'The member country is now AU');
     /* Change the data (update existing record - logged in member owns this email) */
     $member = EcommerceRole::createOrMerge(array('Country' => 'NZ', $uniqueField => '*****@*****.**'));
     $this->assertType('object', $member, 'The member is an object, not FALSE');
     $this->assertEquals('*****@*****.**', $member->getField($uniqueField), 'The unique field is the same (updated own record)');
     $this->assertEquals('NZ', $member->getField('Country'), 'The member country is now NZ');
     /* Change the email address to one exists (we should not get a member back when trying to merge!) */
     $member = EcommerceRole::createOrMerge(array('Country' => 'US', $uniqueField => '*****@*****.**'));
     $this->assertFalse($member, 'No member returned because we tried to merge an email that already exists in the DB');
     /* Log the member out */
     $this->session()->inst_set('loggedInAs', null);
     /* Non-logged in site user creating a new member with email that doesn't exist */
     $member = EcommerceRole::createOrMerge(array('Country' => 'NZ', $uniqueField => '*****@*****.**'));
     $this->assertType('object', $member, 'The member is an object, not FALSE');
     $this->assertEquals('*****@*****.**', $member->getField($uniqueField));
     $this->assertEquals('NZ', $member->getField('Country'), 'The member country is NZ');
     /* Non-logged in site user creating a member with email that DOES exist */
     $member = EcommerceRole::createOrMerge(array('Country' => 'AU', $uniqueField => '*****@*****.**'));
     $this->assertFalse($member, 'The new user tried to create a member with an email that already exists, FALSE returned');
     $member = EcommerceRole::createOrMerge(array('Country' => 'AU', $uniqueField => '*****@*****.**'));
     $this->assertFalse($member, 'Even if the email has a different case, FALSE is still returned');
 }
 function run($request)
 {
     $customerGroup = EcommerceRole::get_customer_group();
     if ($customerGroup) {
         $allCombos = DB::query("\n\t\t\t\tSELECT \"Group_Members\".\"ID\", \"Group_Members\".\"MemberID\", \"Group_Members\".\"GroupID\"\n\t\t\t\tFROM \"Group_Members\"\n\t\t\t\tWHERE \"Group_Members\".\"GroupID\" = " . $customerGroup->ID . ";");
         //make an array of all combos
         $alreadyAdded = array();
         $alreadyAdded[-1] = -1;
         if ($allCombos) {
             foreach ($allCombos as $combo) {
                 $alreadyAdded[$combo["MemberID"]] = $combo["MemberID"];
             }
         }
         $unlistedMembers = Member::get()->exclude(array("ID" => $alreadyAdded))->innerJoin("Order", "\"Order\".\"MemberID\" = \"Member\".\"ID\"");
         //add combos
         if ($unlistedMembers->count()) {
             $existingMembers = $customerGroup->Members();
             foreach ($unlistedMembers as $member) {
                 $existingMembers->add($member);
                 DB::alteration_message("Added member to customers: " . $member->Email, "created");
             }
         }
     } else {
         DB::alteration_message("NO customer group found", "deleted");
     }
 }
 function AddMemberToCartForm()
 {
     $member = Member::currentUser();
     $order = ShoppingCart::current_order();
     $currentCustomer = $order->CreateOrReturnExistingMember(false);
     if ($member && $member->IsShopAdmin()) {
         $fields = new FieldList(new HeaderField("SelectCustomer", _t("AddToCartPage.SELECTCUSTOMER", "Select Customer")), new ReadonlyField("CurrentMember", _t("AddToCartPage.CURRENTCUSTOMER", "Current"), $currentCustomer->getTitle()), new DropdownField("MemberID", _t("AddToCartPage.CUSTOMER", "Change to"), EcommerceRole::list_of_customers(), $currentCustomer->ID));
         $actions = new FieldList(new FormAction("addmembertocartform_add", _t("AddToCartPage.ADDMEMBERTOORDER", "Update customer")));
         $validator = new RequiredFields(array("MemberID"));
         return new Form($this, "AddMemberToCartForm", $fields, $actions, $validator);
     }
 }
示例#6
0
 /**
  * standard SS method
  * adds the ability to update order after writing it.
  **/
 function onAfterWrite()
 {
     parent::onAfterWrite();
     if ($this->IsSubmitted()) {
         //do nothing
     } else {
         if ($this->StatusID) {
             $this->calculateOrderAttributes();
             if (EcommerceRole::current_member_is_shop_admin()) {
                 if (isset($_REQUEST["SubmitOrderViaCMS"])) {
                     $this->tryToFinaliseOrder();
                     //just in case it writes again...
                     unset($_REQUEST["SubmitOrderViaCMS"]);
                 }
             }
         }
     }
 }
 static function associate_to_current_order($associate = true)
 {
     self::$associate_to_current_order = $associate;
 }
    /** 
     * Process the items in the shopping cart from session,
     * creating a new {@link Order} record, and updating the
     * customer's details {@link Member} record.
     * 
     * {@link Payment} instance is created, linked to the order,
     * and payment is processed {@link Payment::processPayment()}
     * 
     * @param array $data Form request data submitted from OrderForm
     * @param Form $form Form object for this action
     * @param HTTPRequest $request Request object for this action
     */
    function processOrder($data, $form, $request)
    {
        $paymentClass = !empty($data['PaymentMethod']) ? $data['PaymentMethod'] : null;
        $payment = class_exists($paymentClass) ? new $paymentClass() : null;
        if (!($payment && $payment instanceof Payment)) {
            user_error(get_class($payment) . ' is not a valid Payment object!', E_USER_ERROR);
        }
        if (!ShoppingCart::has_items()) {
            $form->sessionMessage('Please add some items to your cart', 'bad');
            Director::redirectBack();
            return false;
        }
        // Create new OR update logged in {@link Member} record
        $member = EcommerceRole::createOrMerge($data);
        if (!$member) {
            $form->sessionMessage(_t('OrderForm.MEMBEREXISTS', 'Sorry, a member already exists with that email address.
					If this is your email address, please log in first before placing your order.'), 'bad');
            Director::redirectBack();
            return false;
        }
        $member->write();
        $member->logIn();
        // Create new Order from shopping cart, discard cart contents in session
        $order = ShoppingCart::save_current_order();
        ShoppingCart::clear();
        // Write new record {@link Order} to database
        $form->saveInto($order);
        $order->write();
        // Save payment data from form and process payment
        $form->saveInto($payment);
        $payment->OrderID = $order->ID;
        $payment->Amount = $order->Total();
        $payment->write();
        // Process payment, get the result back
        $result = $payment->processPayment($data, $form);
        // isProcessing(): Long payment process redirected to another website (PayPal, Worldpay)
        if ($result->isProcessing()) {
            return $result->getValue();
        }
        if ($result->isSuccess()) {
            $order->sendReceipt();
        }
        Director::redirect($order->Link());
        return true;
    }
Order::set_receipt_subject("Shop Sale Information #%d");
Order::set_modifiers(array(), true);
Order::set_table_overview_fields(array('ID' => 'Order No', 'Created' => 'Created', 'FirstName' => 'First Name', 'Surname' => 'Surname', 'Total' => 'Total', 'Status' => 'Status'));
Order::set_maximum_ignorable_sales_payments_difference(0.01);
Order::set_order_id_start_number(0);
Order::set_cancel_before_payment(true);
Order::set_cancel_before_processing(false);
Order::set_cancel_before_sending(false);
Order::set_cancel_after_sending(false);
OrderForm::set_user_membership_optional(false);
OrderForm::set_force_membership(true);
OrderManipulation::set_allow_cancelling(false);
OrderManipulation::set_allow_paying(false);
// * * * PRODUCTS
ProductsAndGroupsModelAdmin::set_managed_models(array("Product", "ProductGroup", "ProductVariation", "ProductAttributeType"));
Product_Image::set_thumbnail_size(140, 100);
Product_Image::set_content_image_width(200);
Product_Image::set_large_image_width(200);
ProductGroup::set_include_child_groups(true);
ProductGroup::set_must_have_price(true);
ProductGroup::set_sort_options(array('Title' => 'Alphabetical', 'Price' => 'Lowest Price'));
// * * * CHECKOUT
ExpiryDateField::set_short_months(true);
OrderFormWithoutShippingAddress::set_fixed_country_code(null);
OrderFormWithoutShippingAddress::set_postal_code_url("http://www.nzpost.co.nz/Cultures/en-NZ/OnlineTools/PostCodeFinder");
OrderFormWithoutShippingAddress::set_postal_code_label("find postcode");
OrderFormWithoutShippingAddress::set_login_invite_alternative_text('Please <a href="Security/login?BackURL=/">log in now</a> to retrieve your account details or create an account below.');
// * * * MEMBER
EcommerceRole::set_group_name("Shop Customers");
// * * * HELP
Product::set_global_allow_purchase(true);
示例#10
0
 /**
  * Returns the correct shipping address. If there is an alternate
  * shipping country then it uses that. Failing that, it returns
  * the country of the member.
  *
  * @TODO This is pretty complicated code. It can be simplified.
  *
  * @param boolean $codeOnly If true, returns only the country code, instead
  * 								of the full name.
  * @return string
  */
 function findShippingCountry($codeOnly = false)
 {
     if (!$this->ID) {
         $country = ShoppingCart::has_country() ? ShoppingCart::get_country() : EcommerceRole::find_country();
     } elseif (!$this->UseShippingAddress || !($country = $this->ShippingCountry)) {
         $country = EcommerceRole::find_country();
     }
     return $codeOnly ? $country : EcommerceRole::find_country_title($country);
 }
 function run($request)
 {
     $customerGroup = EcommerceRole::get_customer_group();
     $customerPermissionCode = EcommerceConfig::get("EcommerceRole", "customer_permission_code");
     if (!$customerGroup) {
         $customerGroup = new Group();
         $customerGroup->Code = EcommerceConfig::get("EcommerceRole", "customer_group_code");
         $customerGroup->Title = EcommerceConfig::get("EcommerceRole", "customer_group_name");
         $customerGroup->write();
         Permission::grant($customerGroup->ID, $customerPermissionCode);
         DB::alteration_message(EcommerceConfig::get("EcommerceRole", "customer_group_name") . ' Group created', "created");
     } elseif (DB::query("SELECT * FROM \"Permission\" WHERE \"GroupID\" = '" . $customerGroup->ID . "' AND \"Code\" LIKE '" . $customerPermissionCode . "'")->numRecords() == 0) {
         Permission::grant($customerGroup->ID, $customerPermissionCode);
         DB::alteration_message(EcommerceConfig::get("EcommerceRole", "customer_group_name") . ' permissions granted', "created");
     }
     $customerGroup = EcommerceRole::get_customer_group();
     if (!$customerGroup) {
         user_error("could not create user group");
     } else {
         DB::alteration_message(EcommerceConfig::get("EcommerceRole", "customer_group_name") . ' is ready for use', "created");
     }
     $adminGroup = EcommerceRole::get_admin_group();
     $adminCode = EcommerceConfig::get("EcommerceRole", "admin_group_code");
     $adminName = EcommerceConfig::get("EcommerceRole", "admin_group_name");
     $adminPermissionCode = EcommerceConfig::get("EcommerceRole", "admin_permission_code");
     $adminRoleTitle = EcommerceConfig::get("EcommerceRole", "admin_role_title");
     if (!$adminGroup) {
         $adminGroup = new Group();
         $adminGroup->Code = $adminCode;
         $adminGroup->Title = $adminName;
         $adminGroup->write();
         Permission::grant($adminGroup->ID, $adminPermissionCode);
         DB::alteration_message($adminName . ' Group created', "created");
     } elseif (DB::query("SELECT * FROM \"Permission\" WHERE \"GroupID\" = '" . $adminGroup->ID . "' AND \"Code\" LIKE '" . $adminPermissionCode . "'")->numRecords() == 0) {
         Permission::grant($adminGroup->ID, $adminPermissionCode);
         DB::alteration_message($adminName . ' permissions granted', "created");
     }
     $permissionRole = DataObject::get_one("PermissionRole", "\"Title\" = '" . $adminRoleTitle . "'");
     if (!$permissionRole) {
         $permissionRole = new PermissionRole();
         $permissionRole->Title = $adminRoleTitle;
         $permissionRole->OnlyAdminCanApply = true;
         $permissionRole->write();
     }
     if ($permissionRole) {
         $permissionArray = EcommerceConfig::get("EcommerceRole", "admin_role_permission_codes");
         if (is_array($permissionArray) && count($permissionArray) && $permissionRole) {
             foreach ($permissionArray as $permissionCode) {
                 $permissionRoleCode = DataObject::get_one("PermissionRoleCode", "\"Code\" = '{$permissionCode}'");
                 if (!$permissionRoleCode) {
                     $permissionRoleCode = new PermissionRoleCode();
                     $permissionRoleCode->Code = $permissionCode;
                     $permissionRoleCode->RoleID = $permissionRole->ID;
                     $permissionRoleCode->write();
                 }
             }
         }
         if ($adminGroup) {
             $existingGroups = $permissionRole->Groups();
             $existingGroups->add($adminGroup);
         }
     }
 }
 private function createshopadmin()
 {
     $member = new Member();
     $member->FirstName = 'Shop';
     $member->Surname = 'Admin';
     $member->Email = '*****@*****.**';
     $member->SetPassword = '******';
     $member->Password = '******';
     $member->write();
     $group = EcommerceRole::get_admin_group();
     $member->Groups()->add($group);
 }
 /**
  * Only shop admin can delete this
  *@return Boolean
  **/
 public function canDelete($member = null)
 {
     return EcommerceRole::current_member_is_shop_admin($member);
 }
 /**
  * Finds or creates a current order.
  * @todo split this into two functions: initcart, and currentcart...so that templates can return null for Cart
  */
 public static function current_order()
 {
     if (self::$order) {
         return self::$order;
     }
     //we only want to hit the database once
     //find order by id saved to session (allows logging out and retaining cart contents)
     $cartid = Session::get(self::$cartid_session_name);
     //TODO: make clear cart on logout optional
     if ($cartid && ($o = DataObject::get_one('Order', "\"Status\" = 'Cart' AND \"ID\" = {$cartid}"))) {
         $order = $o;
     } else {
         $order = new Order();
         $order->SessionID = session_id();
         if (EcommerceRole::get_associate_to_current_order()) {
             $order->MemberID = Member::currentUserID();
         }
         // Set the Member relation to this order
         $order->write();
         Session::set(self::$cartid_session_name, $order->ID);
         //init modifiers the first time the order is created
         // (currently assumes modifiers won't change)
     }
     self::$order = $order;
     //temp caching
     $order->initModifiers();
     //init /re-init modifiers
     $order->write();
     // Write the order
     return $order;
 }
 /**
  * standard SS method
  * Make sure the member is added as a customer
  */
 public function onAfterWrite()
 {
     $customerGroup = EcommerceRole::get_customer_group();
     if ($customerGroup) {
         $existingMembers = $customerGroup->Members();
         if ($existingMembers) {
             $existingMembers->add($this->owner);
         }
     }
 }
 protected function LiveCountry()
 {
     return EcommerceRole::findCountry();
 }
    /**
     * Process the items in the shopping cart from session,
     * creating a new {@link Order} record, and updating the
     * customer's details {@link Member} record.
     *
     * {@link Payment} instance is created, linked to the order,
     * and payment is processed {@link Payment::processPayment()}
     *
     * @param array $data Form request data submitted from OrderForm
     * @param Form $form Form object for this action
     * @param HTTPRequest $request Request object for this action
     */
    function processOrder($data, $form, $request)
    {
        $paymentClass = !empty($data['PaymentMethod']) ? $data['PaymentMethod'] : null;
        $payment = class_exists($paymentClass) ? new $paymentClass() : null;
        if (!($payment && $payment instanceof Payment)) {
            user_error(get_class($payment) . ' is not a valid Payment object!', E_USER_ERROR);
            //TODO: be more graceful with errors
        }
        $this->saveDataToSession($data);
        //save for later if necessary
        //check for cart items
        if (!ShoppingCart::has_items()) {
            $form->sessionMessage(_t('OrderForm.NoItemsInCart', 'Please add some items to your cart'), 'bad');
            Director::redirectBack();
            return false;
        }
        //check that price hasn't changed
        $oldtotal = ShoppingCart::current_order()->Total();
        // Create new Order from shopping cart, discard cart contents in session
        $order = ShoppingCart::current_order();
        if ($order->Total() != $oldtotal) {
            $form->sessionMessage(_t('OrderForm.PriceUpdated', 'The order price has been updated'), 'warning');
            Director::redirectBack();
            return false;
        }
        $member = Member::currentUser();
        if (!$member) {
            if (self::$user_membership_optional) {
                if ($this->userWantsToBecomeMember($data, $form)) {
                    $member = EcommerceRole::ecommerce_create_or_merge($data);
                }
                //otherwise we assume they don't want to become a member
            } elseif (self::$force_membership) {
                //create member
                $member = EcommerceRole::ecommerce_create_or_merge($data);
            }
        }
        //if they are a member, or if they have filled out the member fields (password, save my details)
        // Create new OR update logged in {@link Member} record
        if ($member === false) {
            $form->sessionMessage(_t('OrderForm.MEMBEREXISTS', 'Sorry, a member already exists with that email address.
					If this is your email address, please log in first before placing your order.' . ' <a href="Security/lostpassword">Recover password.</a>'), 'bad');
            Director::redirectBack();
            return false;
        }
        //assiciate member with order, if there is a member now
        if ($member) {
            $member->write();
            $member->logIn();
            if ($member) {
                $payment->PaidByID = $member->ID;
            }
            $order->MemberID = $member->ID;
        }
        // Write new record {@link Order} to database
        $form->saveInto($order);
        $order->save();
        //sets status to 'Unpaid' //is it even necessary to have it's own function? ..just legacy code.
        $this->clearSessionData();
        //clears the stored session form data that might have been needed if validation failed
        // Save payment data from form and process payment
        $form->saveInto($payment);
        $payment->OrderID = $order->ID;
        $payment->PaidForID = $order->ID;
        $payment->PaidForClass = $order->class;
        $payment->Amount->Amount = $order->Total();
        $payment->write();
        //prepare $data - ie put into the $data array any fields that may need to be there for payment
        // Process payment, get the result back
        $result = $payment->processPayment($data, $form);
        // isProcessing(): Long payment process redirected to another website (PayPal, Worldpay)
        if ($result->isProcessing()) {
            return $result->getValue();
        }
        if ($result->isSuccess()) {
            $order->sendReceipt();
        }
        Director::redirect($order->Link());
        return true;
    }