def _get_form(self, resource, context): # We cannot call direct parent NewInstance, because we override the # container form = super(NewInstance, self)._get_form(resource, context) # 1. The container container = self._get_container(resource, context) ac = container.get_access_control() if not ac.is_allowed_to_add(context.user, container): path = context.get_link(container) path = '/' if path == '.' else '/%s/' % path msg = ERROR(u'Adding resources to {path} is not allowed.') raise FormError, msg.gettext(path=path) # 2. Strip the title form['title'] = form['title'].strip() # 3. The name name = self.get_new_resource_name(form) if not name: raise FormError, messages.MSG_NAME_MISSING try: name = checkid(name) except UnicodeEncodeError: name = None if name is None: raise FormError, messages.MSG_BAD_NAME # Check the name is free if container.get_resource(name, soft=True) is not None: raise FormError, messages.MSG_NAME_CLASH form['name'] = name # Ok return form
def action_update(self, resource, context, form): timetables = resource.get_value('timetables') if len(timetables) == 0: context.message = ERROR(u'Nothing to change.') return # Update timetable or just set index to next index new_timetables = [] for index in range(len(timetables)): try: start = context.get_form_value('%s_start' % index, type=Time) end = context.get_form_value('%s_end' % index, type=Time) except: context.message = ERROR(u'Wrong time selection (HH:MM).') return if start >= end: message = ERROR(u'Start time must be earlier than end time.') context.message = message return new_timetables.append((start, end)) new_timetables.sort() resource.set_property('timetables', new_timetables) # Ok context.message = messages.MSG_CHANGES_SAVED
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_form(self, resource, context): form = super(User_EditPassword, self)._get_form(resource, context) # Strip password newpass = form['newpass'].strip() form['newpass'] = newpass # Check username is different from password if form['username'] == form['newpass']: raise FormError, messages.MSG_PASSWORD_EQUAL_TO_USERNAME # Check the new password matches if newpass != form['newpass2']: raise FormError, ERROR(u"Passwords mismatch, please try again.") # Check old password if resource.name == context.user.name: password = form['password'] if not resource.authenticate(password): message = ERROR( u"You mistyped your actual password, your account is" u" not changed.") raise FormError, message # Ok return form
def _get_form(self, resource, context): form = super(Archive_View, self)._get_form(resource, context) # Get the target resource target = form['target'] target = resource.get_resource(target, soft=True) if target is None: raise FormError, ERROR(u'Target does not exist.') if isinstance(target, Folder) is False: raise FormError, ERROR(u'Target must be a folder.') return form
def get_container(self, resource, context, form): # Container container = resource path = str(container.abspath) # Access control class_id = context.query['type'] root = context.root if not root.has_permission(context.user, 'add', container, class_id): path = '/' if path == '.' else '/%s/' % path msg = ERROR(u'Adding resources to {path} is not allowed.') raise FormError, msg.gettext(path=path) # Ok return container
def _get_form(self, resource, context): form = super(Event_NewInstance, self)._get_form(resource, context) dtstart = form['dtstart'] dtend = form['dtend'] allday = form.get('allday', False) if not allday and (not form['dtstart_time'] or not form['dtend_time']): msg = ERROR(u"You have to fill start and end time") raise FormError(msg) if dtstart > dtend: msg = ERROR(u'Invalid dates.') raise FormError(msg) return form
def action_import_ods(self, resource, context, form): # Check if lpod is install ? if lpod_is_install is False: msg = ERROR(u'Please install LPOD') return context.come_back(msg) # Get models root = context.root shop = get_shop(resource) models = shop.get_resource('products-models').get_resources() # Open ODF file filename, mimetype, body = form['file'] f = StringIO(body) document = odf_get_document(f) for table in document.get_body().get_tables(): model_name = table.get_name() csv = CSVFile(string=table.to_csv()) for row in csv.get_rows(): reference = row[0] declination_name = row[1] stock = row[-3] price1 = row[-2] price2 = row[-1] product_brains = root.search( reference=reference).get_documents() if len(product_brains) > 1: print 'Reference %s %s' % (reference, len(product_brains)) continue product_brain = product_brains[0] product = root.get_resource(product_brain.abspath) declination = product.get_resource(declination_name) # Set change declination.set_property('stock-quantity', int(stock)) context.message = MSG(u'Import has been done') return
def action_add_to_cart(self, resource, context, form): """ Add to cart """ cart = ProductCart(context) # Check if we can add to cart if not resource.is_buyable(context): msg = MSG(u"This product isn't buyable") return context.come_back(msg) # Get purchase options declination = None kw = {} for key in resource.get_purchase_options_schema(): if form[key] is not None: kw[key] = form[key] if kw: declination = resource.get_declination(kw) if declination is None: context.message = ERROR(u'Declination not exist') return # Check if product is in stock cart_quantity = cart.get_product_quantity_in_cart(resource.name) total_quantity = cart_quantity + form['quantity'] if not resource.is_in_stock_or_ignore_stock(total_quantity, declination): msg = u"Quantity in stock insufficient." return context.come_back(MSG(msg)) # Add to cart cart.add_product(resource, form['quantity'], declination) # Information message context.message = INFO(u'Product added to cart !')
def action_cancel_order(self, resource, context, form): try: resource.make_transition('open_to_cancel', None) except WorkflowError, excp: log_error(excp.message, domain='ikaaro') context.message = ERROR(unicode(excp.message, 'utf-8')) return
def action(self, resource, context, form): resource.save_barcode(form['reference']) # Set pub_datetime if (resource.get_property('state') == 'private' and form['state'] == 'public'): resource.set_property('pub_datetime', datetime.now()) # We change category if needed if str(resource.parent.get_abspath()) != form['category']: target = context.root.get_resource(form['category']) if target.get_resource(resource.name, soft=True) is not None: context.message = ERROR(u"""Impossible to change category: There's already a product with this name in this category""") return target.move_resource(resource.get_abspath(), resource.name) goto = '%s/%s' % (context.get_link(target), resource.name) resource = target.get_resource(resource.name) else: goto = None # Set cover as public if form['cover']: cover = resource.get_resource(form['cover']) cover.set_property('state', 'public') # Save properties language = resource.get_content_language(context) for key, datatype in self.get_schema(resource, context).iteritems(): if key in ('ctime', 'category', 'pub_datetime'): continue elif issubclass(datatype, Unicode): resource.set_property(key, form[key], language) elif getattr(datatype, 'multilingual', False): resource.set_property(key, form[key], language) else: resource.set_property(key, form[key]) # Come back return context.come_back(messages.MSG_CHANGES_SAVED, goto=goto)
def action_change_order_state(self, resource, context, form): try: resource.make_transition(form['transition'], form['comments']) except WorkflowError, excp: log_error(excp.message, domain='ikaaro') context.message = ERROR(unicode(excp.message, 'utf-8')) return
def get_messages(self, context): """Return the message string of the last action. A list of messages is supported. """ # Text if context.message is not None: messages = context.message elif 'error' in context.uri.query: messages = ERROR(context.get_query_value('error', type=Unicode)) elif 'info' in context.uri.query: messages = INFO(context.get_query_value('info', type=Unicode)) # XXX For backwards compatibility elif 'message' in context.uri.query: messages = INFO(context.get_query_value('message', type=Unicode)) else: return None # Multiple messages: if not isinstance(messages, list): messages = [messages] messages_ns = [] for message in messages: css_class = getattr(message, 'css', 'info') messages_ns.append({'message': message, 'class': css_class}) namespace = {'messages': messages_ns} template = context.get_template('/ui/aruni/message.xml') return stl(template, namespace)
def GET(self, resource, context): app = resource.parent for form in app.get_forms(): state = form.get_value('form_state') if state != 'private': break else: return context.come_back(ERR_NO_DATA) format = context.query['format'] if format == 'xls': writer_cls = XLSWriter else: writer_cls = ODSWriter name = MSG(u"{title} Data").gettext(title=resource.get_title()) writer = writer_cls(name) schema = resource.get_schema() # Main header header = [ title.gettext() for title in (MSG(u"Form"), MSG(u"First Name"), MSG(u"Last Name"), MSG(u"E-mail"), MSG(u"State")) ] for name in sorted(schema): header.append(name.replace('_', '')) try: writer.add_row(header, is_header=True) except Exception, exception: return context.come_back(ERROR(unicode(exception)))
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 action_remove(self, resource, context, form): # Remove resource try: resource.parent.del_resource(resource.name) except ConsistencyError: context.message = ERROR(u"Can't remove this calendar") return msg = MSG(u'This calendar has been removed') return context.come_back(msg, goto='./;calendars')
def get_container(self, resource, context, form): # Container container = resource if 'location' in self.get_fields(): path = form['location'] if path is not None: container = resource.get_resource(path) # Access control class_id = context.query['type'] root = context.root if not root.has_permission(context.user, 'add', container, class_id): path = '/' if path == '.' else '/%s/' % path msg = ERROR(u'Adding resources to {path} is not allowed.') raise FormError, msg.gettext(path=path) # Ok return container
def action_delete(self, resource, context, form): shop = get_shop(resource) try: resource.parent.del_resource(resource.name) except ConsistencyError: # TODO improve message context.message = ERROR(u"You can't delete this product") return return context.come_back(INFO(u'Product deleted !'), goto='../')
def GET(self, resource, context): reference = context.query['reference'] if reference: order = resource.parent.get_resource(str(reference), soft=True) if order: msg = INFO(u'Reference found !') return context.come_back(msg, goto=context.get_link(order)) else: context.message = ERROR(u'Unknow reference "%s"' % reference) return STLForm.GET(self, resource, context)
def action(self, resource, context, form): child = self.make_new_resource(resource, context, form) if child is None: return errors = None try: errors = child.load_ods_file(form['data'], context) except ValueError, e: context.message = ERROR(u'Cannot load: {x}').gettext(x=unicode(e)) return
def on_query_error(self, resource, context): # XXX Should be done in itools kw = {} for key in context.uri.query: if not (key in context.query_error.missing or key in context.query_error.invalid): kw[key] = context.uri.query[key] context.uri.query = kw msg = ERROR(u'Formulaire invalide') return context.come_back(msg, goto=context.uri)
def action(self, resource, context, form): root = context.root if root.get_resource('users/%s' % form['user'], soft=True) is None: context.message = ERROR(u'User do not exist') return shop = get_shop(resource) payments_table = shop.get_resource('payments/%s/payments' % form['payment_way']).handler del form['payment_way'] payments_table.add_record(form) return context.come_back(MSG(u'New payment added !'), goto='./')
def run_next_update_method(self, context, force=False): versions = find_versions_to_update(context, force) while versions['cls_to_update']: messages = run_next_update_method(context, force) if messages: error = ERROR(u'Error during update method. See logs.') messages.insert(0, error) context.message = messages return versions = find_versions_to_update(context, force) # Ok context.message = MSG(u'Updated method has been launched')
def action_add(self, resource, context, form): # Check start time is before end time start = form['new_start'] end = form['new_end'] if start >= end: message = ERROR(u'Start time must be earlier than end time.') context.message = message return # Check the given range is not defined yet timetables = resource.get_value('timetables') if (start, end) in timetables: context.message = ERROR(u'The given range is already defined.') return # Add new range timetables.append((start, end)) timetables.sort() resource.set_value('timetables', timetables) # Ok context.message = messages.MSG_CHANGES_SAVED
def action(self, resource, context, form): root = context.root references_number = form['references_number'] for i in range(1, references_number + 1): reference = form['reference_%s' % i] if not reference: context.message = ERROR( u'[Error] Line number %s has no reference' % i) context.commit = False return new_stock = form['new_stock_%s' % i] search = root.search(reference=reference) results = search.get_documents() if not results: context.message = ERROR(u'[Error] Unknow reference %s' % reference) context.commit = False return # XXX #if len(results) > 1: # context.message = ERROR(u'[Error] Reference %s is used %s times.' % # (reference, len(results))) # context.commit = False # return product = root.get_resource(results[0].abspath) if new_stock: product.set_property('stock-quantity', new_stock) nb_declinations = form['nb_declinations_%s' % i] if nb_declinations == 0: continue #declinations = list(product.search_resources(cls=Declination)) for j in range(1, nb_declinations + 1): suffix = '_%s_%s' % (i, j) name_declination = form['name' + suffix] stock_declination = form['new_stock' + suffix] if stock_declination: declination = product.get_resource(name_declination) declination.set_property('stock-quantity', stock_declination) context.message = INFO(u'Stock quantity has been updated')
def action_add_users(self, resource, context, form): new_users = form['new_users'].strip() users = resource.get_resource('/users') root = context.root added = [] for lineno, line in enumerate(new_users.splitlines()): lastname, email = parseaddr(line) try: email = email.encode('utf-8') except UnicodeEncodeError: email = None if not email or not EmailField.is_valid(email): context.commit = False message = ERROR(u"Unrecognized line {lineno}: {line}") context.message = message.gettext(lineno=lineno + 1, line=line) return if type(lastname) is str: lastname = unicode(lastname) # Is the user already known? user = root.get_user_from_login(email) if user is None: # Register the user user = users.set_user(**{'email': email, 'lastname': lastname}) resource.subscribe_user(user) added.append(user.name) if not added: context.message = ERROR(u"No user added.") return context.body['new_users'] = u"" message = INFO(u"{n} user(s) added.") context.message = message.gettext(n=len(added))
def action_send_registration_key(self, resource, context, form): email = form['email'] # Get the user with the given login name user = self._get_user(resource, context, email) if user is None: message = ERROR(u'There is no user identified as "{username}"', username=email) return context.come_back(message, goto='./;confirm_registration') # Resend confirmation must_confirm = user.get_property('user_must_confirm') if not must_confirm: # Already confirmed message = ERROR(u'Your account has already been confirmed') return context.come_back(message, goto='/') # Ok user.send_confirmation(context, email) message = MSG(u'Your activation key has been sent to your mailbox') return context.come_back(message, goto='./;confirm_registration')
def GET(self, resource, context): if lpod_is_install is False: msg = ERROR(u'Please install LPOD') return context.come_back(msg) document = odf_new_document_from_type('text') body = document.get_body() root = context.root table = odf_create_table(u"Table 1", width=5, height=1, style='table-cell') for brain in root.search(format='product').get_documents(): # Get product product = root.get_resource(brain.abspath) cover = product.get_resource(product.get_property('cover')) # Add line row = odf_create_row(width=5) cell = odf_create_cell(u"") file = context.database.fs.open(cover.handler.key) local_uri = document.add_file(file) image_frame = odf_create_image_frame(local_uri, size=('5cm', '5cm'), position=('0cm', '0cm'), anchor_type='as-char') paragraph = cell.get_element('text:p') paragraph.append(image_frame) cell.append(paragraph) row.set_cell(0, cell) row.set_cell_value(1, brain.reference) row.set_cell_value(2, brain.title) row.set_cell_value(3, u'%s' % product.get_price_without_tax()) table.append_row(row) # Get declinations for d in product.search_resources(cls=Declination): price = d.parent.get_price_without_tax(id_declination=d.name, pretty=True) row = odf_create_row(width=5) row.set_cell_value(1, 'reference') row.set_cell_value(2, d.get_declination_title()) row.set_cell_value(3, u'%s' % price) row.set_cell_value(4, d.get_property('stock-quantity')) table.append(row) body.append(table) f = StringIO() document.save(f) content = f.getvalue() f.close() context.set_content_type('application/vnd.oasis.opendocument.text') context.set_content_disposition('attachment', 'export.odt') return content
def action_remove(self, resource, context, form): container = resource.parent try: container.del_resource(resource.name) except ConsistencyError: err = (u'Referenced resource cannot be removed, check the' u' <a href=";backlinks">backlinks</a>.') context.message = ERROR(err, format='html') return # Ok message = MSG(u'Resource removed') return context.come_back(message, goto=str(container.abspath))
def action_remove(self, resource, context, form): ids = form['ids'] if len(ids) == 0: context.message = ERROR(u'Nothing to remove.') return # New timetables timetables = resource.get_value('timetables') timetables = [ timetable for index, timetable in enumerate(timetables) if index not in ids ] resource.set_property('timetables', timetables) # Ok context.message = INFO(u'Timetable(s) removed successfully.')
def action_confirm_key(self, resource, context, form): # Get the email address form['username'] = form['username'].strip() email = form['username'] # Get the user with the given login name user = self._get_user(resource, context, email) if user is None: message = ERROR(u'There is no user identified as "{username}"', username=email) context.message = message return # Check register key must_confirm = user.get_property('user_must_confirm') if not must_confirm: # Already confirmed message = ERROR(u'Your account has already been confirmed') context.message = message return elif form['key'] != must_confirm: message = ERROR(u'Your activation key is wrong') context.message = message return user.del_property('user_must_confirm') # We log-in user username = str(user.name) crypted = user.get_property('password') cookie = Password.encode('%s:%s' % (username, crypted)) context.set_cookie('__ac', cookie, path='/') context.user = user # Ok message = INFO(u'Operation successful! Welcome.') return context.come_back(message, goto='/users/%s' % user.name)
def action_remove(self, resource, context, form): from countries import CountriesEnumerate ids = form['ids'] for id in ids: datatype = CountriesEnumerate(zone=id) options = datatype.get_options() if len(options) != 0: record = resource.handler.get_record(id) zone = resource.handler.get_record_value(record, 'title') context.message = ERROR(self.del_msg % (zone, len(options))) return resource.handler.del_record(id) # Reindex the resource context.server.change_resource(resource) context.message = INFO(u'Zone(s) deleted')