class ImportXliffForm(formbase.PageForm): """ Form for importing xliff """ form_fields = form.FormFields(IImportParams) label = u'Import Xliff' form_name = _(u"Import Xliff") template = pagetemplatefile.ZopeTwoPageTemplateFile( 'templates/import_xliff.pt') def __call__(self): self.request.set('disable_border', True) return super(ImportXliffForm, self).__call__() @form.action(u'Import') def action_import(self, action, data): context = aq_inner(self.context) file = self.request.get('form.file') xliffimporter = getUtility(IXLIFFImporter) errors = xliffimporter.upload(file, html_compatibility=False) if errors != []: error = ["%s: %s" % x for x in errors] confirm = _(u"Error while importing Xliff.\n " + "\n".join(error)) IStatusMessage(self.request).addStatusMessage(confirm, type='warn') else: confirm = _(u"Xliff import successful.") IStatusMessage(self.request).addStatusMessage(confirm, type='info') self.request.response.redirect(context.absolute_url() + '/@@xliffimport') return ''
class UserAddForm(formbase.AddForm): """ """ template = pagetemplatefile.ZopeTwoPageTemplateFile("user.pt") form_fields = form.Fields(IUserAddForm) label = _(u"Add User") form_name = _(u"Add User") @form.action(_(u"label_save", default=u"Save"), condition=form.haveInputWidgets, name=u'save') def handle_save_action(self, action, data): """ """ self.createAndAdd(data) def createAndAdd(self, data): """ """ username = data.get("username") username = username.encode( "utf-8") # rtool doesn't understand unicode. password = data.get("password_1") request = self.context.REQUEST rtool = getToolByName(self.context, "portal_registration") rtool.addMember(username, password) utool = getToolByName(self.context, "portal_url") portal_url = utool.getPortalObject().absolute_url() # Plone's logged_in script (see below) redirects to given came_from, # hence we just have to pass the next url to it to get to the next url # within the checkout process. came_from = ICheckoutManagement( self.context).getNextURL("AFTER_ADDED_USER") parameters = { "came_from": came_from, "__ac_name": username, "__ac_password": password, "form.submitted": "1", "js_enabled": "1", "cookies_enabled": "1", "login_name": username, "pwd_empty": "0", } temp = [] for key, value in parameters.items(): if value != "": temp.append("%s=%s" % (key, value)) url = "%s/logged_in?%s" % (portal_url, "&".join(temp)) request.RESPONSE.redirect(url)
class BankAccountAddForm(base.AddForm): """ """ template = pagetemplatefile.ZopeTwoPageTemplateFile(DEFAULT_SHOP_FORM) form_fields = form.Fields(IBankAccount) label = _(u"Add Bank Information") form_name = _(u"Add Bank Information") @form.action(_(u"label_save", default=u"Save"), condition=form.haveInputWidgets, name=u'save') def handle_save_action(self, action, data): """ """ self.createAndAdd(data) @form.action(_(u"label_cancel", default=u"Cancel"), validator=null_validator, name=u'cancel') def handle_cancel_action(self, action, data): """ """ self.context.reindexObject() self.nextUrl() def createAndAdd(self, data): """ """ # add address id = self.context.generateUniqueId("BankAccount") direct_debit = BankAccount(id) direct_debit.account_number = data.get("account_number") direct_debit.bank_identification_code = data.get( "bank_identification_code") direct_debit.depositor = data.get("depositor") direct_debit.bank_name = data.get("bank_name") self.context._setObject(id, direct_debit) direct_debit.reindexObject() self.nextUrl() def nextUrl(self): """ """ url = self.request.get("goto", "") if url != "": self.request.response.redirect(url) else: url = self.context.absolute_url() + "/manage-payment-methods" self.request.response.redirect(url)
class CustomerEditForm(base.EditForm): """ """ template = pagetemplatefile.ZopeTwoPageTemplateFile(DEFAULT_SHOP_FORM) form_fields = form.Fields(ICustomer) label = _(u"Edit Customer") description = _("Please edit the form below and press save.") form_name = _(u"Edit Customer") @form.action(_(u"label_save", default="Save"), condition=form.haveInputWidgets, name=u'save') def handle_save_action(self, action, data): """ """ utils = getToolByName(self.context, "plone_utils") utils.addPortalMessage(_(u"Changes saved"), "info") if form.applyChanges(self.context, self.form_fields, data, self.adapters): zope.event.notify( zope.lifecycleevent.ObjectModifiedEvent(self.context)) zope.event.notify(EditSavedEvent(self.context)) else: zope.event.notify(EditCancelledEvent(self.context)) self.context.reindexObject() self._nextUrl() @form.action(_(u"label_cancel", default=u"Cancel"), validator=null_validator, name=u'cancel') def handle_cancel_action(self, action, data): """ """ utils = getToolByName(self.context, "plone_utils") utils.addPortalMessage(_(u"Edit canceled"), "info") zope.event.notify(EditCancelledEvent(self.context)) self._nextUrl() def _nextUrl(self): """ """ url = self.request.get("goto", "") if url != "": self.request.response.redirect(url) else: url = self.context.absolute_url() url += "/my-account" self.request.response.redirect(url)
class AddressEditForm(base.EditForm): """ """ template = pagetemplatefile.ZopeTwoPageTemplateFile(DEFAULT_SHOP_FORM) form_fields = form.Fields(IAddress).omit("email") label = _(u"Edit Address") description = _("To change your address edit the form and press save.") form_name = _(u"Edit Address") @form.action(_(u"label_save", default="Save"), condition=form.haveInputWidgets, name=u'save') def handle_save_action(self, action, data): """ """ if form.applyChanges(self.context, self.form_fields, data, self.adapters): notify(ObjectModifiedEvent(self.context)) notify(EditSavedEvent(self.context)) self.status = "Changes saved" else: notify(EditCancelledEvent(self.context)) self.status = "No changes" self.context.reindexObject() self.context.aq_inner.aq_parent.reindexObject() self.redirectToNextURL() @form.action(_(u"label_cancel", default=u"Cancel"), validator=null_validator, name=u'cancel') def handle_cancel_action(self, action, data): """ """ notify(EditCancelledEvent(self.context)) self.redirectToNextURL() def redirectToNextURL(self): """ """ url = self.request.get("goto", "") if url != "": self.request.response.redirect(url) else: customer = self.context.aq_inner.aq_parent url = "%s/manage-addressbook" % customer.absolute_url() self.request.response.redirect(url)
class BankAccountEditForm(base.EditForm): """ """ template = pagetemplatefile.ZopeTwoPageTemplateFile(DEFAULT_SHOP_FORM) form_fields = form.Fields(IBankAccount) label = _(u"Edit Bank Account") description = _( "To change your bank information edit the form and press save.") form_name = _(u"Edit Bank Account") @form.action(_(u"label_save", default="Save"), condition=form.haveInputWidgets, name=u'save') def handle_save_action(self, action, data): """ """ if form.applyChanges(self.context, self.form_fields, data, self.adapters): notify(ObjectModifiedEvent(self.context)) notify(EditSavedEvent(self.context)) self.status = "Changes saved" else: notify(EditCancelledEvent(self.context)) self.status = "No changes" self.context.reindexObject() self.nextUrl() @form.action(_(u"label_cancel", default=u"Cancel"), validator=null_validator, name=u'cancel') def handle_cancel_action(self, action, data): """ """ notify(EditCancelledEvent(self.context)) self.nextUrl() def nextUrl(self): """ """ url = self.request.get("goto", "") if url != "": self.request.response.redirect(url) else: parent = self.context.aq_inner.aq_parent url = parent.absolute_url() + "/manage-payment-methods" self.request.response.redirect(url)
class MigratePagesForm(formbase.PageForm): form_fields = form.FormFields(IMigrate) result_template = pagetemplatefile.ZopeTwoPageTemplateFile('migration-results.pt') @form.action("Migrate") def action_migrate(self, action, data): urls = data['urls'].split() migrater = PageMigrater(self.context) migrater.migrate_pages(urls, data['root_url']) self.log = migrater.get_log() self.errors = migrater.get_errors() return self.result_template()
class ShippingSelectForm(formbase.EditForm): """ """ template = pagetemplatefile.ZopeTwoPageTemplateFile("shipping.pt") form_fields = form.Fields(IShippingSelectForm) @form.action(_(u"label_next", default="Next"), condition=form.haveInputWidgets, name=u'next') def handle_next_action(self, action, data): """ """ customer = ICustomerManagement(self.context).getAuthenticatedCustomer() customer.selected_shipping_method = data.get("shipping_method", "") ICheckoutManagement( self.context).redirectToNextURL("SELECTED_SHIPPING_METHOD") def getShippingMethods(self): """ """ customer = ICustomerManagement(self.context).getAuthenticatedCustomer() selected_shipping_id = customer.selected_shipping_method sm = IShippingMethodManagement(self.context) shipping_methods = [] for shipping in sm.getShippingMethods(): if selected_shipping_id == safe_unicode(shipping.getId()): checked = True elif selected_shipping_id == u"" and shipping.getId( ) == "standard": checked = True else: checked = False shipping_methods.append({ "id": shipping.getId(), "title": shipping.Title, "description": shipping.Description, "checked": checked, }) return shipping_methods
class AddressAddForm(base.AddForm): """ """ template = pagetemplatefile.ZopeTwoPageTemplateFile(DEFAULT_SHOP_FORM) form_fields = form.Fields(IAddress).omit("email") label = _(u"Add Address") form_name = _(u"Add Address") @form.action(_(u"label_save", default=u"Save"), condition=form.haveInputWidgets, name=u'save') def handle_save_action(self, action, data): """ """ self.createAndAdd(data) @form.action(_(u"label_cancel", default=u"Cancel"), validator=null_validator, name=u'cancel') def handle_cancel_action(self, action, data): """ """ self.redirectToNextURL() def createAndAdd(self, data): """ """ am = IAddressManagement(self.context) am.addAddress(data) self.redirectToNextURL() def redirectToNextURL(self): """ """ url = self.request.get("goto", "") if url != "": self.request.response.redirect(url) else: url = "%s/manage-addressbook" % self.context.absolute_url() self.request.response.redirect(url)
class AddressEditForm(base.EditForm): """This form let anonymous users edit their already entered invoice and shipping address. This happens when they click checkout again and they have already entered addresses within the same sessions. """ template = pagetemplatefile.ZopeTwoPageTemplateFile("address_form.pt") form_fields = form.Fields(IAddress) label = _(u"Edit Address") description = _("To change your address edit the form and press save.") form_name = _(u"Edit Address") @form.action(_(u"label_save", default="Save"), condition=form.haveInputWidgets, name=u'save') def handle_save_action(self, action, data): """ """ if form.applyChanges(self.context, self.form_fields, data, self.adapters): notify(ObjectModifiedEvent(self.context)) notify(EditSavedEvent(self.context)) self.status = "Changes saved" else: notify(EditCancelledEvent(self.context)) self.status = "No changes" shop = IShopManagement(self.context).getShop() ICheckoutManagement(shop).redirectToNextURL("EDITED_ADDRESS") def getAddressType(self): """ """ return self.request.get("address_type", "shipping") def isShippingAddress(self): """ """ return self.getAddressType() == "shipping"
class AddressSelectForm(formbase.EditForm): """ """ template = pagetemplatefile.ZopeTwoPageTemplateFile("address_select.pt") form_fields = form.Fields(IAddressSelectForm) @form.action(_(u"label_next", default="Next"), condition=form.haveInputWidgets, name=u'next') def handle_next_action(self, action, data): """ """ customer = ICustomerManagement(self.context).getAuthenticatedCustomer() customer.selected_invoice_address = data.get("invoice_address", "") customer.selected_shipping_address = data.get("shipping_address", "") ICheckoutManagement( self.context).redirectToNextURL("SELECTED_ADDRESSES") @form.action(_(u"label_add_address", default="Add Address"), name=u'add_address') def handle_add_address_action(self, action, data): """ """ customer = ICustomerManagement(self.context).getAuthenticatedCustomer() customer_url = customer.absolute_url() template_url = self.context.absolute_url( ) + "/checkout-select-addresses" url = customer_url + "/add-address?goto=" + template_url self.request.response.redirect(url) def getShippingAddresses(self): """Returns all addresses with the currently selected invoice address checked. """ customer = ICustomerManagement(self.context).getAuthenticatedCustomer() am = IAddressManagement(customer) found_selected_address = False result = [] line = [] for index, address in enumerate(am.getAddresses()): checked = False if safe_unicode( address.getId()) == customer.selected_shipping_address: checked = "checked" found_selected_address = True address_as_dict = self._getAddressAsDict(address) address_as_dict["checked"] = checked line.append(address_as_dict) if (index + 1) % 3 == 0: result.append(line) line = [] result.append(line) if len(result) > 0 and found_selected_address == False: result[0][0]["checked"] = True return result def getInvoiceAddresses(self): """ """ customer = ICustomerManagement(self.context).getAuthenticatedCustomer() am = IAddressManagement(customer) found_selected_address = False result = [] line = [] for index, address in enumerate(am.getAddresses()): checked = False if safe_unicode( address.getId()) == customer.selected_invoice_address: checked = "checked" found_selected_address = True address_as_dict = self._getAddressAsDict(address) address_as_dict["checked"] = checked line.append(address_as_dict) if (index + 1) % 3 == 0: result.append(line) line = [] result.append(line) if found_selected_address == False: result[0][0]["checked"] = True return result def _getAddressAsDict(self, address): """Returns given address as dictionary. """ return { "id": address.getId(), "url": address.absolute_url(), "firstname": address.firstname, "lastname": address.lastname, "companyname": address.company_name, "address1": address.address_1, "zipcode": address.zip_code, "city": address.city, "country": address.country_title(), "phone": address.phone, }
class PaymentForm(formbase.EditForm): """ """ template = pagetemplatefile.ZopeTwoPageTemplateFile("payment.pt") form_fields = form.Fields(IPaymentSelectForm) def validator(self, action, data): """ """ errors = [] if self.request.get("form.id") == "direct_debit_new": for widget_name in ("account_number", "depositor", "bank_name", "bank_identification_code"): if self.request.get("form.%s" % widget_name, u"") == u"": widget = self.widgets[widget_name] error = WidgetInputError( widget.name, widget.label, "%s" + _(u" is required" % widget.label)) widget._error = error errors.append(error) elif self.request.get("form.id") == "credit_card_new": for widget_name in ("card_type", "card_owner", "card_number"): if self.request.get("form.%s" % widget_name, u"") == u"": widget = self.widgets[widget_name] error = WidgetInputError( widget.name, widget.label, _(u"%s is required" % widget.label)) widget._error = error errors.append(error) return errors @form.action(_(u"label_next", default="Next"), validator=validator, name=u"next") def handle_next_action(self, action, data): """ """ customer = ICustomerManagement(self.context).getAuthenticatedCustomer() id = self.request.get("form.id") # figure out payment method type if id.startswith("bank_account"): payment_method = "direct-debit" elif id.startswith("credit_card"): payment_method = "credit-card" else: payment_method = id if id == "bank_account_new": depositor = self.request.get("form.depositor", u"") account_number = self.request.get("form.account_number", u"") bank_identification_code = self.request.get( "form.bank_identification_code", u"") bank_name = self.request.get("form.bank_name", u"") id = self.context.generateUniqueId("BankAccount") bank_account = BankAccount(id) bank_account.account_number = account_number bank_account.bank_identification_code = bank_identification_code bank_account.bank_name = bank_name bank_account.depositor = depositor customer._setObject(id, bank_account) if id == "credit_card_new": card_type = self.request.get("form.card_type", u"") card_number = self.request.get("form.card_number", u"") card_owner = self.request.get("form.card_owner", u"") card_expiration_date_month = self.request.get( "form.card_expiration_date_month", u"") card_expiration_date_year = self.request.get( "form.card_expiration_date_year", u"") id = self.context.generateUniqueId("CreditCard") credit_card = CreditCard(id) credit_card.card_type = card_type credit_card.card_number = card_number credit_card.card_owner = card_owner credit_card.card_expiration_date_month = card_expiration_date_month credit_card.card_expiration_date_year = card_expiration_date_year customer._setObject(id, credit_card) elif id.startswith("bank_account_existing") or \ id.startswith("credit_card_existing"): id = id.split(":")[1] customer.selected_payment_method = payment_method customer.selected_payment_information = id ICheckoutManagement( self.context).redirectToNextURL("SELECTED_PAYMENT_METHOD") def getCreditCards(self): """ """ if self._isValid("credit-card") == False: return [] cm = ICustomerManagement(self.context) customer = cm.getAuthenticatedCustomer() result = [] pm = IPaymentInformationManagement(customer) for credit_card in pm.getPaymentInformations(interface=ICreditCard, check_validity=True): selected_payment_information = \ pm.getSelectedPaymentInformation(check_validity=True) if selected_payment_information and \ selected_payment_information.getId() == credit_card.getId(): checked = True else: checked = False exp_date = "%s/%s" % (credit_card.card_expiration_date_month, credit_card.card_expiration_date_year) result.append({ "id": credit_card.getId(), "type": credit_card.card_type, "owner": credit_card.card_owner, "number": credit_card.card_number, "expiration_date": exp_date, "checked": checked, }) return result def getBankAccounts(self): """ """ if self._isValid("direct-debit") == False: return [] cm = ICustomerManagement(self.context) customer = cm.getAuthenticatedCustomer() result = [] pm = IPaymentInformationManagement(customer) for bank_account in pm.getPaymentInformations(interface=IBankAccount, check_validity=True): selected_payment_information = \ pm.getSelectedPaymentInformation(check_validity=True) if selected_payment_information and \ selected_payment_information.getId() == bank_account.getId(): checked = True else: checked = False result.append({ "id": bank_account.getId(), "bic": bank_account.bank_identification_code, "account_no": bank_account.account_number, "depositor": bank_account.depositor, "bank_name": bank_account.bank_name, "checked": checked, }) return result def getSelectablePaymentMethods(self): """Returns selectable payment methods. """ customer = ICustomerManagement(self.context).getAuthenticatedCustomer() pm = IPaymentInformationManagement(customer) selected_payment_method = \ pm.getSelectedPaymentMethod(check_validity=True) result = [] pm = IPaymentMethodManagement(self.context) for payment in pm.getSelectablePaymentMethods(check_validity=True): # Todo: Make default payment method editable. ATM it is prepayment. # So if nothing is selected checked is true for prepayment. # If id is bank_account_new (this happens when customer wants to # add a new direct debit and is due to validation errors redirected to # the form). checked = False if (self.request.get("form.id", "") not in ("bank_account_new", "credit_card_new")) and \ (selected_payment_method.getId() == safe_unicode(payment.getId())): checked = True result.append({ "id": payment.getId(), "title": payment.Title(), "description": payment.Description(), "checked": checked, }) return result def getClass(self, expression, true_value, false_value): """ """ if len(expression) > 0: return "widget error" else: return "widget" def showCreditCards(self): """ """ return self._isValid("credit-card") def showBankAccounts(self): """ """ return self._isValid("direct-debit") def _isValid(self, name): """Returns true if the payment method with given name is valid. """ spm = IPaymentMethodManagement(self.context) dd = spm.getPaymentMethod(name) if dd is None or IValidity(dd).isValid() == False: return False else: return True
class OrderPreviewForm(formbase.AddForm): """ """ template = pagetemplatefile.ZopeTwoPageTemplateFile("order_preview.pt") form_fields = form.Fields(IOrderPreviewForm) def validator(self, action, data): """ """ errors = [] if self.request.get("form.confirmation", "") == "": error_msg = _(u"Please confirm our terms and conditions.") widget = self.widgets["confirmation"] error = WidgetInputError(widget.name, widget.label, error_msg) widget._error = error widget.error = error_msg errors.append(error) return errors @form.action(_(u"label_buy", default=u"Buy"), validator=validator, name=u'buy') def handle_buy_action(self, action, data): """Buys a cart. """ putils = getToolByName(self.context, "plone_utils") # add order om = IOrderManagement(self.context) new_order = om.addOrder() # Set message to shop owner new_order.setMessage(self.context.request.get("form.message", "")) # process payment result = IPaymentProcessing(new_order).process() # Need error for payment methods for which the customer has to pay at # any case The order process should not go on if the customer is not # able to pay. if result.code == ERROR: om.deleteOrder(new_order.id) putils.addPortalMessage(result.message, type=u"error") ICheckoutManagement( self.context).redirectToNextURL("ERROR_PAYMENT") return "" else: cm = ICartManagement(self.context) # Decrease stock IStockManagement(self.context).removeCart(cm.getCart()) # Delete cart cm.deleteCart() # Set order to pending (Mails will be sent) wftool = getToolByName(self.context, "portal_workflow") wftool.doActionFor(new_order, "submit") putils.addPortalMessage(MESSAGES["ORDER_RECEIVED"]) if result.code == PAYED: # Set order to payed (Mails will be sent) wftool = getToolByName(self.context, "portal_workflow") # We need a new security manager here, because this transaction # should usually just be allowed by a Manager except here. old_sm = getSecurityManager() tmp_user = UnrestrictedUser(old_sm.getUser().getId(), '', ['Manager'], '') portal = getToolByName(self.context, 'portal_url').getPortalObject() tmp_user = tmp_user.__of__(portal.acl_users) newSecurityManager(None, tmp_user) wftool.doActionFor(new_order, "pay_not_sent") ## Reset security manager setSecurityManager(old_sm) # Redirect customer = \ ICustomerManagement(self.context).getAuthenticatedCustomer() selected_payment_method = \ IPaymentInformationManagement(customer).getSelectedPaymentMethod() if not IAsynchronPaymentMethod.providedBy(selected_payment_method): ICheckoutManagement(self.context).redirectToNextURL("BUYED_ORDER") def getVATRegistration(self): """Returns the VAT registration (if any) of the current customer. """ customer = ICustomerManagement(self.context).getAuthenticatedCustomer() vatreg = customer.getVATRegistration() return vatreg def getCartItems(self): """Returns the items of the current cart. """ cart = self._getCart() cm = ICurrencyManagement(self.context) im = IItemManagement(cart) result = [] for cart_item in im.getItems(): product = cart_item.getProduct() product_price = IPrices( cart_item).getPriceForCustomer() / cart_item.getAmount() product_price = cm.priceToString(product_price) price = IPrices(cart_item).getPriceForCustomer() # Todo: Think about to factoring out properties stuff # because same has to be uses there: cart.py / getCartItems() properties = [] pm = IPropertyManagement(product) for selected_property in cart_item.getProperties(): property_price = pm.getPriceForCustomer( selected_property["id"], selected_property["selected_option"]) # Get titles of property and option titles = getTitlesByIds(product, selected_property["id"], selected_property["selected_option"]) if titles is None: continue if IProductVariant.providedBy(product) == True: show_price = False else: show_price = True properties.append({ "id": selected_property["id"], "selected_option": titles["option"], "title": titles["property"], "price": cm.priceToString(property_price), "show_price": show_price, }) # Discount total_price = 0 discount = IDiscountsCalculation(cart_item).getDiscount() if discount is not None: discount_price = getMultiAdapter( (discount, cart_item)).getPriceForCustomer() discount = { "title": discount.Title(), "value": cm.priceToString(discount_price, prefix="-"), } total_price = price - discount_price # Data data = IData(product).asDict() result.append({ "product_title": data["title"], "product_price": product_price, "properties": properties, "price": cm.priceToString(price), "amount": cart_item.getAmount(), "total_price": cm.priceToString(total_price), "discount": discount, }) return result def getDiscounts(self): """ """ return [] cart = self._getCart() if cart is None: return [] cm = ICurrencyManagement(self.context) discounts = [] for cart_item in IItemManagement(cart).getItems(): discount = IDiscountsCalculation(cart_item).getDiscount() if discount is not None: value = getMultiAdapter( (discount, cart_item)).getPriceForCustomer() discounts.append({ "title": discount.Title(), "value": cm.priceToString(value, prefix="-"), }) return discounts def getInvoiceAddress(self): """Returns invoice address of the current customer. """ cm = ICustomerManagement(self.context) customer = cm.getAuthenticatedCustomer() am = IAddressManagement(customer) address = am.getInvoiceAddress() return addressToDict(address) def getSelectedPaymentInformation(self): """ """ customer = ICustomerManagement(self.context).getAuthenticatedCustomer() pm = IPaymentInformationManagement(customer) return pm.getSelectedPaymentInformation() def getPaymentMethodInfo(self): """ """ # method customer = ICustomerManagement(self.context).getAuthenticatedCustomer() selected_payment_method = customer.selected_payment_method pm = IPaymentMethodManagement(self.context) method = pm.getPaymentMethod(selected_payment_method) # price pp = IPaymentPriceManagement(self.context) payment_price = pp.getPriceGross() cm = ICurrencyManagement(self.context) price = cm.priceToString(payment_price) return { "type": method.portal_type, "title": method.Title(), "price": price, "display": payment_price != 0, } def getShippingAddress(self): """ """ cm = ICustomerManagement(self.context) customer = cm.getAuthenticatedCustomer() am = IAddressManagement(customer) address = am.getShippingAddress() return addressToDict(address) def getShippingInfo(self): """ """ sm = IShippingPriceManagement(self.context) shipping_price = sm.getPriceForCustomer() cm = ICurrencyManagement(self.context) price = cm.priceToString(shipping_price) method = IShippingMethodManagement( self.context).getSelectedShippingMethod() return { "price": price, "title": method.Title(), "description": method.Description() } def getTotalPrice(self): """ """ cart = self._getCart() pm = IPrices(cart) total = pm.getPriceForCustomer() cm = ICurrencyManagement(self.context) return cm.priceToString(total) def getTotalTax(self): """ """ cart = self._getCart() total = ITaxes(cart).getTaxForCustomer() cm = ICurrencyManagement(self.context) return cm.priceToString(total) def hasCartItems(self): """ """ cart = self._getCart() if cart is None: return False im = IItemManagement(cart) if im.hasItems(): return True return False def isCustomerComplete(self): """ """ cm = ICustomerManagement(self.context) customer = cm.getAuthenticatedCustomer() return ICompleteness(customer).isComplete() def test(self, error, result_true, result_false): """ """ if error == True: return result_true else: return result_false @memoize def _getCart(self): """Returns current cart. """ return ICartManagement(self.context).getCart()
class ExportXliffForm(formbase.PageForm): """ Form for exporting xliff """ form_fields = form.FormFields(IExportParams) label = u'Export Xliff' form_name = _(u"Export Xliff") template = pagetemplatefile.ZopeTwoPageTemplateFile( 'templates/export_xliff.pt') def __call__(self): self.request.set('disable_border', 'on') return super(ExportXliffForm, self).__call__() def setUpWidgets(self, ignore_request=False): self.adapters = {} data = {} # make the recursive checked if context is folderish if self.context.isPrincipiaFolderish: data = {'recursive': True} self.widgets = setUpWidgets(self.form_fields, self.prefix, self.context, self.request, form=self, data=data, adapters=self.adapters, ignore_request=ignore_request) def have_shoppinglist(self): return HAVE_SHOPPINGLIST def shoppinglist(self): """ returns the titles of the items currently in the shoppinglist """ context = aq_inner(self.context) mtool = getToolByName(context, 'portal_membership') pc = getToolByName(context, 'portal_catalog') member = mtool.getAuthenticatedMember() sl = member.getProperty('shoppinglist', tuple()) brains = pc(UID=sl) mylist = list() for b in brains: if b is not None: mylist.append(dict(uid=b.UID, title=b.Title, url=b.getURL())) return mylist @form.action(u'Export') def action_export(self, action, data): context = aq_inner(self.context) recursive = not not self.request.get('form.recursive') single_file = not not self.request.get('form.single_file') zip = not not self.request.get('form.zip') html_compatibility = not not self.request.get( 'form.html_compatibility') export_shoppinglist = not not self.request.get( 'form.export_shoppinglist') if self.context.isPrincipiaFolderish: container = context else: container = context.aq_parent if recursive is True: xliffexporter = IXLIFFExporter(container) else: xliffexporter = IXLIFFExporter(context) xliffexporter.recursive = recursive xliffexporter.single_file = single_file xliffexporter.html_compatibility = html_compatibility xliffexporter.zip = zip xliffexporter.source_language = "en" xliffexporter.export_shoppinglist = export_shoppinglist if export_shoppinglist is True: xliffexporter.shoppinglist = [ x['uid'] for x in self.shoppinglist() ] data = xliffexporter.export() if zip is True: self.request.response.setHeader('Content-type', 'application/zip') self.request.response.setHeader( 'Content-Disposition', 'attachment; filename=xliff_export_%s.zip' % DateTime().strftime('%Y-%m-%d')) elif html_compatibility and single_file: self.request.response.setHeader('Content-type', 'text/html') self.request.response.setHeader( 'Content-Disposition', 'attachment; filename=%s_xliff.html' % context.getId()) elif single_file: self.request.response.setHeader('Content-type', 'text/xml') self.request.response.setHeader( 'Content-Disposition', 'attachment; filename=%s.xliff' % context.getId()) else: pass # Should not happen return data