Esempio n. 1
0
def list_other_entity():

    product_id = request.args(0)

    current_user_entities = [
        _entity.id for _entity in ENTITY_MAPPER().find(person_id=auth.user.id)
    ]
    my_logger.debug(message='user_entities:%s' % current_user_entities)

    entities = ENTITY_MAPPER().find(entity_id=current_user_entities,
                                    negate_id_search=True,
                                    product_id=product_id)

    return dict(entities=entities, product_id=product_id)
Esempio n. 2
0
class STOCK_MAPPER(object):

    def __init__(self):

        self.__product_mapper = PRODUCT_MAPPER()
        self.__entity_mapper = ENTITY_MAPPER()
        self.__unit_mapper = UNIT_MAPPER()

    def __stock_from_row(self, stock_row):

        my_logger.debug(message='%s' % stock_row)
        return STOCK(id=stock_row['stock']['id'],
                                    product=lambda: self.__product_mapper.find(stock_row['stock']['product'])[0],
                                    entity=lambda: self.__entity_mapper.find(stock_row['stock']['entity'])[0],
                                    maximum=stock_row['stock']['maximum'],
                                    maximum_unit=self.__unit_mapper.find(stock_row['stock']['maximum_unit']) if stock_row['stock']['maximum_unit'] is not None else None,
                                    minimum=stock_row['stock']['minimum'],
                                    minimum_unit=self.__unit_mapper.find(stock_row['stock']['minimum_unit']) if stock_row['stock']['minimum_unit'] is not None else None)

    def find(self, product_id, entity_id):

        if type(entity_id) is ListType:
            _stock_rows = current.db((current.db.stock.entity.belongs(tuple(entity_id))) &
                         (current.db.stock.product == product_id) &
                         (current.db.entity.id == current.db.stock.entity)).select()
        else:
            _stock_rows = current.db((current.db.stock.entity == entity_id) &
                         (current.db.stock.product == product_id) &
                         (current.db.entity.id == current.db.stock.entity)).select()

        return [self.__stock_from_row(_stock_row) for _stock_row in _stock_rows]
Esempio n. 3
0
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)
Esempio n. 4
0
def delete():
    entity_mapper = ENTITY_MAPPER()

    entity_id = request.args[0]

    mylogger.debug(message='entity_id:%s' % entity_id)

    _entity = entity_mapper.find(entity_id=entity_id)[0]

    entity_mapper.delete(_entity)

    cc.clear_menu_cache()

    redirect(
        URL(request.application,
            request.controller,
            'list_reload.html',
            args=entity_id,
            vars=request.vars))
Esempio n. 5
0
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)
Esempio n. 6
0
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 options(self, *args1, **args2):
     _auth_user_entities = tuple([
         _ENTITY.id
         for _ENTITY in ENTITY_MAPPER().find(person_id=current.auth.user.id)
     ])
     if self.dbset.query is not None:
         self.dbset.query = self.dbset.query.__and__(
             current.db.store_location.entity.belongs(_auth_user_entities))
     else:
         self.dbset.query = current.db.store_location.entity.belongs(
             _auth_user_entities)
     return super(IS_IN_DB_AND_USER_STORE_LOCATION,
                  self).options(*args1, **args2)
    def __call__(self, *args1, **args2):
        _auth_user_entities = tuple([
            _ENTITY.id
            for _ENTITY in ENTITY_MAPPER().find(person_id=current.auth.user.id)
        ])
        if self._db_set_query_save is not None:
            self.dbset.query = self._db_set_query_save.__and__(
                current.db.entity.id.belongs(_auth_user_entities))
        else:
            self.dbset.query = current.db.entity.id.belongs(
                _auth_user_entities)

        self.build_set()

        return super(IS_IN_DB_AND_USER_ENTITY, self).__call__(*args1, **args2)
Esempio n. 9
0
def list_action():
    '''
    return actions for the entity given in parameter
    '''
    mylogger.debug(message='request.vars:%s' % request.vars)

    entity_mapper = ENTITY_MAPPER()

    _entity_id = request.args[0]

    _entity = entity_mapper.find(entity_id=_entity_id)[0]

    _updatable_entity = False
    _deletable_entity = False

    # if the is_updatable method throws an HTTP exception, conditions are not met
    try:
        is_updatable()
        _updatable_entity = True
        mylogger.debug(message='is updatable:%s' % _entity_id)
    except HTTP:
        mylogger.debug(message='is not updatable:%s' % _entity_id)

    # if the is_deletable method throws an HTTP exception, conditions are not met
    try:
        is_deletable()
        _deletable_entity = True
        mylogger.debug(message='is deletable:%s' % _entity_id)
    except HTTP:
        mylogger.debug(message='is not deletable:%s' % _entity_id)

    session.flash = None

    return dict(entity=_entity,
                updatable_entity=_updatable_entity,
                deletable_entity=_deletable_entity)
Esempio n. 10
0
def list_archive():

    product_id = request.args(0)

    current_user_entities = [
        _entity.id for _entity in ENTITY_MAPPER().find(person_id=auth.user.id)
    ]
    my_logger.debug(message='user_entities:%s' % current_user_entities)

    storages = STORAGE_MAPPER().find(entity_id=current_user_entities,
                                     product_id=product_id,
                                     archive=True)

    request.vars['archive'] = True

    return dict(storages=storages, product_id=product_id)
    def options(self, *args1, **args2):
        # root_entity already filtered by the ENTITY_MAPPER().find function
        _auth_user_entities = tuple([
            _ENTITY.id
            for _ENTITY in ENTITY_MAPPER().find(person_id=current.auth.user.id,
                                                role='all_entity',
                                                negate_role_search=True)
        ])
        if self.dbset.query is not None:
            self.dbset.query = self.dbset.query.__and__(
                current.db.entity.id.belongs(_auth_user_entities))
        else:
            self.dbset.query = current.db.entity.id.belongs(
                _auth_user_entities)

        return super(IS_IN_DB_AND_USER_ENTITY, self).options(*args1, **args2)
Esempio n. 12
0
def list():
    """List all commands."""

    # 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)
    elif 'request' in request.vars and request.vars['request'] == 'accepted':
        status_id = db(db.command_status.label == 'Accepted').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)

    # pagination stuff
    paginate_selector = PaginateSelector(anchor='main')
    paginator = Paginator(paginate=paginate_selector.paginate,
                          extra_vars={'v': 1},
                          anchor='main',
                          renderstyle=False)
    paginator.records = db(_query).count()
    paginate_info = PaginateInfo(paginator.page, paginator.paginate,
                                 paginator.records)

    # querying the database
    _orderby = ~db.command.modification_datetime
    rows = db(_query).select(limitby=paginator.limitby(), orderby=_orderby)

    return dict(commands=rows,
                paginator=paginator,
                paginate_selector=paginate_selector,
                paginate_info=paginate_info)
Esempio n. 13
0
def list():

    my_logger.debug(message='request.vars:%s' % request.vars)

    product_id = request.args[0] if len(
        request.args) > 0 else request.vars['product_id']
    my_logger.debug(message='product_id:%s' % product_id)

    if product_id is None:
        return 'foo'

    current_user_entities = [
        _entity.id for _entity in ENTITY_MAPPER().find(person_id=auth.user.id)
    ]
    my_logger.debug(message='user_entities:%s' % current_user_entities)

    storages = STORAGE_MAPPER().find(product_id=product_id,
                                     entity_id=current_user_entities)

    d = dict(storages=storages, product_id=product_id)

    return response.render(d)
Esempio n. 14
0
def list():
    '''
    lists entities of the authenticated user
    '''
    mylogger.debug(message='request.vars:%s' % request.vars)

    entity_mapper = ENTITY_MAPPER()
    person_mapper = PERSON_MAPPER()

    # getting the authenticated user
    auth_user = person_mapper.find(person_id=auth.user.id)[0]

    # pagination stuff
    paginate_selector = PaginateSelector(anchor='main')
    paginator = Paginator(paginate=paginate_selector.paginate,
                          extra_vars={'v': 1},
                          anchor='main',
                          renderstyle=False)
    paginator.records = entity_mapper.count_all() if auth_user.is_all_entity() \
                                                  else auth_user.compute_nb_entities()
    paginate_info = PaginateInfo(paginator.page, paginator.paginate,
                                 paginator.records)

    # if the authenticated user is in all entities (ie. 'all_entity' entity)
    # retrieving the whole entitities
    if auth_user.is_all_entity():
        auth_user_entitites = entity_mapper.find(limitby=paginator.limitby())
    # else getting the authenticated user entitities
    else:
        auth_user_entitites = entity_mapper.find(person_id=auth.user.id,
                                                 limitby=paginator.limitby())
        # adding the all_entity entity for the whole users
        auth_user_entitites.insert(0, entity_mapper.find(role='all_entity')[0])
        mylogger.debug(message='auth_user_entitites:%s' % auth_user_entitites)

    # putting 'all_entity' at the top of the list
    auth_user_entitites = sorted(
        auth_user_entitites,
        key=lambda k: k.role if k.role != 'all_entity' else '0_%s' % k.role)

    return dict(entities=auth_user_entitites,
                paginator=paginator,
                paginate_selector=paginate_selector,
                paginate_info=paginate_info)
Esempio n. 15
0
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)
Esempio n. 16
0
def build_menu():

    _response_menu = []

    if auth.user:
        _quick_request_menu = []

        _quick_request_menu.append((cc.get_string("MENU_ALL_PC"),
                                    False,
                                    URL(request.application, 'product', 'search.html',
                                    vars={'request': 'all'}),
                                    ))

        if auth.has_permission('select_sc') or \
           auth.has_permission('admin'):
            _quick_request_menu.append((cc.get_string("MENU_PC_BORROW_ENTITY"),
                                        False,
                                        URL(request.application, 'product', 'search.html',
                                        vars={'borrow_entity': '1'}),
                                        ))

        if auth.has_permission('select_sc') or \
           auth.has_permission('admin'):
            _quick_request_menu.append((cc.get_string("MENU_PC_ORG"),
                                        False,
                                        URL(request.application, 'product', 'search.html',
                                        vars={'request': 'organization'}),
                                        ))

        if auth.has_permission('select_sc') or \
           auth.has_permission('admin'):

            for _entity in ENTITY_MAPPER().find(person_id=auth.user.id):

                if _entity.name != 'all_entity':

                    _quick_request_sub_menu = []

                    if auth.has_permission('read_sc') or \
                       auth.has_permission('admin'):

                        for _store_location in STORE_LOCATION_MAPPER().find(entity_id=_entity.id, root=True):

                            if  _store_location.can_store:

                                _quick_request_sub_menu.append((_store_location.name,
                                                                False,
                                                                URL(current.request.application,'product','search.html',
                                                                    vars={'request': 'store_location',
                                                                          'is_in_store_location': _store_location.id,
                                                                          'not_archive': 'True'}),
                                                                get_store_location_submenu(_store_location.id)))
                            else:
                                 _quick_request_sub_menu.append((SPAN(_store_location.name, _class="can_not_store"),
                                                                False,
                                                                None,
                                                                get_store_location_submenu(_store_location.id)))

                    _quick_request_menu.append((_entity.name,
                                               False,
                                               URL(request.application,'product','search.html',
                                                   vars={'request': 'entity',
                                                          'is_in_entity': _entity.id,
                                                          'not_archive': 'True'}),
                                                _quick_request_sub_menu
                                                ))


#     _response_menu = [
#         (cc.get_string("INDEX"), False, URL(request.application,'default','index.html'), []),
#         ]

    if auth.user:

        _tools_menu = []
        if auth.has_permission('read_user') or \
           auth.has_permission('update_sl') or \
           auth.has_permission('update_ent') or \
           auth.has_permission('admin'):
            _tools_menu.append((cc.get_string("MENU_MANAGE_USER"), False, URL(request.application,'entity','search.html')))

        if auth.has_permission('update_coc') or \
           auth.has_permission('admin'):
            _tools_menu.append((cc.get_string("MENU_MANAGE_COC"), False, URL(request.application,'class_of_compounds','list.html')))
            _tools_menu.append((cc.get_string("MENU_MANAGE_PHYSICAL_STATE"), False, URL(request.application,'physical_state','list.html')))

        if auth.has_permission('update_sup') or \
           auth.has_permission('admin'):
            _tools_menu.append((cc.get_string("MENU_MANAGE_SUP"), False, URL(request.application,'supplier','list.html')))

        if auth.has_permission('admin'):
            _tools_menu.append((cc.get_string("ADMIN_TOOL_EXPORT_PRODUCT_DATABASE"),
                                      False,
                                      A(cc.get_string("ADMIN_TOOL_EXPORT_PRODUCT_DATABASE"),
                                        _class='noblockui',
                                        _href=URL(a=request.application, c='product', f='export_to_csv'),
                                        _onclick="displayConsole()")))
            _tools_menu.append((cc.get_string("ADMIN_TOOL_IMPORT_PRODUCT_DATABASE"),
                                      False,
                                      URL(a=request.application, c='product', f='import_from_csv')))

        if auth.has_permission('read_pc') or \
           auth.has_permission('admin'):
            _response_menu.append((cc.get_string("MENU_SEARCH_PC"), False, URL(request.application,'product','search.html'), _quick_request_menu))

        if auth.has_permission('create_pc') or \
           auth.has_permission('admin'):
            _response_menu.append((cc.get_string("MENU_ADD_PC"), False, URL(request.application,'product','create.html'), []))

        if auth.has_permission('read_com') or \
           auth.has_permission('admin'):
            _com_menu = []
            _com_menu.append((cc.get_string("MENU_LIST_COM_MINE"), False, URL(request.application,'command','list.html', vars={'request': 'mine'})))
            _com_menu.append((cc.get_string("MENU_LIST_COM_NEW"), False, URL(request.application,'command','list.html', vars={'request': 'new'})))
            _com_menu.append((cc.get_string("MENU_LIST_COM_ACCEPTED"), False, URL(request.application,'command','list.html', vars={'request': 'accepted'})))
            _com_menu.append((cc.get_string("MENU_LIST_COM_ALL"), False, URL(request.application,'command','list.html', vars={'request': 'all'})))
            _response_menu.append((cc.get_string("MENU_LIST_COM"), False, URL(request.application,'command','list.html'), _com_menu))

        if auth.has_permission('read_user') or \
           auth.has_permission('update_sl') or \
           auth.has_permission('update_ent') or \
           auth.has_permission('update_coc') or \
           auth.has_permission('update_sup') or \
           auth.has_permission('delete_archive') or \
           auth.has_permission('admin'):
           _response_menu.append((cc.get_string("MENU_ADMIN"),
                                  False,
                                  URL(request.application,'tools','list.html'),
                                  _tools_menu))

        _response_menu.append((cc.get_string("MESSAGE"), False, URL(request.application,'message','index.html', [])))

#     _response_menu.append(('test', False, A('test',
#                                             _class='noblockui',
#                                             _href=URL(a=request.application, c='test', f='index.html'),
#                                             _onclick="displayConsole()"), []))

        _response_menu.append((cc.get_string("MENU_EXPOSURE_CARD"),
                               False,
                               URL(request.application,
                                   'exposure_card',
                                   'list.html'),
                               []))

    return _response_menu
Esempio n. 17
0
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)
Esempio n. 18
0
    def __init__(self):

        self.__product_mapper = PRODUCT_MAPPER()
        self.__entity_mapper = ENTITY_MAPPER()
        self.__unit_mapper = UNIT_MAPPER()