def create(): """Create or clone a command.""" # Clone if 'command_clone_id' in request.vars: command_clone_id = request.vars['command_clone_id'] command_clone = db(db.command.id == command_clone_id).select().first() product_id = command_clone.product.id db.command.volume_weight.default = command_clone.volume_weight db.command.unit.default = command_clone.unit db.command.nb_items.default = command_clone.nb_items db.command.funds.default = command_clone.funds db.command.entity.default = command_clone.entity db.command.subteam.default = command_clone.subteam db.command.supplier.default = command_clone.supplier db.command.retailer.default = command_clone.retailer db.command.store_location.default = command_clone.store_location db.command.unit_price.default = command_clone.unit_price db.command.reference.default = command_clone.reference db.command.product_reference.default = command_clone.product_reference db.command.comment.default = command_clone.comment else: product_id = request.args(0) product = db(db.product.id == product_id).select().first() db.command.product.default = product_id status = db(db.command_status.label == 'New').select().first() db.command.status.default = status.id db.command.submitter.default = db.person[auth.user.id] # default to uniq entity current_user_entities = [ _entity.id for _entity in ENTITY_MAPPER().find(person_id=auth.user.id) ] if len(current_user_entities) == 1: db.command.entity.default = current_user_entities[0] form = SQLFORM(db.command, submit_button=cc.get_string("SUBMIT"), fields=[ 'volume_weight', 'unit', 'nb_items', 'funds', 'entity', 'subteam', 'store_location', 'supplier', 'retailer', 'unit_price', 'reference', 'product_reference', 'comment' ]) if form.accepts(request.vars, session): redirect(URL(a=request.application, c=request.controller, f='list')) elif form.errors: session.flash = DIV(cc.get_string("MISSING_FIELDS"), _class="flasherror") return dict(form=form, product=product, is_edit=False)
def ajax_add_vendor(): my_logger.debug(message='request.vars:%s' % request.vars) label = request.vars['text'] if len(label) == 0: return '1;' + cc.get_string("ENTER_A_LABEL") # check that the coc does NOT already exists count = db(db.supplier.label == label).count() if count != 0: return '1;' + cc.get_string("SUPPLIER_ALREADY_EXIST") else: _id = db.supplier.insert(label=label) return '0;' + str(_id)
def create(): my_logger.debug(message='request.vars:%s' % request.vars) product_id = request.args(0) db.storage.product.default = product_id db.storage.barecode.default = STORAGE_MAPPER.create_barecode(product_id) # creating the form db.storage.product.widget.attributes['_disabled'] = 'disabled' form = crud.create( db.storage, next=URL(request.application, 'product', 'details_reload', args=product_id, vars={'load_storage_list': True}), onvalidation=lambda form: clean_unit(form), # onvalidation=lambda form: (clean_unit(form), # generate_barecode(form)), onaccept=lambda form: (duplicate_storage(form), create_stock(form))) if form.errors: session.flash = DIV(cc.get_string("MISSING_FIELDS"), _class="flasherror") cache.ram.clear(regex='.*/storage/list') cache.ram.clear(regex='.*/product/details') return dict(product_id=product_id, form=form)
def update(): storage_id = request.args[0] _storage = STORAGE_MAPPER().find(storage_id)[0] # creating the form db.storage.product.widget.attributes['_disabled'] = 'disabled' form = crud.update( db.storage, storage_id, next=URL(request.application, 'product', 'details_reload', args=_storage.product.id, vars={'load_storage_list': True}), onvalidation=lambda theform: (update_storage_person(theform), save_storage_store_location(theform)), onaccept=lambda theform: (auth.archive( theform, archive_table=db.storage_history, archive_current=False), ), ondelete=lambda theform: (auth.archive( theform, archive_table=db.storage_history, archive_current=False))) if form.errors: session.flash = DIV(cc.get_string("MISSING_FIELDS"), _class="flasherror") cache.ram.clear(regex='.*/storage/list') cache.ram.clear(regex='.*/product/details') return dict(storage_id=storage_id, product_id=_storage.product.id, form=form)
def read(): mylogger.debug(message='request.vars:%s' % request.vars) exposure_card_mapper = EXPOSURE_CARD_MAPPER() product_mapper = PRODUCT_MAPPER() error = '' # getting the exposure card exposure_card = exposure_card_mapper.find(exposure_card_id=request.args[0])[0] if 'cas_number' in request.vars: _product_id = request.vars.cas_number # duclicity check not performed by the field validator #_value, _error = db.exposure_item.product.validate(_product_id) #mylogger.debug(message='_error, _value:%s, %s' % (_error, _value)) # but in the c_exposure_card.py class with an exceptions.AssertionError _product = product_mapper.find(product_id=_product_id)[0] try: exposure_card.add_exposure_item_for_product(_product) exposure_card_mapper.update(exposure_card) except AssertionError, e: error = cc.get_string('EXPOSURE_CARD_PRODUCT_ALREADY_PRESENT_ERROR')
def profile(): mylogger.debug(message='request.vars:%s' %request.vars) person_mapper = PERSON_MAPPER() _person_id = auth.user.id _person = person_mapper.find(person_id=_person_id)[0] # an existing PERSON form = PERSON_FORM(person=_person, readonly_fields=[ 'email', 'creator', 'custom_permission', 'custom_entity', 'is_admin' ]).get_form() if form.accepts(request.vars, session, dbio=False): mylogger.debug(message='form.vars:%s' %form.vars) _person.first_name = form.vars['first_name'] _person.last_name = form.vars['last_name'] _person.contact = form.vars['contact'] # saving the user person_mapper.save_or_update(_person) session.flash=cc.get_string("PERSON_UPDATED") redirect(URL(request.application, 'default', 'index')) else: return dict(form = form)
def represent(values): if 'admin' in values: return 'X' _ret = '' _i = -1 for _item in Permission.ITEMS: _i = _i + 1 _ret = _ret + '<div id="value">' for _action in Permission.ACTIONS: _perm = '%s_%s' % (_action, _item) if _perm in values or _perm in current.settings[ 'disabled_permissions'].keys(): _ret = _ret + '<img src="%s/%s" title="%s"/>' % ( cc.images_base_url, getattr(cc, 'IMAGE_PRIVILEGE_%s' % _action.upper()), cc.get_string('PERMISSION_%s' % _action.upper())) + ' ' _ret = _ret + '</div>' _ret = _ret + '<div id="label">%s</div>' % current.T( Permission.LABELS[_i]) return XML(_ret)
def delete(): """Delete a command.""" command_id = request.args(0) db(db.command.id == command_id).delete() session.flash = cc.get_string("COMMAND_DELETED") return redirect(URL(request.application, request.controller, 'list'))
def clone(): my_logger.debug(message='request.vars:%s' % request.vars) storage_id = request.args(0) user_entity = [ _entity.id for _entity in ENTITY_MAPPER().find(person_id=auth.user.id) ] storage_to_update = db(db.storage.id == storage_id).select().first() product_id = storage_to_update.product db.storage.product.default = storage_to_update.product db.storage.volume_weight.default = storage_to_update.volume_weight db.storage.unit.default = storage_to_update.unit db.storage.comment.default = storage_to_update.comment db.storage.reference.default = storage_to_update.reference db.storage.batch_number.default = storage_to_update.batch_number db.storage.supplier.default = storage_to_update.supplier # getting the user store locations ids my_logger.debug(message='user_entity:%s' % user_entity) rows = db(db.store_location.entity.belongs(tuple(user_entity))).select( db.store_location.id) or None user_store_location_ids = [row.id for row in rows] if rows else None my_logger.debug(message='user_store_location_ids:%s' % user_store_location_ids) # the user as no store locations - leaving... if not user_store_location_ids: # TODO return an error pass # creating the form db.storage.product.widget.attributes['_disabled'] = 'disabled' form = crud.create( db.storage, next=URL(request.application, 'product', 'details_reload', args=product_id, vars={'load_storage_list': True}), # onvalidation=lambda theform: (generate_barecode(theform)), onaccept=lambda form: ( duplicate_storage(form), #update_stock(form) )) if form.errors: session.flash = DIV(cc.get_string("MISSING_FIELDS"), _class="flasherror") cache.ram.clear(regex='.*/storage/list') cache.ram.clear(regex='.*/product/details') return dict(product_id=product_id, form=form)
def __call__(self, value): mylogger.debug(message='__call__') mylogger.debug(message='value:%s' % value) if value is None or value == '0000-00-0': return (value, None) if self.function == 'create': rows = current.db((current.db.product.cas_number == value) & ( current.db.product.specificity == self.specificity)).select( current.db.product.id) if rows and len(rows) != 0: return (value, cc.get_string("DB_PRODUCT_CAS_NUMBER_COMMENT")) else: return (value, None) else: return (value, None)
def toogle_disable(): mylogger.debug(message='request.vars:%s' %request.vars) person_mapper = PERSON_MAPPER() _person_id = request.args[0] # an id _person = person_mapper.find(person_id=_person_id)[0] # an existing PERSON if _person.is_disabled(): _person.enable() else: _person.disable() # saving the user person_mapper.save_or_update(_person) session.flash=cc.get_string("PERSON_UPDATED") return json.dumps({'success': True})
def not_authorized(): return DIV(SPAN(cc.get_string("NOT_AUTHORIZED")))
# You should have received a copy of the Cecill along with Chimithèque. # If not, see <http://www.cecill.info/licences/>. # # SVN Revision: # ------------- # $Id: physical_state.py 194 2015-02-23 16:27:16Z tbellemb $ # from chimitheque_ide_autocomplete import * from chimitheque_logger import chimitheque_logger from plugin_paginator import Paginator, PaginateSelector, PaginateInfo import chimitheque_commons as cc mylogger = chimitheque_logger() crud.messages.record_created = cc.get_string("PHYSICAL_STATE_CREATED") crud.messages.record_updated = cc.get_string("PHYSICAL_STATE_UPDATED") crud.messages.record_deleted = cc.get_string("PHYSICAL_STATE_DELETED") crud.messages.submit_button = cc.get_string("SUBMIT") @auth.requires(auth.has_permission('admin') or auth.has_permission('read_coc')) @auth.requires_login() def list(): # building the query _query = db.physical_state _orderby = db.physical_state.label # pagination stuff paginate_selector = PaginateSelector(anchor='main')
# GNU General Public License for more details. # # You should have received a copy of the Cecill along with Chimithèque. # If not, see <http://www.cecill.info/licences/>. # # SVN Revision: # ------------- # $Id: use.py 194 2015-02-23 16:27:16Z tbellemb $ # from c_storage_mapper import STORAGE_MAPPER from chimitheque_logger import chimitheque_logger import chimitheque_commons as cc mylogger = chimitheque_logger() crud.messages.record_created = cc.get_string("BORROWING_CREATED") crud.messages.record_updated = cc.get_string("BORROWING_UPDATED") crud.messages.record_deleted = cc.get_string("BORROWING_DELETED") crud.messages.delete_label = cc.get_string("CHECK_TO_GIVE_BACK") @auth.requires(auth.has_permission('admin') or auth.has_permission('read_sc')) @auth.requires_login() def create_update(): storage_id = request.args[0] if db(db.borrow.storage == storage_id).count() > 0: return update() else: return create()
def search(): mylogger.debug(message='request.vars:%s' % str(request.vars)) mylogger.debug(message='request.args:%s' % str(request.args)) # some init query_list = [] rows = None persons = None entities = None paginator = '' paginate_selector = '' paginate_info = '' nb_entries = 1 # number of results label = '' # request title, ie. "products in the Chemical Lab. page = int(request.vars['page']) if 'page' in request.vars else 0 result_per_page = int(request.vars['result_per_page'] ) if 'result_per_page' in request.vars else 10 connected_user_entity_ids = db( db.entity.id.belongs([ _entity.id for _entity in ENTITY_MAPPER().find(person_id=auth.user.id) ])).select(cacheable=True) # no way to pass the "keep_last_search" variable while clicking on a "x results per page" link if 'paginate' in request.vars: request.vars['keep_last_search'] = True # # restoring session vars if keep_last_search # if 'keep_last_search' in request.vars: if session.search_display_by: request.vars['display_by'] = session.search_display_by if session.search_person_id: request.vars['member'] = session.search_member if session.search_role: request.vars['role'] = session.search_role del request.vars['keep_last_search'] # # and then cleaning up request vars # for key in ['search_display_by', 'search_member', 'search_role']: if session.has_key(key): mylogger.debug(message='key:%s' % str(key)) mylogger.debug(message='session[key]:%s' % str(session[key])) del session[key] mylogger.debug(message='request.vars:%s' % str(request.vars)) # # display by entity or person # if 'display_by' in request.vars and request.vars['display_by'] == 'person': session.search_display_by = 'person' display_by_person = True else: display_by_person = False session.search_result_per_page = result_per_page session.search_page = page # # building the request # if 'member' in request.vars and request.vars['member'] != '': mylogger.debug(message='case 1') session.search_member = request.vars['member'] _person_entity_ids = db( db.entity.id.belongs([ _entity.id for _entity in ENTITY_MAPPER().find( person_id=request.vars['member']) ])).select(cacheable=True) _common_entity_ids = [ _id for _id in _person_entity_ids if _id in connected_user_entity_ids ] if len(_common_entity_ids) > 0: if display_by_person: query_list.append(db.person.id == request.vars['member']) else: query_list.append(db.entity.id.belongs(_common_entity_ids)) elif 'role' in request.vars and request.vars['role'] != '': mylogger.debug(message='case 2') session.search_role = request.vars['role'] if display_by_person: query_list.append( (db.entity.role.like('%s%%' % request.vars['role'].strip())) | (db.entity.role.like('%%%s%%' % request.vars['role'].strip()))) query_list.append( db.membership.group_id.belongs(connected_user_entity_ids)) query_list.append(db.membership.group_id == db.entity.id) query_list.append(db.membership.user_id == db.person.id) else: query_list.append( (db.entity.role.like('%s%%' % request.vars['role'].strip())) | (db.entity.role.like('%%%s%%' % request.vars['role'].strip()))) query_list.append( db.membership.group_id.belongs(connected_user_entity_ids)) query_list.append(db.membership.group_id == db.entity.id) else: mylogger.debug(message='case 3') if display_by_person: # Need to get users without entities #query_list.append(db.membership.group_id.belongs(connected_user_entity_ids)) query_list.append(db.membership.user_id == db.person.id) else: query_list.append(db.entity.id.belongs(connected_user_entity_ids)) #request.vars['member'] = auth.user.id if len(query_list) != 0: finalQuery = query_list[0] for query in query_list[1:]: mylogger.debug(message='query:%s' % str(query)) finalQuery = finalQuery.__and__(query) mylogger.debug(message='finalQuery:%s' % str(finalQuery)) if display_by_person: _distinct = db.person.id else: _distinct = db.entity.id # # pagination # range_min = page * result_per_page range_max = range_min + result_per_page mylogger.debug(message='page:%s' % page) mylogger.debug(message='result_per_page:%s' % result_per_page) mylogger.debug(message='range_min:%s' % range_min) mylogger.debug(message='range_min:%s' % range_max) theset = db(finalQuery) nb_entries = theset.count(distinct=_distinct) mylogger.debug(message='nb_entries:%i' % nb_entries) paginate_selector = PaginateSelector(anchor='main') paginator = Paginator(paginate=paginate_selector.paginate, extra_vars={'keep_last_search': True}, anchor='main', renderstyle=False) paginator.records = nb_entries paginate_info = PaginateInfo(paginator.page, paginator.paginate, paginator.records) # # executing the query # _limitby = paginator.limitby() if display_by_person: _orderby = db.person.email select_fields = [db.person.ALL] else: _orderby = db.entity.role select_fields = [db.entity.ALL] allrows = theset.select(*select_fields, orderby=_orderby, distinct=True, limitby=_limitby, cacheable=True) rows = allrows mylogger.debug(message='len(rows):%s' % len(rows)) for row in rows: mylogger.debug(message='row:%s' % row) if len(rows) > 0: if not display_by_person: entities = ENTITY_MAPPER().find( entity_id=[row.id for row in rows], orderby=_orderby) mylogger.debug(message='len(entities):%s' % len(entities)) else: persons = PERSON_MAPPER().find( person_id=[row.id for row in rows], orderby=_orderby) mylogger.debug(message='len(persons):%s' % len(persons)) # # building the search form # db.entity.role.widget = SQLFORM.widgets.string.widget #db.person.email.widget=CHIMITHEQUE_MULTIPLE_widget(db.person.email, configuration={'*': {'disable_validate': True}}) # prepopulating form values + default values in the following form declaration db.entity.role.default = request.vars['role'] #db.person.email.default = request.vars['member'] db.entity.role.label = cc.get_string('SEARCH_ENTITY_NAME') #db.person.email.label = cc.get_string('SEARCH_PERSON_EMAIL') form = SQLFORM.factory( db.entity.role, Field('member', 'reference person', default=request.vars['member'], label=cc.get_string('SEARCH_ENTITY_MEMBER'), widget=CHIMITHEQUE_MULTIPLE_widget( db.person.email, configuration={'*': { 'disable_validate': True }})), _action='/%s/%s/search' % (request.application, request.controller), submit_button=cc.get_string("SEARCH")) return dict(form=form, persons=persons, entities=entities, nb_entries=nb_entries, label=label, paginator=paginator, paginate_selector=paginate_selector, paginate_info=paginate_info)
# Chimithèque is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the Cecill along with Chimithèque. # If not, see <http://www.cecill.info/licences/>. # # SVN Revision: # ------------- # $Id: shout.py 194 2015-02-23 16:27:16Z tbellemb $ # import chimitheque_commons as cc crud = Crud(globals(), db) crud.messages.record_created = cc.get_string("SHOUT_CREATED") @auth.requires_login() def ajax_check_shout(): session.forget() if auth.user: nb_shout = db(db.shout.receiver == auth.user.id).count() return str(nb_shout) else: return 0 @auth.requires_login() def load(): session.forget()
def export_to_csv(): mylogger.debug(message='request.vars:%s' % request.vars) field_names = [ 'kind_of_work', 'cpe', 'ppe', 'nb_exposure', 'exposure_time', 'simultaneaous_risk', ] if 'exposure_item' not in request.vars: return None exposure_item_mapper = EXPOSURE_ITEM_MAPPER() exposure_item_ids = request.vars['exposure_item'] if type(exposure_item_ids) is StringType: exposure_item_ids = [exposure_item_ids] export_list = [] for exposure_item_id in exposure_item_ids: exposure_item = exposure_item_mapper.find(exposure_item_id=exposure_item_id)[0] product_name = exposure_item.product.name.label product_cas_number = exposure_item.product.cas_number product_cmr_cat = exposure_item.product.cmr_cat product_symbol = ','.join([s.label for s in exposure_item.product.symbol]) product_hazard_statement = ','.join([h.reference for h in exposure_item.product.hazard_statement]) _row = [product_name, product_cas_number, product_cmr_cat, product_symbol, product_hazard_statement] for field_name in field_names: _field = '%s_%s' % (field_name, exposure_item_id) _field_value = request.vars[_field] mylogger.debug(message='_field:%s' % _field) mylogger.debug(message='_field_value:%s' % _field_value) if _field in request.vars: if field_name == 'cpe' or field_name == 'ppe': if type(_field_value) is StringType: _row.append(db(db[field_name].id == _field_value).select().first().label) else: _val = ','.join([db(db[field_name].id == _field_value_item).select().first().label for _field_value_item in _field_value]) _row.append(_val) else: _row.append(_field_value) else: _row.append('') export_list.append(_row) mylogger.debug(message='export_list:%s' % export_list) response.view = 'product/export_chimitheque.csv' export_header = [ cc.get_string('DB_PRODUCT_NAME_LABEL'), cc.get_string('DB_PRODUCT_CAS_NUMBER_LABEL'), cc.get_string('DB_PRODUCT_CMR_CATEGORY_LABEL'), cc.get_string('DB_PRODUCT_SYMBOL_LABEL'), cc.get_string('DB_PRODUCT_HAZARD_STATEMENT_LABEL'), cc.get_string('DB_EXPOSURE_ITEM_KIND_OF_WORK_LABEL'), cc.get_string('DB_EXPOSURE_ITEM_CPE_LABEL'), cc.get_string('DB_EXPOSURE_ITEM_PPE_LABEL'), cc.get_string('DB_EXPOSURE_ITEM_NB_EXPOSURE_LABEL'), cc.get_string('DB_EXPOSURE_ITEM_EXPOSURE_TIME_LABEL'), cc.get_string('DB_EXPOSURE_ITEM_SIMULTANEAOUS_RISK_LABEL'), ] informations = [ '%s %s' % (auth.user.first_name, auth.user.last_name) ] return dict(filename='exposure_card_chimitheque.csv', informations=informations, csvdata=export_list, field_names=export_header)
from chimitheque_ide_autocomplete import * from c_entity_mapper import ENTITY_MAPPER from c_permission import PERMISSION from c_person_form import PERSON_FORM from c_person_mapper import PERSON_MAPPER from chimitheque_decorators import is_not_myself_or_admin, is_in_same_entity, has_same_permission, is_person_deletable from chimitheque_logger import chimitheque_logger from plugin_paginator import Paginator, PaginateSelector, PaginateInfo import chimitheque_commons as cc if settings['ldap_enable']: import ldap mylogger = chimitheque_logger() crud.messages.record_created = cc.get_string("PERSON_CREATED") crud.messages.record_updated = cc.get_string("PERSON_UPDATED") crud.messages.record_deleted = cc.get_string("PERSON_DELETED") def lang(): """ Set the application language """ del(session.language) session.language = request.vars['lang'] mylogger.debug(message='session.language:%s' %session.language) cache.ram.clear(regex='.*menu_') return redirect(URL(request.application, 'default', 'index'))
def update(): """Update a command.""" command_id = request.args(0) command = db(db.command.id == command_id).select().first() # Don't update a command with a final state if command['status'].state != 0: redirect(URL(a=request.application, c=request.controller, f='list')) form = SQLFORM(db.command, command, submit_button=cc.get_string("SUBMIT"), fields=[ 'status', 'volume_weight', 'unit', 'nb_items', 'funds', 'entity', 'subteam', 'store_location', 'supplier', 'retailer', 'unit_price', 'reference', 'product_reference', 'comment' ]) old_status = command.status if form.accepts(request.vars, session): # Get modified fields command = db(db.command.id == command_id).select().first() new_status = command.status # Integration if new_status.state == 1: barecode = STORAGE_MAPPER.create_barecode(command.product.id) barecode_begin = barecode[0:-1] barecode_number = int(barecode[-1:]) for _ in range(command.nb_items): this_barecode = barecode_begin + str(barecode_number) db.storage.insert(product=command.product, store_location=command.store_location, volume_weight=command.volume_weight, unit=command.unit, nb_items=1, reference=command.product_reference, supplier=command.supplier, comment='', batch_number='', barecode=this_barecode) barecode_number = barecode_number + 1 if old_status != new_status: db.command_log.insert(command=command, before_status=old_status, after_status=new_status) # Notify the submitter message = cc.get_string("COMMAND_UPDATE_MESSAGE_BODY") %(command.submitter.first_name + ' ' + command.submitter.last_name, \ '%d X %.1f%s' % (command.nb_items, command.volume_weight, command.unit.label), \ '%s / %s' % (command.product.cas_number, command.product.name.label), \ T(old_status.label), T(new_status.label)) mail_sent = mail.send( command.submitter.email, subject=cc.get_string("COMMAND_UPDATE_MESSAGE_SUBJECT"), message=message) if mail_sent: session.flash = cc.get_string("EMAIL_SENT") else: session.flash = cc.get_string("ERROR") + mail.error redirect(URL(a=request.application, c=request.controller, f='list')) elif form.errors: session.flash = DIV(cc.get_string("MISSING_FIELDS"), _class="flasherror") return dict(form=form, product=command.product, is_edit=True)
def widget(cls, field, value, disable=False, auth_user_permissions=None, **attributes): mylogger.debug(message='auth_user_permissions:%s' % auth_user_permissions) mylogger.debug(message='value:%s' % value) _widget = super(PermissionWidget, cls).widget(field, value, cols=5, **attributes) _hidden_fields = [] for e in _widget.elements('input'): _value = e.attributes[ '_value'] if '_value' in e.attributes else None _name = e.attributes['_name'] checked = e.attributes[ '_checked'] == 'checked' if '_checked' in e.attributes else False mylogger.debug(message='_value:%s' % _value) mylogger.debug(message='_name:%s' % _name) # tip to "disable" input with None value if _value is None: e.attributes['_name'] = '%s-renamed-to-disable' % _name # disabling checkboxes for default permissions if (_value and _value in current.settings['disabled_permissions'].keys() ) or disable: mylogger.debug(message='NM') e.update(_disabled='disabled') e.update(_class='NM') # checking checkboxes for default permissions set to True # adding an hidden field to pass the value in the form if not disable and current.settings['disabled_permissions'][ _value]: e.update(_checked='checked') _hidden_fields.append( INPUT(_type='hidden', _value=_value, _name=_name)) # hidding checkboxes for permissions not owned by the authenticated user # to avoid action elif (auth_user_permissions is not None) and (_value not in auth_user_permissions): mylogger.debug(message='blocked') e.update(_style='display: none;') if checked: e.update(_class='blocked') try: e.__delitem__('_checked') except KeyError: pass # disabling the hidden if the permission was not set # we could also remove the input if not checked: e.update(_disabled='disabled') _v_header1 = [ cc.get_string("PRODUCT_CARD"), cc.get_string("PRODUCT_CARD_RESTRICTED"), cc.get_string("STORAGE_CARD"), cc.get_string("STORAGE_ARCHIVE"), cc.get_string("STORE_LOCATION"), cc.get_string("ENTITY"), cc.get_string("USER"), cc.get_string("COC"), cc.get_string("SUPPLIER"), cc.get_string("MESSAGE"), cc.get_string("COMMAND") ] _v_header2 = ['', '', '*', '*', '*', '*', '*', '', '', '**', ''] _i = 0 for e in _widget.elements('tr')[:11]: e.insert(0, _v_header1[_i]) _i = _i + 1 _i = 0 for e in _widget.elements('tr')[:11]: e.insert(6, _v_header2[_i]) _i = _i + 1 _h_legend = TR( TR(TD('S: %s' % cc.get_string("PERMISSION_SELECT"), _colspan="7")), TR(TD('R: %s' % cc.get_string("PERMISSION_READ"), _colspan="7")), TR(TD('U: %s' % cc.get_string("PERMISSION_UPDATE"), _colspan="7")), TR(TD('C: %s' % cc.get_string("PERMISSION_CREATE"), _colspan="7")), TR(TD('D: %s' % cc.get_string("PERMISSION_DELETE"), _colspan="7")), TR( TD('*: %s' % cc.get_string("PERMISSION_IN_HIS_ENTITY"), _colspan="7")), TR( TD('**: %s' % cc.get_string("PERMISSION_HIS_MESSAGE"), _colspan="7"))) _h_header = TR(TH(''), TH('S'), TH('R'), TH('U'), TH('C'), TH('D'), TH('')) _widget.element('table').insert(0, _h_header) _widget.element('table').insert(0, _h_legend) _widget.components.extend(_hidden_fields) return _widget
def _create(): mylogger.debug(message='request.vars:%s' %request.vars) mylogger.debug(message='request.args:%s' %request.args) person_mapper = PERSON_MAPPER() entity_mapper = ENTITY_MAPPER() _person_id = request.args[0] if len(request.args) > 0 else None # an id or None if _person_id is None: _person = person_mapper.create() else: _person = person_mapper.find(person_id=_person_id)[0] _all_entity_id = entity_mapper.find(role='all_entity')[0].id form = PERSON_FORM(person=_person).get_form() if form.accepts(request.vars, session, dbio=False): mylogger.debug(message='form.vars:%s' %form.vars) is_virtual = 'is_virtual' in request.vars mylogger.debug(message='is_virtual:%s' %is_virtual) _person.first_name = form.vars['first_name'] _person.last_name = form.vars['last_name'] _person.email = form.vars['email'] _person.contact = form.vars['email'] # initializing the contact with the email address if 'custom_permission' in form.vars.keys(): _person.permissions = [ PERMISSION(name=_permission_name) for _permission_name in form.vars['custom_permission'] ] if 'custom_entity' in form.vars.keys(): _custom_entity = form.vars['custom_entity'] if type(_custom_entity) is not ListType: _custom_entity = [ _custom_entity ] if str(_all_entity_id) in _custom_entity: _custom_entity = [ _all_entity_id ] _person.entities = [ entity_mapper.find(entity_id=_entity_id)[0] for _entity_id in _custom_entity ] if is_virtual: # this is a new person # sending an email to the creator message = cc.get_string("PERSON_VIRTUAL_CREATION_MESSAGE_BODY") %(_person.first_name + ' ' + \ _person.last_name, \ _person.email, \ _person.password) _creator = person_mapper.find(person_id=auth.user.id)[0] # enabling the new person _person.enable() _person.virtual=True mail_sent = mail.send(_creator.email, subject= cc.get_string("PERSON_VIRTUAL_CREATION_MESSAGE_SUBJECT"), message=message) if mail_sent: # saving the user _new_person_id = person_mapper.save_or_update(_person) session.flash=cc.get_string("EMAIL_SENT") else: del(_person) session.flash=cc.get_string("ERROR") + mail.error # sending an email to the new user elif _person.new_person: message = cc.get_string("PERSON_CREATION_MESSAGE_BODY") %(_person.first_name + ' ' + \ _person.last_name, \ _person.email, \ settings['application_url'], \ _person.password_key) mail_sent = mail.send(_person.email, subject= cc.get_string("PERSON_CREATION_MESSAGE_SUBJECT"), message=message) if mail_sent: # saving the user _new_person_id = person_mapper.save_or_update(_person) session.flash=cc.get_string("EMAIL_SENT") else: del(_person) mylogger.error(message='mail.error:%s' % mail.error) session.flash=cc.get_string("ERROR") + str(mail.error) redirect(URL(request.application, request.controller, 'page_reload')) else: # saving the user _new_person_id = person_mapper.save_or_update(_person) session.flash=cc.get_string("PERSON_UPDATED") mylogger.debug(message='_person:%s' %_person) cc.clear_menu_cache() if _person_id is not None: redirect(URL(request.application, request.controller, 'list_reload', args=_person.id, vars=request.vars)) else: redirect(URL(request.application, request.controller, 'page_reload', vars={'member': _new_person_id, 'display_by': 'person'})) else: return dict(form=form, all_entities_id=_all_entity_id)
def __new__(cls, **kwargs): instance = super(PERSON_FORM, cls).__new__(cls) instance.person = kwargs.get('person') # PERSON type instance.readonly = kwargs.get('readonly') or False instance.readonly_fields = kwargs.get('readonly_fields') or [] my_logger.debug(message='instance.person:%s' % instance.person) my_logger.debug(message='instance.person.creator:%s' % instance.person.creator) if instance.person is not None: current.db.person.first_name.default = instance.person.first_name if 'first_name' in instance.readonly_fields: current.db.person.first_name.writable = False current.db.person.last_name.default = instance.person.last_name if 'last_name' in instance.readonly_fields: current.db.person.last_name.writable = False current.db.person.email.default = instance.person.email if 'email' in instance.readonly_fields: current.db.person.email.writable = False current.db.person.contact.default = instance.person.contact if 'contact' in instance.readonly_fields: current.db.person.contact.writable = False current.db.person.email.requires = [ IS_NOT_EMPTY(), IS_EMAIL(), IS_NOT_IN_DB( current.db(current.db.person.id != instance.person.id), current.db.person.email) ] # creator is a computed field and then not shown by web2py # we need to add it manually instance.form = SQLFORM.factory(Field('creator', 'string', writable=not 'creator' in instance.readonly_fields, label=cc.get_string("PERSON_CREATOR_LABEL"), default=instance.person.creator.email \ if instance.person.creator is not None \ else ''), # creator should exists - backward compatibility current.db.person, Field('is_all_entity', 'boolean', label=cc.get_string("PERSON_IS_ALL_ENTITY_LABEL"), comment=cc.get_string("PERSON_IS_ALL_ENTITY_COMMENT"), represent=lambda r: current.T(str(instance.person.is_all_entity())), # disabled if the user is not admin readable=current.auth.has_membership('all_entity') or \ current.auth.has_membership('admin_entity') or \ current.auth.has_permission('admin'), # admin_ENTITY: backward compatibility writable=(current.auth.has_membership('all_entity') or \ current.auth.has_membership('admin_entity') or \ current.auth.has_permission('admin')) and \ not 'custom_entity' in instance.readonly_fields, # for an update request, pre populating the widget if the user is in all entities default=instance.person.is_all_entity(), ), Field('custom_entity', 'list:reference entity', comment=cc.get_string("PERSON_ENTITY_COMMENT"), label=cc.get_string("PERSON_ENTITY_LABEL"), required=True, notnull=True, writable=not 'custom_entity' in instance.readonly_fields, # for an update request, pre populating the widget given the user entities default=[_entity.id for _entity in instance.person.entities] \ if instance.person.entities is not None \ else [], requires=[IS_IN_DB_AND_USER_ENTITY(current.db(current.db.entity.id > 0), current.db.entity.id, current.db.entity._format, multiple=True), IS_ONE_SELECTED(db=current.db, table=current.db.entity, table_set=~current.db.entity.role.like('user_%'))], represent=lambda r: XML(' <br/>'.join(['%s' % (e.name) \ for e in instance.person.entities])) \ if (not instance.person.is_all_entity() and instance.person.entities is not None) else 'X', widget=lambda field, value: SQLFORM.widgets.multiple.widget(field, value, _class='required')), Field('is_admin', 'boolean', label=cc.get_string("PERSON_IS_ADMIN_LABEL"), comment=cc.get_string("PERSON_IS_ADMIN_COMMENT"), represent=lambda r: current.T(str(instance.person.is_admin())), # disabled if the user is not admin readable=current.auth.has_permission('admin'), writable=current.auth.has_permission('admin') and not 'is_admin' in instance.readonly_fields, # for an update request, pre populating the widget if the user is admin default=instance.person.is_admin(), ), Field('custom_permission', 'string', # this does not matter given that we define our own permission widget label=cc.get_string("PERSON_ENTITY_PERMISSION_LABEL"), required=True, notnull=True, writable=not 'custom_permission' in instance.readonly_fields, # for an update request, pre populating the widget given the user permissions default=[_permission.name for _permission in instance.person.permissions], comment=cc.get_string("PERSON_ENTITY_PERMISSION_COMMENT"), requires=IS_CHIMITHEQUE_PERMISSION(), represent=lambda r: PermissionWidget.represent(r), widget=lambda field, value: PermissionWidget.widget(field, value, _class='required', auth_user_permissions=[_permission.name for _permission in PERSON_MAPPER().find_permissions(current.auth.user.id)] \ if not current.auth.has_permission('admin') \ else None)), readonly=instance.readonly, comments=not instance.readonly, next=URL(current.request.application, 'user', 'list'), submit_button=cc.get_string("SUBMIT") ) else: instance.form = SQLFORM.factory( Field('None', 'string', writable=False, readable=False)) return instance
# SVN Revision: # ------------- # $Id: store_location.py 201 2015-03-04 13:08:14Z tbellemb $ # from c_store_location_mapper import STORE_LOCATION_MAPPER from chimitheque_decorators import is_auth_user_member_of_store_location from chimitheque_decorators import is_store_location_deletable from chimitheque_logger import chimitheque_logger import chimitheque_commons as cc from gluon.html import XML from fake import * mylogger = chimitheque_logger() crud.messages.record_created = cc.get_string("STORE_LOCATION_CREATED") crud.messages.record_updated = cc.get_string("STORE_LOCATION_UPDATED") crud.messages.record_deleted = cc.get_string("STORE_LOCATION_DELETED") crud.messages.submit_button = cc.get_string("SUBMIT") @auth.requires(auth.has_permission('admin') or auth.has_permission('read_sl')) @auth.requires( (auth.has_membership('all_entity') or auth.has_membership(request.vars['entity'])) if len(request.vars) != 0 and request.vars['entity'] != '' else True) @auth.requires_login() def ajax_get_entity_store_location_options(): ''' returns store locations of the ENTITY given in parameters as HTML select options
def export_to_csv(): export_list = [] response.view = 'command/export_chimitheque.csv' export_header = [ cc.get_string('DB_PRODUCT_NAME_LABEL'), cc.get_string('DB_PRODUCT_CAS_NUMBER_LABEL'), cc.get_string('DB_COMMAND_SUBMITTER_LABEL'), cc.get_string('DB_COMMAND_NB_ITEMS_LABEL'), cc.get_string('DB_COMMAND_VOLUME_WEIGHT_LABEL'), cc.get_string('DB_COMMAND_UNIT_LABEL'), cc.get_string('DB_COMMAND_FUNDS_LABEL'), cc.get_string('DB_COMMAND_ENTITY_LABEL'), cc.get_string('DB_COMMAND_SUBTEAM_LABEL'), cc.get_string('DB_COMMAND_SUPPLIER_LABEL'), cc.get_string('DB_COMMAND_RETAILER_LABEL'), cc.get_string('DB_COMMAND_UNIT_PRICE_LABEL'), cc.get_string('DB_COMMAND_REFERENCE_LABEL'), cc.get_string('DB_COMMAND_PRODUCT_REFERENCE_LABEL'), cc.get_string('DB_COMMAND_COMMENT_LABEL'), ] # querying the database current_user_entities = [ _entity.id for _entity in ENTITY_MAPPER().find(person_id=auth.user.id) ] if 'request' in request.vars and request.vars['request'] == 'all': _query = db.command.entity.belongs(current_user_entities) elif 'request' in request.vars and request.vars['request'] == 'mine': _query = db.command.submitter == auth.user.id elif 'request' in request.vars and request.vars['request'] == 'new': status_id = db(db.command_status.label == 'New').select( db.command_status.id) _query = db.command.status.belongs( status_id) & db.command.entity.belongs(current_user_entities) else: status_id = db(db.command_status.state == 0).select( db.command_status.id) _query = db.command.status.belongs( status_id) & db.command.entity.belongs(current_user_entities) # querying the database _orderby = ~db.command.modification_datetime rows = db(_query).select(orderby=_orderby) for row in rows: if not row.supplier: sup = '' else: sup = row.supplier.label values = (row.product.name.label, row.product.cas_number, row.submitter.last_name, row.nb_items, row.volume_weight, row.unit.label, \ row.funds, row.entity.role, row.subteam, sup, row.retailer, row.unit_price, row.reference, row.product_reference, row.comment) export_list.append(values) return dict(filename='command_chimitheque.csv', csvdata=export_list, field_names=export_header)
from datetime import date, datetime import json import re from c_entity_mapper import ENTITY_MAPPER from c_product_mapper import PRODUCT_MAPPER from c_storage_mapper import STORAGE_MAPPER from c_store_location_mapper import STORE_LOCATION_MAPPER from chimitheque_logger import chimitheque_logger import chimitheque_commons as cc from fake import * my_logger = chimitheque_logger() crud.messages.record_created = cc.get_string("STORAGE_CREATED") crud.messages.record_updated = cc.get_string("STORAGE_UPDATED") crud.messages.record_deleted = cc.get_string("STORAGE_DELETED") @auth.requires( auth.has_permission('create_sup') or auth.has_permission('admin')) @auth.requires_login() def ajax_add_vendor(): my_logger.debug(message='request.vars:%s' % request.vars) label = request.vars['text'] if len(label) == 0: return '1;' + cc.get_string("ENTER_A_LABEL") # check that the coc does NOT already exists count = db(db.supplier.label == label).count()
# You should have received a copy of the Cecill along with Chimithèque. # If not, see <http://www.cecill.info/licences/>. # # SVN Revision: # ------------- # $Id: class_of_compounds.py 194 2015-02-23 16:27:16Z tbellemb $ # from chimitheque_ide_autocomplete import * from chimitheque_logger import chimitheque_logger from plugin_paginator import Paginator, PaginateSelector, PaginateInfo import chimitheque_commons as cc mylogger = chimitheque_logger() crud.messages.record_created = cc.get_string("COC_CREATED") crud.messages.record_updated = cc.get_string("COC_UPDATED") crud.messages.record_deleted = cc.get_string("COC_DELETED") crud.messages.submit_button = cc.get_string("SUBMIT") @auth.requires(auth.has_permission('admin') or auth.has_permission('read_coc')) @auth.requires_login() def list(): # building the query _query = db.class_of_compounds _orderby = db.class_of_compounds.label # pagination stuff paginate_selector = PaginateSelector(anchor='main')
from chimitheque_logger import chimitheque_logger from c_person_mapper import PERSON_MAPPER from c_product_mapper import PRODUCT_MAPPER from c_exposure_card_mapper import EXPOSURE_CARD_MAPPER from c_exposure_item_mapper import EXPOSURE_ITEM_MAPPER from chimitheque_multiple_widget import CHIMITHEQUE_MULTIPLE_widget from time import strftime import chimitheque_commons as cc import json from exceptions import AssertionError from types import StringType mylogger = chimitheque_logger() crud.messages.record_created = cc.get_string("EXPOSURE_CARD_CREATED") crud.messages.record_updated = cc.get_string("EXPOSURE_CARD_UPDATED") crud.messages.record_deleted = cc.get_string("EXPOSURE_CARD_DELETED") crud.messages.submit_button = cc.get_string("SUBMIT") def _set_exposure_item_attr(exposure_item_id, attribute, value): _value, _error = db.exposure_item[attribute].validate(value) mylogger.debug(message='_value:%s,_error:%s' % (_value, _error)) if _error is not None: return _error exposure_item_mapper = EXPOSURE_ITEM_MAPPER()