def action(self, resource, context, form): email = form['username'].strip() password = form['password'] # Check the user exists root = context.root user = root.get_user_from_login(email) if user is None: message = ERROR(u'The user "{username}" does not exist.', username=email) goto = context.get_referrer() return context.come_back(message, goto) # Check the password is right if not user.authenticate(password, clear=True): message = ERROR(u'The password is wrong.') goto = context.get_referrer() return context.come_back(message, goto) # Check user is enabled ac = resource.get_access_control() if not user.get_property('is_enabled') and \ not ac.is_admin(user, resource): message = ERROR(u"""Your account isn't validated, please contact the webmaster""") goto = context.get_referrer() return context.come_back(message, goto) # Check user has confirm is registration if user.get_property('user_must_confirm'): message = ERROR(u"""Your account has not been confirmed.""") goto = '/users/%s/;confirm_registration' % user.name return context.come_back(message, goto) # We log authentification if resource != context.root: shop = get_shop(resource) if shop.get_property('log_authentification'): logs = shop.get_resource('customers/authentification_logs') logs.log_authentification(user.name) user.set_property('last_time', datetime.now()) # Set cookie user.set_auth_cookie(context, password) # Set context context.user = user # Come back referrer = context.get_referrer() if referrer is None: goto = get_reference('./') else: path = get_uri_path(referrer) if path.endswith(';login'): goto = get_reference('./') else: goto = referrer return context.come_back(INFO(u"Welcome!"), goto)
def get_options(cls): shop = get_shop(get_context().resource) enumerates_folder = shop.get_resource("enumerates") return [ {"name": res.name, "value": res.get_property("title")} for res in enumerates_folder.search_resources(cls=EnumerateTable) ]
def backoffice_tabs(self): context = self.context site_root = context.site_root user = context.user shop = get_shop(site_root) tabs = [] is_site_root = site_root == context.resource # Go home active = is_site_root and context.view_name in (None, 'view') tabs.append({'name': '/', 'label': MSG(u'Go home'), 'icon': 'house-go', 'class': active and 'active' or None}) # Open backoffice tabs.append({'name': shop.get_property('shop_backoffice_uri'), 'label': MSG(u'Backoffice'), 'icon': 'cog', 'class': None}) # Site root access control ac = site_root.get_access_control() # New resource active = is_site_root and context.view_name == 'website_new_resource' view = site_root.get_view('website_new_resource') if view and ac.is_access_allowed(user, site_root, view): tabs.append({'name': '/;website_new_resource', 'label': MSG(u'Create a new resource'), 'icon': 'page-white-add', 'class': active and 'active' or None}) # Logout tabs.append({'name': '/;logout', 'label': MSG(u'Log out'), 'icon': 'action-logout', 'class': active and 'active' or None}) return tabs
def set_user(self, email=None, password=None): context = get_context() shop = get_shop(context.resource) # Calculate the user id user_id = self.get_next_user_id() # Add the user cls = shop.user_class user = cls.make_resource(cls, self, user_id) # Set the email and paswword if email is not None: user.set_property('email', email) if password is not None: user.set_password(password) # Set default group root = context.root query = [PhraseQuery('format', 'user-group'), PhraseQuery('name', 'default')] search = root.search(AndQuery(*query)) documents = search.get_documents() group = documents[0] group = root.get_resource(group.abspath) user.set_property('user_group', str(group.get_abspath())) user_is_enabled = group.get_property('user_is_enabled_when_register') user.set_property('is_enabled', user_is_enabled) # Return the user return user
def get_options(cls): shop = get_shop(get_context().resource) enumerates_folder = shop.get_resource('enumerates') return [{ 'name': res.name, 'value': res.get_property('title') } for res in enumerates_folder.search_resources(cls=EnumerateTable)]
def send_confirm_url(self, context, email, subject, text, view): # XXX We override send_confirm_url to send mail # without setting subject with host, to use shop_uri # and not backoffice_uri (Since webmaster click from backoffice uri) # and to use good from_addr # Set the confirmation key if self.has_property('user_must_confirm'): key = self.get_property('user_must_confirm') else: key = generate_password(30) self.set_property('user_must_confirm', key) # Build the confirmation link shop = get_shop(context.resource) base_uri = shop.get_property('shop_uri') confirm_url = get_reference(base_uri) path = '/users/%s/%s' % (self.name, view) confirm_url.path = Path(path) confirm_url.query = {'key': key, 'username': self.get_login_name()} confirm_url = str(confirm_url) text = text.gettext(uri=confirm_url, key=key) # Get from_addr site_root = context.site_root if site_root.get_property('emails_from_addr'): user_name = site_root.get_property('emails_from_addr') user = self.get_resource('/users/%s' % user_name) from_addr = user.get_title(), user.get_property('email') else: from_addr = context.server.smtp_from # Subject subject = u'[%s] %s' % (base_uri, subject.gettext()) # Send email context.root.send_email(email, subject, from_addr=from_addr, text=text, subject_with_host=False)
def sort_and_batch(self, resource, context, results): shop = get_shop(context.resource) start = context.query['batch_start'] # Get sort by from query or from shop default configuration size = shop.get_property('categories_batch_size') if context.uri.query.has_key('sort_by'): sort_by = context.query['sort_by'] else: sort_by = shop.get_property('shop_sort_by') if context.uri.query.has_key('reverse'): reverse = context.query['reverse'] else: reverse = shop.get_property('shop_sort_reverse') # Get documents items = results.get_documents(sort_by=sort_by, reverse=reverse, start=start, size=size) # FIXME This must be done in the catalog. if sort_by == 'title': items.sort(cmp=lambda x,y: cmp(x.title, y.title)) if reverse: items.reverse() # Access Control (FIXME this should be done before batch) user = context.user root = context.root allowed_items = [] for item in items: resource = root.get_resource(item.abspath) ac = resource.get_access_control() if ac.is_allowed_to_view(user, resource): allowed_items.append((item, resource)) return allowed_items
def action(self, resource, context, form): root = context.root to_addr = resource.get_property('to_addr') subject = MSG(u'Message from form: "%s"' % resource.get_title()).gettext() text = [] handler = resource.handler get_value = handler.get_record_value from_addr = to_addr for record in handler.get_records_in_order(): name = get_value(record, 'name') datatype = get_value(record, 'datatype') value = form[name] # XXX Render on datatype ? if datatype == 'product': shop = get_shop(resource) site_root = resource.get_site_root() product = context.root.get_resource(value) base_uri = shop.get_property('shop_uri') end_uri = site_root.get_pathto(product) value = get_reference(base_uri).resolve(end_uri) elif datatype == 'email': # XXX Set from_addr from_addr = value title = get_value(record, 'title') text.append('*%s* \n\n %s' % (title, value)) text = '\n\n\n'.join(text) root.send_email(to_addr, subject, from_addr=from_addr, text=text, subject_with_host=False) return resource.get_property('final_message')
def set_user(self, email=None, password=None): context = get_context() shop = get_shop(context.resource) # Calculate the user id user_id = self.get_next_user_id() # Add the user cls = shop.user_class user = cls.make_resource(cls, self, user_id) # Set the email and paswword if email is not None: user.set_property('email', email) if password is not None: user.set_password(password) # Set default group root = context.root query = [ PhraseQuery('format', 'user-group'), PhraseQuery('name', 'default') ] search = root.search(AndQuery(*query)) documents = search.get_documents() group = documents[0] group = root.get_resource(group.abspath) user.set_property('user_group', str(group.get_abspath())) user_is_enabled = group.get_property('user_is_enabled_when_register') user.set_property('is_enabled', user_is_enabled) # Return the user return user
def get_namespace(self, resource, context): namespace = {'category': resource.get_title()} shop = get_shop(resource) # Check resources if len(context.query['products'])>3: return {'error': MSG(u'Too many products to compare')} if len(context.query['products'])<1: return {'error': MSG(u'Please select products to compare')} # Get real product resources products_to_compare = [] products_models = [] products = shop.get_resource('products') for product in context.query['products']: try: product_resource = products.get_resource(product) except LookupError: product_resource = None if not product_resource: return {'error': MSG(u'Error: product invalid')} products_to_compare.append(product_resource) product_model = product_resource.get_property('product_model') products_models.append(product_model) # Check if products models are the same if len(set(products_models))!=1: return {'error': MSG(u"You can't compare this products.")} # Build comparator namespace namespace['error'] = None namespace['products'] = [] namespace['nb_products'] = len(products_to_compare) namespace['nb_products_plus_1'] = len(products_to_compare) +1 for product in products_to_compare: # Base products namespace ns = product.get_small_namespace(context) namespace['products'].append(ns) # Comporator model schema model = products_to_compare[0].get_product_model() if model: # Get model schema keys = [] comparator = {} schema_resource = model.get_resource('schema').handler get_value = schema_resource.get_record_value for record in schema_resource.get_records_in_order(): if get_value(record, 'visible') is False: continue name = get_value(record, 'name') title = get_value(record, 'title') keys.append(name) comparator[name] = {'name': name, 'title': title, 'values': []} for product in products_to_compare: model_ns = model.get_model_namespace(product) for d in model_ns['specific_list']: comparator[d['name']]['values'].append(d['value']) # fetch info keys in order namespace['comparator'] = [comparator[key] for key in keys] else: namespace['comparator'] = [] return namespace
def get_namespace(self, resource, context): shop = get_shop(resource) order = shop.get_resource('orders/%s' % context.query['id'], soft=True) # ACL ac = resource.get_access_control() if not order or (order.get_property('customer_id') != context.user.name and not ac.is_admin(context.user, resource)): msg = ERROR(u'Your are not authorized to view this ressource') return context.come_back(msg, goto='/') # Build namespace namespace = order.get_namespace(context) # States namespace['state'] = {'title': states[order.workflow_state], 'color': states_color[order.workflow_state]} # Other namespace['order_name'] = order.name namespace['is_payed'] = order.get_property('is_payed') namespace['is_sent'] = order.get_property('is_sent') # Bill has_bill = order.get_resource('bill', soft=True) is not None namespace['has_bill'] = has_bill # Payments payments = shop.get_resource('payments') # Shipping shippings = shop.get_resource('shippings') # Prices for key in ['shipping_price', 'total_price']: namespace[key] = format_price(order.get_property(key)) # Messages messages = order.get_resource('messages') namespace['messages'] = messages.get_namespace_messages(context) # Payment view payments = shop.get_resource('payments') payments_records = payments.get_payments_records(context, order.name) namespace['payments_view'] = [] for payment_way, payment_record in payments_records: record_view = payment_way.order_view if record_view: payment_table = payment_way.get_resource('payments').handler record_view = record_view( payment_way=payment_way, payment_table=payment_table, record=payment_record, id_payment=payment_record.id) view = record_view.GET(order, context) namespace['payments_view'].append(view) # Shipping view shippings = shop.get_resource('shippings') shipping_way = order.get_property('shipping') shipping_way_resource = shop.get_resource('shippings/%s/' % shipping_way) shippings_records = shippings.get_shippings_records(context, order.name) if shippings_records: last_delivery = shippings_records[0] record_view = shipping_way_resource.order_view view = record_view.GET(order, shipping_way_resource, last_delivery, context) namespace['shipping_view'] = view else: namespace['shipping_view'] = None return namespace
def get_options(cls): shop = get_shop(get_context().resource) enumerates_folder = shop.get_resource('enumerates') table = enumerates_folder.get_resource(cls.enumerate_name) return [ cls.get_kw(table, record) for record in table.handler.get_records_in_order() ]
def action_add_message(self, resource, context, form): shop = get_shop(resource) order = shop.get_resource('orders/%s' % form['id']) messages = order.get_resource('messages') messages.add_new_record({'author': context.user.name, 'private': False, 'message': form['message']}) order.notify_new_message(form['message'], context) context.message = INFO(u'Your message has been sent')
def get_lazy_current_category(self, context): here = context.resource shop = get_shop(here) here = context.resource if isinstance(here, shop.category_class): return here.get_title() elif isinstance(here, shop.product_class): return here.parent.get_title() return None
def get_table_columns(self, resource, context): base = [('checkbox', None)] shop = get_shop(resource) if shop.get_property('registration_need_email_validation') is True: return (base + self.table_columns + [('account_state', MSG(u'Mail confirmé'))]) return (base + self.table_columns)
def get_options(cls): from utils import get_shop context = get_context() # Search shop shop = get_shop(context.resource) # Get options resource = shop.get_resource('countries-zones').handler return [{'name': str(record.id), 'value': resource.get_record_value(record, 'title')} for record in resource.get_records()]
def init_resource(self, *args, **kw): Folder.init_resource(self, *args, **kw) # XXX ctime (Should be done in ikaaro) self.set_property('ctime', datetime.now()) # Currency shop = get_shop(self) devise = shop.get_property('devise') self.set_property('devise', devise) # Workflow self.onenter_open()
def get_options(cls): options = [] context = get_context() shop = get_shop(context.resource) addresses = shop.get_resource('addresses').handler for address in addresses.search(user=context.user.name): options.append( {'name': str(address.id), 'value': addresses.get_record_value(address, 'title')}) return options
def get_options(cls): from utils import get_shop context = get_context() # Search shop shop = get_shop(context.resource) # Get options resource = shop.get_resource('countries-zones').handler return [{ 'name': str(record.id), 'value': resource.get_record_value(record, 'title') } for record in resource.get_records()]
def to_text(cls, name, languages): here = get_context().resource # XXX Hack for icms-update (context.resource is None) if here is None: return None if name is None: return None shop = get_shop(here) enumerates_folder = shop.get_resource("enumerates") table = enumerates_folder.get_resource(cls.enumerate_name) record = table.handler.search(name=name)[0] values = [table.handler.get_record_value(record, "title", lang) for lang in languages] return u" ".join(values)
def get_nb_products(self, only_public=False): root = self.get_root() shop = get_shop(self) abspath = self.get_canonical_path() query = [PhraseQuery('parent_paths', str(abspath)), PhraseQuery('format', shop.product_class.class_id)] if shop.get_property('hide_not_buyable_products') is True: context = get_context() group_name = get_group_name(shop, context) query.append(NotQuery(PhraseQuery('not_buyable_by_groups', group_name))) if only_public is True: query.append(PhraseQuery('workflow_state', 'public')) return len(root.search(AndQuery(*query)))
def get_options(cls): options = [] context = get_context() shop = get_shop(context.resource) addresses = shop.get_resource('addresses').handler for address in addresses.search(user=context.user.name): options.append({ 'name': str(address.id), 'value': addresses.get_record_value(address, 'title') }) return options
def get_query(self, context): shop = get_shop(context.resource) query = Table_AddEditRecord.get_query(self, context) # Test the id is valid id = query['id'] resource = shop.get_resource('addresses') handler = resource.get_handler() record = handler.get_record(id) if record is None: context.query = query raise FormError, MSG(u'The {id} record is missing.', id=id) # Is authorized ? self.is_allowed_to_edit_record(resource.handler, context) # Ok return query
def get_value(cls, name, default=None): if name is None: return None here = get_context().resource # XXX Hack for icms-update (context.resource is None) if here is None: return None shop = get_shop(here) table = shop.get_resource("enumerates/%s" % cls.enumerate_name) records = table.handler.search(name=name) if len(records) == 0: # XXX Should not happen # Enumerate has been deleted return None record = records[0] return cls.get_kw(table, record)["value"]
def get_nb_products(self, only_public=False): root = self.get_root() shop = get_shop(self) abspath = self.get_canonical_path() query = [ PhraseQuery('parent_paths', str(abspath)), PhraseQuery('format', shop.product_class.class_id) ] if shop.get_property('hide_not_buyable_products') is True: context = get_context() group_name = get_group_name(shop, context) query.append( NotQuery(PhraseQuery('not_buyable_by_groups', group_name))) if only_public is True: query.append(PhraseQuery('workflow_state', 'public')) return len(root.search(AndQuery(*query)))
def to_text(cls, name, languages): here = get_context().resource # XXX Hack for icms-update (context.resource is None) if here is None: return None if name is None: return None shop = get_shop(here) enumerates_folder = shop.get_resource('enumerates') table = enumerates_folder.get_resource(cls.enumerate_name) record = table.handler.search(name=name)[0] values = [ table.handler.get_record_value(record, 'title', lang) for lang in languages ] return u' '.join(values)
def get_value(cls, name, default=None): if name is None: return None here = get_context().resource # XXX Hack for icms-update (context.resource is None) if here is None: return None shop = get_shop(here) table = shop.get_resource('enumerates/%s' % cls.enumerate_name) records = table.handler.search(name=name) if len(records) == 0: # XXX Should not happen # Enumerate has been deleted return None record = records[0] return cls.get_kw(table, record)['value']
def get_namespace(self, datatype, value): context = get_context() shop = get_shop(context.resource) product_class = shop.product_class widget = PathSelectorWidget(self.name, action=self.action).to_html(datatype, value) if value is not None: product = context.resource.get_resource(value, soft=True) else: product = None if product is None or not isinstance(product, product_class): viewbox = None else: viewbox = product_class.viewbox.GET(product, context) return {'widget': widget, 'value': value, 'viewbox': viewbox}
def make_payment(self, resource, mode, amount, customer, devise=None, order=None): # Auto incremental name for payments name = self.make_reference() payment_way = get_payment_way(self, mode) order_abspath = str(order.get_abspath()) if order else None # Devise if devise is None: shop = get_shop(resource) devise = shop.get_property('devise') # Payment configuration kw = {'amount': amount, 'customer_id': customer.name, 'devise': devise, 'order_abspath': order_abspath} # Create order cls = payment_way.payment_class return resource.make_resource(name, cls, **kw)
def address(self): # XXX We should have a default address ? context = get_context() shop = get_shop(context.resource) addresses_h = shop.get_resource('addresses').handler records = addresses_h.search(user=self.name) if len(records) == 0: return None record = records[0] addresse = addresses_h.get_record_namespace(record.id) addr = u'' for key in ['address_1', 'address_2', 'zipcode', 'town', 'country']: try: addr += u'%s ' % addresse[key] except Exception: # XXX Why ? addr += u'XXX' return addr
def action_show_payment_form(self, resource, context, form): shop = get_shop(resource) order = shop.get_resource('orders/%s' % context.query['id'], soft=True) # ACL if not order or order.get_property('customer_id') != context.user.name: msg = ERROR(u'Your are not authorized to view this ressource') return context.come_back(msg, goto='/') payments = shop.get_resource('payments') payments_records = payments.get_payments_records(context, order.name) for payment_way, payment_record in payments_records: record_view = payment_way.order_view if record_view: payment_table = payment_way.get_resource('payments').handler record_view = record_view( payment_way=payment_way, payment_table=payment_table, record=payment_record, id_payment=payment_record.id) return record_view.action_show_payment_form(resource, context, form)
def get_sidebar_resource(self, context): # Show sidebar here = context.resource shop = get_shop(here) site_root = here.get_site_root() if isinstance(here, site_root.shop_class): return site_root.get_resource('shop/shop-sidebar', soft=True) elif isinstance(here, shop.product_class): return site_root.get_resource('product-sidebar') elif isinstance(here, shop.category_class): cat = here sidebar = None while cat.name != 'categories' and sidebar is None: sidebar = cat.get_resource('sidebar', soft=True) cat = cat.parent if sidebar: return sidebar return site_root.get_resource('category-sidebar') return NeutralSkin.get_sidebar_resource(self, context)
def backoffice_tabs(self): context = self.context site_root = context.site_root user = context.user shop = get_shop(site_root) tabs = [] is_site_root = site_root == context.resource # Go home active = is_site_root and context.view_name in (None, 'view') tabs.append({ 'name': '/', 'label': MSG(u'Go home'), 'icon': 'house-go', 'class': active and 'active' or None }) # Open backoffice tabs.append({ 'name': shop.get_property('shop_backoffice_uri'), 'label': MSG(u'Backoffice'), 'icon': 'cog', 'class': None }) # Site root access control ac = site_root.get_access_control() # New resource active = is_site_root and context.view_name == 'website_new_resource' view = site_root.get_view('website_new_resource') if view and ac.is_access_allowed(user, site_root, view): tabs.append({ 'name': '/;website_new_resource', 'label': MSG(u'Create a new resource'), 'icon': 'page-white-add', 'class': active and 'active' or None }) # Logout tabs.append({ 'name': '/;logout', 'label': MSG(u'Log out'), 'icon': 'action-logout', 'class': active and 'active' or None }) return tabs
def get_options(cls): context = get_context() # Search shop shop = get_shop(context.resource) # Get options countries = shop.get_resource('countries').handler if hasattr(cls, 'zone'): records = countries.search(zone=str(cls.zone)) else: records = countries.get_records() options = [] for record in records: enabled = countries.get_record_value(record, 'enabled') if enabled is False: continue options.append({'name': str(record.id), 'value': countries.get_record_value(record, 'title')}) options.sort(key=itemgetter('value')) return options
def onenter_paid(self): context = get_context() root = context.root shop = get_shop(self) site_root = context.site_root uri = context.uri.resolve('/%s' % site_root.get_pathto(self)) kw = {'order_name': self.name, 'order_uri': uri} # Send confirmation to customer customer_id = self.get_property('customer_id') user = root.get_user(customer_id) to_addr = user.get_property('email') subject = mail_confirmation_payment_title.gettext(**kw) body = mail_confirmation_payment_body.gettext(**kw) root.send_email(to_addr, subject, text=body) # We send email to inform shop administrator subject = mail_notification_payment_title.gettext(**kw) text = mail_notification_payment_body.gettext(**kw) for to_addr in shop.get_notification_mails(): root.send_email(to_addr, subject, text=text)
def get_items(self, resource, context): shop = get_shop(resource) abspath = resource.get_canonical_path() query = [ PhraseQuery('parent_paths', str(abspath)), PhraseQuery('format', shop.product_class.class_id), PhraseQuery('workflow_state', 'public')] # Is buyable ? if shop.get_property('hide_not_buyable_products') is True: group_name = get_group_name(shop, context) q = PhraseQuery('not_buyable_by_groups', group_name) query.append(NotQuery(q)) # Add query of filter for key, datatype in self.get_search_schema().items(): value = context.query[key] if value and issubclass(datatype, IntegerRange): query.append(RangeQuery(key, value[0], value[1])) elif value: query.append(PhraseQuery(key, value)) return context.root.search(AndQuery(*query))
def get_options(cls): context = get_context() # Search shop shop = get_shop(context.resource) # Get options countries = shop.get_resource('countries').handler if hasattr(cls, 'zone'): records = countries.search(zone=str(cls.zone)) else: records = countries.get_records() options = [] for record in records: enabled = countries.get_record_value(record, 'enabled') if enabled is False: continue options.append({ 'name': str(record.id), 'value': countries.get_record_value(record, 'title') }) options.sort(key=itemgetter('value')) return options
def onenter_open(self): context = get_context() shop = get_shop(self) root = context.root site_root = context.site_root # Build email informations uri = context.uri.resolve('/%s' % site_root.get_pathto(self)) kw = {'order_name': self.name, 'order_uri': uri} # Send confirmation to customer customer_id = self.get_property('customer_id') user = root.get_user(customer_id) to_addr = user.get_property('email') subject = mail_confirmation_creation_title.gettext(**kw) body = mail_confirmation_creation_body.gettext(**kw) root.send_email(to_addr, subject, text=body) # Send confirmation to the shop subject = mail_notification_title.gettext(**kw) body = mail_notification_body.gettext(**kw) for to_addr in shop.get_notification_mails(): root.send_email(to_addr, subject, text=body)
def get_title(cls): shop = get_shop(get_context().resource) enumerates_folder = shop.get_resource('enumerates') table = enumerates_folder.get_resource(cls.enumerate_name) return table.get_title()
def get_products(self, context, product_format, categories=[], excluded_products=[]): shop = get_shop(self) table = self if self.get_property("use_shop_configuration"): table = shop.get_resource("cross-selling") if table.get_property("enabled") is False: return root = context.root products_quantity = table.get_property("products_quantity") # Base query query = [PhraseQuery("format", product_format), PhraseQuery("workflow_state", "public")] # Do not show now buyable products group_name = get_group_name(shop, context) q = PhraseQuery("not_buyable_by_groups", group_name) query.append(NotQuery(q)) # Excluded products query if excluded_products: exclude_query = [PhraseQuery("abspath", str(abspath)) for abspath in excluded_products] if len(exclude_query) > 1: exclude_query = OrQuery(*exclude_query) else: exclude_query = exclude_query[0] query.append(NotQuery(exclude_query)) # Filter on product title filter_text = table.get_property("filter_text") if filter_text: query.append(PhraseQuery("title", filter_text)) # Categories query mode_categories = table.get_property("categories") if mode_categories == "current_category": query_categorie = [PhraseQuery("parent_paths", str(x.get_abspath())) for x in categories] if len(query_categorie) > 1: query.append(OrQuery(*query_categorie)) elif len(query_categorie) == 1: query.append(query_categorie[0]) elif mode_categories == "one_category": query.append(PhraseQuery("parent_paths", table.get_property("specific_category"))) # Show reductions ? promotion = table.get_property("show_product_with_promotion") if promotion in ("0", "1"): query.append(PhraseQuery("has_reduction", bool(promotion))) # Product model product_model = table.get_property("product_model") if product_model: query.append(PhraseQuery("product_model", product_model)) # Tags if table.get_property("tags"): query.append(OrQuery(*[PhraseQuery("tags", x) for x in table.get_property("tags")])) # Selection in cross selling table handler = table.handler get_value = handler.get_record_value ids = list(handler.get_record_ids_in_order()) names = [] for id in ids[:products_quantity]: record = handler.get_record(id) path = get_value(record, "name") names.append(path) products_quantity -= 1 resource = self.get_resource(path, soft=True) if resource is None: log_warning("Error cross selling, %s" % path) elif resource.get_property("state") == "public": yield resource if products_quantity <= 0: return if names: names_query = [PhraseQuery("name", name) for name in names] if len(names_query) > 1: names_query = OrQuery(*names_query) else: names_query = names_query[0] query.append(NotQuery(names_query)) # Complete results sort = table.get_property("sort") if sort == "random": # Random selection results = root.search(AndQuery(*query)) # XXX It's not relevant to make a random cross selling # with more than 1000 products brains = list(results.get_documents(size=1000)) shuffle(brains) for brain in brains[:products_quantity]: yield root.get_resource(brain.abspath) elif sort == "last": results = root.search(AndQuery(*query)) brains = list(results.get_documents(sort_by="ctime", reverse=True, size=products_quantity)) for brain in brains: yield root.get_resource(brain.abspath)
def get_item_classes(self): context = get_context() shop = get_shop(context.resource) return (shop.product_class, )
def get_namespace(self, resource, context): root = context.root # Get user user = resource # Get user class shop = get_shop(resource) group = user.get_group(context) # Build namespace namespace = {} infos = [] for key, title in [('gender', MSG(u'Gender')), ('firstname', MSG(u'Firstname')), ('lastname', MSG(u'Lastname')), ('email', MSG(u'Email')), ('user_language', MSG(u'User language')), ('phone1', MSG(u'Phone1')), ('phone2', MSG(u'Phone2'))]: infos.append({'title': title, 'value': user.get_property(key), 'public': True}) # Is enabled ? value = bool_to_img(user.get_property('is_enabled')) infos.append({'title': MSG(u'Enabled ?'), 'value': value, 'public': True}) # Group infos.append({'title': MSG(u'Group'), 'value': group.get_title(), 'public': True}) # Schema schema = group.get_resource('schema').handler for record in schema.get_records(): name = schema.get_record_value(record, 'name') title = schema.get_record_value(record, 'title') public = schema.get_record_value(record, 'is_public') infos.append({'title': title, 'value': user.get_property(name), 'public': public}) namespace['infos'] = infos # Customer connections namespace['connections'] = [] accept = context.accept_language connections = shop.get_resource('customers/authentification_logs').handler for record in connections.search(user=user.name): ts = connections.get_record_value(record, 'ts') dt = format_datetime(ts, accept) namespace['connections'].append(dt) namespace['connections'].sort(reverse=True) # Customer payments payments = shop.get_resource('payments') namespace['payments'] = payments.get_payments_informations( context, user=user.name) # Customer orders namespace['orders'] = [] query = PhraseQuery('customer_id', user.name) results = root.search(query) nb_orders = 0 for brain in results.get_documents(): order = root.get_resource(brain.abspath) nb_orders += 1 namespace['orders'].append( {'id': brain.name, 'href': resource.get_pathto(order), 'amount': order.get_property('total_price')}) namespace['nb_orders'] = nb_orders # Customer addresses namespace['addresses'] = [] addresses = shop.get_resource('addresses').handler for record in addresses.search(user=user.name): namespace['addresses'].append( addresses.get_record_namespace(record.id)) return namespace
def action(self, resource, context, form): shop = get_shop(resource) root = context.root site_root = resource.get_site_root() # Check the new password matches password = form['password'].strip() if password != form['password_check']: context.message = ERROR(u"The two passwords are different.") return if shop.get_property('registration_need_email_validation') is False: msg = MSG(u'Your inscription has been validaded.') else: msg = MSG(u'Your inscription has been validaded, ' u'you will receive an email to confirm it.') # Do we already have a user with that email? email = form['email'].strip() user = root.get_user_from_login(email) if user is not None: context.message = ERROR(u'This email address is already used.') return # Add the user users = root.get_resource('users') user = users.set_user(email, password) # Set user group (do it befor save_form for dynanic schema) group = self.get_group(context) user.set_property('user_group', str(group.get_abspath())) # Save properties user.save_form(self.get_schema(resource, context), form) # Save address in addresses table if group.get_property('hide_address_on_registration') is False: kw = {'user': user.name} addresses = shop.get_resource('addresses') for key in [ 'gender', 'lastname', 'firstname', 'address_1', 'address_2', 'zipcode', 'town', 'country' ]: kw[key] = form[key] kw['title'] = MSG(u'Your address').gettext() addresses.handler.add_record(kw) # Clean cart, if another user already login before cart = ProductCart(context) cart.clean() # Set the role site_root.set_user_role(user.name, 'guests') # We log authentification shop = get_shop(resource) logs = shop.get_resource('customers/authentification_logs') logs.log_authentification(user.name) user.set_property('last_time', datetime.now()) # Send confirmation email need_email_validation = shop.get_property( 'registration_need_email_validation') user.send_register_confirmation(context, need_email_validation) # User is enabled ? user_is_enabled = group.get_property('user_is_enabled_when_register') user.set_property('is_enabled', user_is_enabled) # Create modules if needed search = context.root.search(is_shop_user_module=True) for brain in search.get_documents(): shop_user_module = root.get_resource(brain.abspath) shop_user_module.initialize(user) # If user not enabled, send mail to webmaster to validate user if user_is_enabled is False: subject = MSG( u'A customer must be validated in your shop').gettext() shop_backoffice_uri = shop.get_property('shop_backoffice_uri') body = registration_notification_body.gettext( name=user.name, email=email, shop_backoffice_uri=shop_backoffice_uri) for to_addr in shop.get_property('order_notification_mails'): root.send_email(to_addr, subject, text=body) # If need_email_validation or user not enable redirect on Welcome if need_email_validation is True or user_is_enabled is False: goto = '%s/welcome/' % context.get_link(group) return context.come_back(msg, goto=goto) ######################## # Do authentification ######################## # Set cookie user.set_auth_cookie(context, form['password']) # Set context context.user = user # Redirect shop = get_shop(resource) if form['goto']: goto = context.query['goto'] elif resource == shop: goto = './;addresses' elif resource.class_id == shop.product_class.class_id: goto = './' else: goto = '/users/%s' % user.name return context.come_back(msg, goto)
def get_products(self, context, product_format, categories=[], excluded_products=[]): shop = get_shop(self) table = self if self.get_property('use_shop_configuration'): table = shop.get_resource('cross-selling') if table.get_property('enabled') is False: return root = context.root products_quantity = table.get_property('products_quantity') # Base query query = [ PhraseQuery('format', product_format), PhraseQuery('workflow_state', 'public') ] # Do not show now buyable products group_name = get_group_name(shop, context) q = PhraseQuery('not_buyable_by_groups', group_name) query.append(NotQuery(q)) # Excluded products query if excluded_products: exclude_query = [ PhraseQuery('abspath', str(abspath)) for abspath in excluded_products ] if len(exclude_query) > 1: exclude_query = OrQuery(*exclude_query) else: exclude_query = exclude_query[0] query.append(NotQuery(exclude_query)) # Filter on product title filter_text = table.get_property('filter_text') if filter_text: query.append(PhraseQuery('title', filter_text)) # Categories query mode_categories = table.get_property('categories') if mode_categories == 'current_category': query_categorie = [ PhraseQuery('parent_paths', str(x.get_abspath())) for x in categories ] if len(query_categorie) > 1: query.append(OrQuery(*query_categorie)) elif len(query_categorie) == 1: query.append(query_categorie[0]) elif mode_categories == 'one_category': query.append( PhraseQuery('parent_paths', table.get_property('specific_category'))) # Show reductions ? promotion = table.get_property('show_product_with_promotion') if promotion in ('0', '1'): query.append(PhraseQuery('has_reduction', bool(promotion))) # Product model product_model = table.get_property('product_model') if product_model: query.append(PhraseQuery('product_model', product_model)) # Tags if table.get_property('tags'): query.append( OrQuery(*[ PhraseQuery('tags', x) for x in table.get_property('tags') ])) # Selection in cross selling table handler = table.handler get_value = handler.get_record_value ids = list(handler.get_record_ids_in_order()) names = [] for id in ids[:products_quantity]: record = handler.get_record(id) path = get_value(record, 'name') names.append(path) products_quantity -= 1 resource = self.get_resource(path, soft=True) if resource is None: log_warning('Error cross selling, %s' % path) elif resource.get_property('state') == 'public': yield resource if products_quantity <= 0: return if names: names_query = [PhraseQuery('name', name) for name in names] if len(names_query) > 1: names_query = OrQuery(*names_query) else: names_query = names_query[0] query.append(NotQuery(names_query)) # Complete results sort = table.get_property('sort') if sort == 'random': # Random selection results = root.search(AndQuery(*query)) # XXX It's not relevant to make a random cross selling # with more than 1000 products brains = list(results.get_documents(size=1000)) shuffle(brains) for brain in brains[:products_quantity]: yield root.get_resource(brain.abspath) elif sort == 'last': results = root.search(AndQuery(*query)) brains = list( results.get_documents(sort_by='ctime', reverse=True, size=products_quantity)) for brain in brains: yield root.get_resource(brain.abspath)
def get_widgets(self, resource, context): if get_shop(resource) == resource.parent: return self.widgets return [self.shop_configuration] + self.widgets