def get(self, day, mode, **kw):

        params, data = TinyDict.split(kw)

        options = TinyDict()
        options.selected_day = params.selected_day

        day = time.strptime(day, '%Y-%m-%d')

        options.year = day[0]
        options.month = day[1]

        options.date1 = day
        options.mode = mode

        if params.colors:
            try:
                options.colors = eval(kw['_terp_colors'])
            except:
                pass

        if params.color_values:
            options.color_values = ustr(params.color_values).split(',')

        options.search_domain = params.search_domain or []
        options.use_search = params.use_search
        if params.get('_terp_color_filters'):
            options.color_filters = params.color_filters
        params.kalendar = options

        form = self.create_form(params)

        return dict(calendar=ustr(form.screen.widget.render()),
                    sidebar=ustr(form.sidebar.render()))
Exemple #2
0
    def create(self, saved=False):

        tg_errors = None
        proxy = rpc.RPCProxy('res.users')
        action_id = proxy.action_get({})

        action = rpc.RPCProxy('ir.actions.act_window').read(
            [action_id], False, rpc.session.context)[0]

        view_ids = []
        if action.get('views', []):
            view_ids = [x[0] for x in action['views']]
        elif action.get('view_id', False):
            view_ids = [action['view_id'][0]]

        params = TinyDict()
        params.id = rpc.session.uid
        params.ids = [params.id]
        params.model = 'res.users'
        params.view_type = 'form'
        params.view_mode = ['form']
        params.view_ids = view_ids

        params.string = _('Preferences')

        params.editable = True
        form = self.create_form(params, tg_errors)

        return dict(form=form, params=params, editable=True, saved=saved)
    def new(self,
            model,
            source=None,
            kind=0,
            text=None,
            domain=None,
            context=None,
            **kw):
        """Create new search view...

        @param model: the model
        @param source: the source, in case of m2m, m2o search
        @param kind: 0=normal, 1=m2o, 2=m2m
        @param text: do `name_search` if text is provided
        @param domain: the domain
        @param context: the context
        """

        params = TinyDict()

        params.model = model
        params.domain = domain or []
        params.context = context or {}

        params.source = source
        params.selectable = kind
        params.limit = params.limit or 50

        ctx = dict(rpc.session.context, **(params.context or {}))
        params.ids = []
        proxy = rpc.RPCProxy(model)
        params.search_text = False

        # parent's search_view has no business being in m2o or m2m
        if '_terp_context' in params and 'search_view' in params[
                '_terp_context']:
            params.get('_terp_context').pop('search_view', None)
        if text:
            params.search_text = True
            ids = proxy.name_search(text, params.domain or [], 'ilike', ctx,
                                    False)

            if ids:
                params.ids = [id[0] for id in ids]

                # For m2o, when name_search is called, then its result will be added to existing domain
                params.domain.append(('id', 'in', params.ids))

                params.count = len(ids)
            else:
                params.context['default_name'] = ustr(text)
        elif 'default_name' in params.context:
            del params.context['default_name']

        if kw.get('return_to'):
            params['return_to'] = ast.literal_eval(kw['return_to'])

        return self.create(params)
Exemple #4
0
    def edit(self,
             model,
             id=False,
             ids=None,
             view_ids=None,
             view_mode=['form', 'tree'],
             source=None,
             domain=[],
             context={},
             offset=0,
             limit=20,
             count=0,
             search_domain=None,
             **kw):

        params, data = TinyDict.split({
            '_terp_model': model,
            '_terp_id': id,
            '_terp_ids': ids,
            '_terp_view_ids': view_ids,
            '_terp_view_mode': view_mode,
            '_terp_source': source,
            '_terp_domain': domain,
            '_terp_context': context,
            '_terp_offset': offset,
            '_terp_limit': limit,
            '_terp_count': count,
            '_terp_search_domain': search_domain
        })

        params.editable = True
        params.view_type = 'form'

        if kw.get('default_date'):
            params.context.update({'default_date': kw.get('default_date')})

        cherrypy.request._terp_view_target = kw.get('target')

        if params.view_mode and 'form' not in params.view_mode:
            params.view_type = params.view_mode[-1]

        if params.view_type == 'tree':
            params.view_type = 'form'

        if not params.ids:
            params.count = 0
            params.offset = 0

        # On New O2M
        if params.source:
            current = TinyDict()
            current.id = False
            params[params.source] = current

        return self.create(params)
Exemple #5
0
    def index(self, model):

        params = TinyDict()
        params.model = 'ir.ui.view'
        params.view_mode = ['tree']

        params.domain = [('model', '=', model)]

        screen = tw.screen.Screen(params, selectable=1)
        screen.widget.pageable = False

        return dict(screen=screen, model=model)
Exemple #6
0
    def index(self, model, active=False):

        params = TinyDict()
        params.model = 'workflow'
        params.view_mode = ['tree']

        params.domain = [('osv', '=', model)]

        screen = tw.screen.Screen(params, selectable=1)
        screen.widget.pageable = False

        return dict(screen=screen, model=model, active=active)
    def __init__(self, params):

        self.params = TinyDict(**params.copy())
        self.params.view_type = 'form'

        form = Form().create_form(self.params)

        record = self._make_record(form)
        self.clear()

        self.update(record.copy())
        self['id'] = params.id or False
Exemple #8
0
def execute_window(view_ids,
                   model,
                   res_id=False,
                   domain=None,
                   view_type='form',
                   context={},
                   mode='form,tree',
                   name=None,
                   target=None,
                   limit=None):
    """Performs `actions.act_window` action.

    @param view_ids: view ids
    @param model: a model for which the action should be performed
    @param res_id: resource id
    @param domain: domain
    @param view_type: view type, eigther `form` or `tree`
    @param context: the context
    @param mode: view mode, eigther `form,tree` or `tree,form` or None

    @return: view (mostly XHTML code)
    """

    params = TinyDict()

    params.model = model
    params.ids = res_id
    params.view_ids = view_ids
    params.domain = domain or []
    params.context = context or {}
    params.limit = limit

    if name:
        params.context['_terp_view_name'] = name

    if params.ids and not isinstance(params.ids, list):
        params.ids = [params.ids]

    params.id = (params.ids or False) and params.ids[0]

    mode = mode or view_type

    if view_type == 'form':
        mode = mode.split(',')
        params.view_mode = mode

        return Form().create(params)

    elif view_type == 'tree':
        return Tree().create(params)

    else:
        raise common.message(_("Invalid View!"))
    def mini(self, year, month, forweek=False):
        params = TinyDict()

        params.year = year
        params.month = month
        params.forweek = forweek

        day = tc.utils.Day(params.year, params.month, 1)
        minical = tc.widgets.MiniCalendar(day,
                                          forweek=params.forweek,
                                          highlight=False)

        return minical.render()
def execute_wizard(name, **datas):
    """Executes given wizard with the given data

    @param name: name of the wizard
    @param datas: datas

    @return: wizard view (mostly XHTML code)
    """
    params = TinyDict()
    params.name = name
    params.datas = datas
    params.state = 'init'

    return Wizard().create(params)
Exemple #11
0
    def edit(self,
             model,
             id=False,
             ids=None,
             view_ids=None,
             view_mode=['form', 'tree'],
             view_type='form',
             source=None,
             domain=[],
             context={},
             offset=0,
             limit=50,
             count=0,
             search_domain=None,
             search_data=None,
             filter_domain=None,
             o2m_edit=False,
             **kw):

        notebook_tab = kw.get('notebook_tab') or 0
        params = self._read_form(context,
                                 count,
                                 domain,
                                 filter_domain,
                                 id,
                                 ids,
                                 kw,
                                 limit,
                                 model,
                                 offset,
                                 search_data,
                                 search_domain,
                                 source,
                                 view_ids,
                                 view_mode,
                                 view_type,
                                 notebook_tab,
                                 o2m_edit=o2m_edit,
                                 editable=True)

        if not params.ids:
            params.count = 0

        # On New O2M
        if params.source:
            current = TinyDict()
            current.id = False
            params[params.source] = current

        return self.create(params)
Exemple #12
0
    def save(self, terp_save_only=False, **kw):
        params, data = TinyDict.split(kw)
        params.editable = True

        proxy = rpc.RPCProxy(params.parent_model)

        pprefix = '.'.join(params.o2m.split('/')[:-1])

        if pprefix:
            data = eval(pprefix, TinyDict(**data)).make_dict()

        ctx = context_with_concurrency_info(rpc.session.context,
                                            params.concurrency_info)
        ctx.update(params.parent_context or {})
        ctx.update(params.o2m_context or {})

        id = proxy.write([params.parent_id], data, ctx)

        prefix = params.o2m
        current = params.chain_get(prefix)

        params.load_counter = 1

        ids = current.ids
        fld = params.o2m.split('/')[-1]
        all_ids = proxy.read([params.parent_id], [fld])[0][fld]
        new_ids = [i for i in all_ids if i not in ids]

        current.ids = all_ids
        if new_ids and params.source:
            current.id = new_ids[-1]
            params.o2m_id = current.id
        elif not params.button:
            params.o2m_id = False

        # perform button action
        if params.button:
            current.button = params.button
            current.parent_params = params
            cherrypy.request._terp_view_target = 'new'
            res = self.button_action(current)
            if res:
                return res
        if params.close:
            return """
            <script type="text/javascript">
                jQuery.o2m('refresh_n_close');
            </script>
            """
        return self.create(params)
Exemple #13
0
    def edit(self, model=None, id=False, **kw):

        params = TinyDict()
        params.model = model
        params.id = id

        id = params.id
        if not id:
            res = rpc.RPCProxy('ir.model').search([('model', '=', params.model)
                                                   ])

            id = (res or False) and res[0]

        return super(NewModel, self).edit(model='ir.model', id=id)
Exemple #14
0
    def default(self, id, model, view_id, domain, context):
        params = TinyDict()

        try:
            view_id = int(view_id)
        except:
            view_id = False

        params.ids = id
        params.view_ids = [view_id]
        params.model = model
        params.domain = domain
        params.context = context or {}

        return self.create(params)
    def multiple_groupby(self, model, name, grp_domain, group_by, view_id,
                         view_type, parent_group, group_level, groups, no_leaf,
                         **kw):
        grp_domain = ast.literal_eval(grp_domain)
        view = cache.fields_view_get(model, view_id, view_type,
                                     rpc.session.context.copy())
        group_by = ast.literal_eval(group_by)
        domain = grp_domain
        group_level = ast.literal_eval(group_level)
        groups = ast.literal_eval(groups)
        # build a new TinyDict to correctly handle _terp_* params
        params = TinyDict(**kw)
        editable = params.editable
        selectable = params.selectable or 2
        context = params.context or {}
        context.update({
            'group_by_no_leaf': int(no_leaf),
            'group_by': group_by,
            '__domain': domain
        })
        # we force offset to 0, as in group_by mode only 'limit' have an effect
        # (offset pagination in only for base grouping - which is handled by ListGroup)
        offset = 0
        limit = params.limit or 20
        args = {
            'editable': editable,
            'view_mode': ['tree', 'form', 'calendar', 'graph'],
            'nolinks': 1,
            'group_by_ctx': group_by,
            'selectable': selectable,
            'multiple_group_by': True,
            'sort_key': kw.get('sort_key'),
            'offset': offset,
            'limit': limit,
            'sort_order': kw.get('sort_order')
        }

        listgrp = listgroup.MultipleGroup(name,
                                          model,
                                          view,
                                          ids=None,
                                          domain=domain,
                                          parent_group=parent_group,
                                          group_level=group_level,
                                          groups=groups,
                                          context=context,
                                          **args)
        return listgrp.render()
Exemple #16
0
    def index(self, model, rec_id=None):

        proxy = rpc.RPCProxy("workflow")
        result = proxy.get_active_workitems(model, rec_id)
        wkf = result['wkf']

        if not wkf:
            raise common.message(_('No workflow associated!'))

        params = TinyDict()
        params.update(_terp_view_type='diagram',
                      _terp_model='workflow',
                      _terp_ids=[wkf['id']],
                      _terp_editable=True,
                      _terp_id=wkf['id'],
                      _terp_view_mode=['tree', 'form', 'diagram'])
        return self.create(params)
Exemple #17
0
    def action(self, **kw):
        params, data = TinyDict.split(kw)

        button = TinyDict()

        button.model = params.model
        button.id = params.id
        button.name = params.action
        button.btype = params.kind

        params.button = button

        fobj = form.Form()

        error = ""
        try:
            res = fobj.button_action(params)
        except Exception, e:
            error = str(e)
class Form(TinyInputWidget):
    """A generic form widget
    """

    template = "/openerp/widgets/form/templates/form.mako"

    params = ['id']
    member_widgets = ['frame', 'concurrency_info']

    def __init__(self, prefix, model, view, ids=[], domain=[], context=None, editable=True, readonly=False, nodefault=False, nolinks=1):

        super(Form, self).__init__(prefix=prefix, model=model, editable=editable, readonly=readonly, nodefault=nodefault)
        dom = xml.dom.minidom.parseString(view['arch'].encode('utf-8'))
        root = dom.childNodes[0]
        attrs = node_attributes(root)
        fields = view['fields']
        self.string = attrs.get('string', '')
        self.link = attrs.get('link', nolinks)
        self.model = model
        self.id = None

        proxy = rpc.RPCProxy(model)

        self.context = dict(rpc.session.context,
                                **(context or {}))
        self.context['bin_size'] = True

        values = {}
        defaults = {}
        try:
            if ids:
                lval = proxy.read(ids[:1], fields.keys() + ['__last_update'], self.context)
                if lval:
                    values = lval[0]
                    self.id = ids[0]
                    
                            
                    ConcurrencyInfo.update(self.model, [values])

            elif 'datas' in view: # wizard data

                for f in fields:
                    if 'value' in fields[f]:
                        values[f] = fields[f]['value']

                values.update(view['datas'])

            elif not self.nodefault: # default
                defaults = self.get_defaults(fields, domain, self.context)

            elif 'state' in fields: # if nodefault and state get state only
                defaults = proxy.default_get(['state'], self.context)

            elif 'x_state' in fields: # if nodefault and x_state get x_state only (for custom objects)
                defaults = proxy.default_get(['x_state'], self.context)

        except Exception,e:
            raise common.warning(e)

        if defaults:
            for k, v in defaults.items():
                values.setdefault(k, v)

        self.state = values.get('state', values.get('x_state'))

        # store current record values in request object (see, self.parse & O2M default_get_ctx)
        if not hasattr(cherrypy.request, 'terp_record'):
            cherrypy.request.terp_record = TinyDict()

        self.view_fields = []
        self.nb_couter = 0
        self.frame = self.parse(prefix, dom, fields, values)[0]
        self.values = [values]
        self.concurrency_info = ConcurrencyInfo(self.model, [self.id])

        # We should generate hidden fields for fields which are not in view, as
        # the values of such fields might be used during `onchange`
        for name, attrs in fields.items():
            if name not in self.view_fields:

                kind = attrs.get('type', 'char')
                if not get_widget(kind):
                    continue

                attrs['prefix'] = prefix
                attrs['name'] = name
                attrs['readonly'] = True # always make them readonly

                field = self._make_field_widget(attrs, values.get(name))
                self.frame.add_hidden(field)
Exemple #19
0
    def __init__(self, **attrs):

        super(Action, self).__init__(**attrs)
        self.nolabel = True

        self.act_id= self.name
        
        proxy = rpc.RPCProxy("ir.actions.actions")
        res = proxy.read([self.act_id], ['type'], rpc.session.context)
        if not res:
            raise common.message(_('Action not found'))

        _type=res[0]['type']
        self.action = rpc.session.execute('object', 'execute', _type, 'read', [self.act_id], False, rpc.session.context)[0]

        if 'view_mode' in attrs:
            self.action['view_mode'] = attrs['view_mode']

        if self.action['type']=='ir.actions.act_window':

            if not self.action.get('domain', False):
                self.action['domain']='[]'

            ctx = dict(rpc.session.context,
                       active_id=False,
                       active_ids=[])

            self.context = expr_eval(self.action.get('context', '{}'), ctx)
            self.domain = expr_eval(self.action['domain'], ctx)
            views = dict(map(lambda x: (x[1], x[0]), self.action['views']))
            view_mode = self.action.get('view_mode', 'tree,form').split(',')
            view_ids = map(lambda x: views.get(x, False), view_mode)
            
            if views.keys() != view_mode:
                view_mode = map(lambda x: x[1], self.action['views'])
                view_ids = map(lambda x: x[0], self.action['views'])
            
            if self.action['view_type'] == 'form':

                params = TinyDict()
                params.updateAttrs(
                    model=self.action['res_model'],
                    id=False,
                    ids=None,
                    view_ids=view_ids,
                    view_mode=view_mode,
                    context=self.context,
                    domain=self.domain,
                    offset = 0,
                    limit = 50
                )

                # get pager vars if set
                if hasattr(cherrypy.request, 'terp_params'):
                    current = cherrypy.request.terp_params
                    current = current.chain_get(self.name or '') or current

                    params.updateAttrs(
                        offset=current.offset,
                        limit=current.limit
                    )

                self.screen = screen.Screen(params, prefix=self.name, editable=True, selectable=3)

            elif self.action['view_type']=='tree':
                pass #TODO
Exemple #20
0
    def __init__(self, **attrs):
        #FIXME: validation error in `Pricelist Version`
        attrs['required'] = False

        super(O2M, self).__init__(**attrs)

        self.new_attrs = {'text': _("New"), 'help': _('Create new record.')}
        self.default_get_ctx = attrs.get('default_get', {}) or attrs.get(
            'context', {})

        # get top params dictionary
        params = cherrypy.request.terp_params
        self.source = params.source
        self.edition = params.o2m_edit
        pprefix = ''
        if '/' in self.name:
            pprefix = self.name[:self.name.rindex('/')]

        pparams = params.chain_get(pprefix)
        if (pparams and not pparams.id) or (not pparams and not params.id):
            self.new_attrs = {
                'text': _("Save/New"),
                'help': _('Save parent record.')
            }

        self.parent_id = params.id
        if pparams:
            self.parent_id = pparams.id

        # get params for this field
        current = params.chain_get(self.name)

        self.model = attrs['relation']
        self.link = attrs.get('link', '')
        self.onchange = None  # override onchange in js code

        view = attrs.get('views', {})
        mode = str(attrs.get('mode', 'tree,form')).split(',')

        self.view = view

        view_mode = mode
        view_type = mode[0]
        self.view_type = view_type

        if not current:
            current = TinyDict()

        if current.view_mode: view_mode = current.view_mode
        if current.view_type: view_type = current.view_type

        self.switch_to = view_mode[-1]
        if view_type == view_mode[-1]: self.switch_to = view_mode[0]

        ids = attrs.get('value') or []
        if not isinstance(ids, list):
            ids = [ids]

        current.offset = current.offset or 0
        current.limit = current.limit or 50
        current.count = len(ids or [])

        if current.limit != -1 and not params.sort_key:
            ids = ids[current.offset:current.offset + current.limit]

        if ids:
            if isinstance(ids[0], dict):
                current.default_data = ids
                for item in current.default_data:
                    self.default_value.append(OneToMany.create(item))
                    item['id'] = 0
                ids = []
            elif isinstance(ids[0], tuple):
                [current_id[1] for current_id in ids]

        id = (ids or None) and ids[0]

        if self.name == self.source or self.name == params.source:
            if params.sort_key and ids:
                domain = current.domain or []
                domain.append(('id', 'in', ids))
                limit = current.limit
                if current.limit == -1:
                    limit = 0
                ids = rpc.RPCProxy(self.model).search(
                    domain, current.offset, limit,
                    params.sort_key + ' ' + params.sort_order, current.context)
                id = ids[0]
        if current and params.source and isinstance(
                params.source,
                basestring) and self.name in params.source.split('/'):
            id = current.id

        id = id or None

        current.model = self.model
        current.id = id
        current.ids = ids
        current.view_mode = view_mode
        current.view_type = view_type
        current.domain = current.domain or []
        current.context = current.context or {}

        group_by_ctx = ''
        if self.default_get_ctx:
            ctx = dict(cherrypy.request.terp_record,
                       context=current.context,
                       active_id=self.parent_id or False)
            ctx[attrs['name']] = ids
            # XXX: parent record for O2M
            #if self.parent:
            #    ctx['parent'] = EvalEnvironment(self.parent)

            try:
                context = ctx.copy()
                ctx = expr_eval("dict(%s)" % self.default_get_ctx, context)
                ctx.update(
                    expr_eval("dict(%s)" % attrs.get('context', '{}'),
                              context))
                current.context.update(ctx)
            except:
                pass

            if ctx and ctx.get('group_by'):
                group_by_ctx = ctx.get('group_by')

        # Group By for one2many list.
        if group_by_ctx:
            current.group_by_ctx = group_by_ctx
            current.domain = [('id', 'in', ids)]

        if current.view_type == 'tree' and self.readonly:
            self.editable = False

        if 'default_name' in current.context:
            del current.context['default_name']

        self.screen = Screen(current,
                             prefix=self.name,
                             views_preloaded=view,
                             editable=self.editable,
                             readonly=self.readonly,
                             selectable=0,
                             nolinks=self.link,
                             _o2m=1)

        self.id = id
        self.ids = ids

        if view_type == 'tree':
            self.id = None

        elif view_type == 'form':
            records_count = len(self.screen.ids or [])

            current_record = 0
            if records_count and self.screen.id in self.screen.ids:
                current_record = self.screen.ids.index(self.screen.id) + 1
                self.pager_info = _('%d of %d') % (current_record,
                                                   records_count)
            else:
                self.pager_info = _('- of %d') % (records_count)
Exemple #21
0
    def __init__(self, **attrs):
        super(M2M, self).__init__(**attrs)

        ids = None
        params = getattr(cherrypy.request, 'terp_params', None)
        if not params:
            params = TinyDict()
            params.model = attrs.get('relation', 'model')
            params.ids = attrs.get('value', [])
            params.name = attrs.get('name', '')

        current = params.chain_get(self.name)
        if current and params.source == self.name:
            ids = current.ids

        self.model = attrs.get('relation', 'model')
        self.link = attrs.get('link', None)
        self.onchange = None  # override onchange in js code

        self.relation = attrs.get('relation', '')
        self.domain = attrs.get('domain', [])
        self.context = attrs.get('context', {}) or {}

        view = attrs.get('views', {})
        mode = str(attrs.get('mode', 'tree,form')).split(',')

        self.view = view

        view_mode = mode
        view_type = mode[0]

        self.switch_to = view_mode[-1]
        if view_type == view_mode[-1]: self.switch_to = view_mode[0]

        if ids is None:
            ids = attrs.get('value', [])

        id = (ids or None) and ids[0]

        pprefix = ''
        if '/' in self.name:
            pprefix = self.name[:self.name.rindex('/')]

        if self.name == params.source and params.sort_key and ids:
            self.domain.append(('id', 'in', ids))
            ids = rpc.RPCProxy(self.model).search(
                self.domain, 0, 0, params.sort_key + ' ' + params.sort_order,
                self.context)
            id = ids[0]
        current = params.chain_get(self.name)

        if not current:
            current = TinyDict()

        current.offset = current.offset or 0
        current.limit = current.limit or 50
        current.count = len(ids or [])

        if current.view_mode: view_mode = current.view_mode
        if current.view_type: view_type = current.view_type

        if current and params.source == self.name:
            id = current.id

        id = id or None

        current.model = self.model
        current.id = id

        if isinstance(ids, tuple):
            ids = list(ids)

        current.ids = ids or []
        current.view_mode = view_mode
        current.view_type = view_type
        current.domain = current.domain or []
        current.context = current.context or {}

        if isinstance(self.context, basestring):
            # XXX: parent record for O2M
            #if self.parent:
            #    ctx['parent'] = EvalEnvironment(self.parent)

            try:
                ctx = expr_eval(
                    self.context,
                    dict(cherrypy.request.terp_record,
                         context=current.context,
                         active_id=current.id or False))
                current.context.update(ctx)
            except:
                pass

        if current.view_type == 'tree' and self.readonly:
            self.editable = False

        if self.editable is False:
            selectable = 0
        else:
            selectable = 2

        # try to get original input values if creating validation form
        if not params.filter_action:
            try:
                current.ids = eval(cherrypy.request.terp_data.get(self.name))
            except:
                pass

        self.screen = Screen(current,
                             prefix=self.name,
                             views_preloaded=view,
                             editable=self.editable,
                             readonly=self.editable,
                             selectable=selectable,
                             nolinks=self.link,
                             **{'_m2m': 1})

        self.screen.widget.checkbox_name = False
        self.screen.widget.m2m = True

        self.validator = validators.many2many()
Exemple #22
0
    def __init__(self, prefix, model, view, ids=[], domain=[], context={}, editable=True, readonly=False, nodefault=False, nolinks=1, is_wizard=False):

        super(Form, self).__init__(prefix=prefix, model=model, editable=editable, readonly=readonly, nodefault=nodefault)

        dom = xml.dom.minidom.parseString(view['arch'].encode('utf-8'))
        root = dom.childNodes[0]
        attrs = tools.node_attributes(root)
        fields = view['fields']

        self.string = attrs.get('string', '')
        self.link = attrs.get('link', nolinks)
        self.is_wizard = is_wizard
        self.id = None
        self.context = context or {}

        proxy = rpc.RPCProxy(model)

        ctx = rpc.session.context.copy()
        ctx.update(context)
        ctx['bin_size'] = True

        values = {}
        defaults = {}

        # update values according to domain
        for d in domain:
            if d[0] in fields:
                if d[1] == '=':
                    values[d[0]] = d[2]
                if d[1] == 'in' and len(d[2]) == 1:
                    values[d[0]] = d[2][0]

        if ids:
            lval = proxy.read(ids[:1], fields.keys() + ['__last_update'], ctx)
            if lval:
                values = lval[0]
                self.id = ids[0]
                self._update_concurrency_info(self.model, [values])

        elif 'datas' in view: # wizard data

            for f in fields:
                if 'value' in fields[f]:
                    values[f] = fields[f]['value']

            values.update(view['datas'])

        elif not self.nodefault: # default
            defaults = proxy.default_get(fields.keys(), ctx)

        elif 'state' in fields: # if nodefault and state get state only
            defaults = proxy.default_get(['state'], ctx)

        elif 'x_state' in fields: # if nodefault and x_state get x_state only (for custom objects)
            defaults = proxy.default_get(['x_state'], ctx)

        for k, v in defaults.items():
            values.setdefault(k, v)

        self.state = values.get('state', values.get('x_state'))

        # store current record values in request object (see, self.parse & O2M default_get_ctx)
        if not hasattr(cherrypy.request, 'terp_record'):
            cherrypy.request.terp_record = TinyDict()

        self.view_fields = []
        self.nb_couter = 0
        self.frame = self.parse(prefix, dom, fields, values)[0]
        self.values = [values]
        self.concurrency_info = ConcurrencyInfo(self.model, [self.id])

        # We should generate hidden fields for fields which are not in view, as
        # the values of such fields might be used during `onchange`
        for name, attrs in fields.items():
            if name not in self.view_fields:

                kind = attrs.get('type', 'char')
                if kind not in WIDGETS:
                    continue

                attrs['prefix'] = prefix
                attrs['name'] = name
                attrs['readonly'] = True # always make them readonly

                field = self._make_field_widget(attrs, values.get(name))
                self.frame.add_hidden(field)
def execute_window(view_ids,
                   model,
                   res_id=False,
                   domain=None,
                   view_type='form',
                   context=None,
                   mode='form,tree',
                   name=None,
                   target=None,
                   limit=None,
                   search_view=None,
                   context_menu=False,
                   display_menu_tip=False,
                   action_id=None):
    """Performs `actions.act_window` action.

    @param view_ids: view ids
    @param model: a model for which the action should be performed
    @param res_id: resource id
    @param domain: domain
    @param view_type: view type, eigther `form` or `tree`
    @param context: the context
    @param mode: view mode, eigther `form,tree` or `tree,form` or None

    @return: view (mostly XHTML code)
    """

    params = TinyDict()

    params.model = model
    params.ids = res_id
    params.view_ids = view_ids
    params.domain = domain or []
    params.context = context or {}
    params.limit = limit
    params.search_view = search_view
    params['context_menu'] = context_menu
    params['display_menu_tip'] = display_menu_tip
    params['target'] = target or None
    cherrypy.request._terp_view_name = name or None
    cherrypy.request._terp_view_target = target or None

    if action_id:
        params.action_id = action_id

    if name:
        params.context['_terp_view_name'] = name
    else:
        if params.context.get('_terp_view_name'):
            del params.context['_terp_view_name']

    if params.ids and not isinstance(params.ids, list):
        params.ids = [params.ids]

    params.id = (params.ids or False) and params.ids[0]

    mode = mode or view_type
    if view_type == 'form':
        mode = mode.split(',')
        params.view_mode = mode

        return Form().create(params)

    elif view_type == 'tree':
        return Tree().create(params)

    else:
        raise common.message(_("Invalid View"))
Exemple #24
0
    def create(self, params, tg_errors=None):

        params.view_type = params.view_type or params.view_mode[0]

        if params.view_type == 'tree':
            params.editable = True

        form = self.create_form(params, tg_errors)

        if not tg_errors:
            try:
                cherrypy.session.pop('remember_notebooks')
            except:
                self.reset_notebooks()

        editable = form.screen.editable
        mode = form.screen.view_type
        id = form.screen.id
        ids = form.screen.ids

        buttons = TinyDict()  # toolbar
        links = TinyDict()  # bottom links (customise view, ...)

        buttons.new = not editable or mode == 'tree'
        buttons.edit = not editable and mode == 'form'
        buttons.save = editable and mode == 'form'
        buttons.cancel = editable and mode == 'form'
        buttons.delete = not editable and mode == 'form'
        buttons.pager = mode == 'form'  # Pager will visible in edit and non-edit mode in form view.

        buttons.search = 'tree' in params.view_mode and mode != 'tree'
        buttons.graph = 'graph' in params.view_mode and mode != 'graph'
        buttons.form = 'form' in params.view_mode and mode != 'form'
        buttons.calendar = 'calendar' in params.view_mode and mode != 'calendar'
        buttons.gantt = 'gantt' in params.view_mode and mode != 'gantt'
        buttons.can_attach = id and mode == 'form'
        buttons.has_attach = buttons.can_attach and len(
            form.sidebar.attachments)
        buttons.i18n = not editable and mode == 'form'

        target = getattr(cherrypy.request, '_terp_view_target', None)

        show_header = target != 'new'
        if not int(cherrypy.request.params.get('_terp_header_footer', 1)):
            show_header = False
        cherrypy.request.show_header_footer = show_header

        buttons.toolbar = target != 'new' and not form.is_dashboard

        if cache.can_write('ir.ui.view'):
            links.view_manager = True

        if cache.can_write('workflow'):
            links.workflow_manager = True

        buttons.process = cache.can_read('process.process')

        pager = None
        if buttons.pager:
            pager = tw.pager.Pager(id=form.screen.id,
                                   ids=form.screen.ids,
                                   offset=form.screen.offset,
                                   limit=form.screen.limit,
                                   count=form.screen.count,
                                   view_type=params.view_type)

        return dict(form=form,
                    pager=pager,
                    buttons=buttons,
                    links=links,
                    path=self.path,
                    show_header_footer=show_header)
Exemple #25
0
    def __init__(self, **attrs):

        super(Action, self).__init__(**attrs)
        self.nolabel = True

        self.act_id = self.name
        res = rpc.session.execute('object', 'execute', 'ir.actions.actions',
                                  'read', [self.act_id], ['type'],
                                  rpc.session.context)
        if not res:
            raise _('Action not found!')

        type = res[0]['type']
        self.action = rpc.session.execute('object', 'execute', type, 'read',
                                          [self.act_id], False,
                                          rpc.session.context)[0]

        if 'view_mode' in attrs:
            self.action['view_mode'] = attrs['view_mode']

        if self.action['type'] == 'ir.actions.act_window':

            if not self.action.get('domain', False):
                self.action['domain'] = '[]'

            ctx = rpc.session.context.copy()
            ctx.update({'active_id': False, 'active_ids': []})

            self.context = tools.expr_eval(self.action.get('context', '{}'),
                                           ctx)
            self.domain = tools.expr_eval(self.action['domain'], ctx)

            views = dict(map(lambda x: (x[1], x[0]), self.action['views']))
            view_mode = self.action.get('view_mode', 'tree,form').split(',')
            view_ids = map(lambda x: views.get(x, False), view_mode)

            if self.action['view_type'] == 'form':

                params = TinyDict()
                params.model = self.action['res_model']
                params.id = False
                params.ids = None
                params.view_ids = view_ids
                params.view_mode = view_mode
                params.context = self.context
                params.domain = self.domain

                params.offset = params.offset or 0
                params.limit = params.limit or 20

                # get pager vars if set
                if hasattr(cherrypy.request, 'terp_params'):
                    current = cherrypy.request.terp_params
                    current = current.chain_get(self.name or '') or current

                    params.offset = current.offset
                    params.limit = current.limit

                self.screen = screen.Screen(params,
                                            prefix=self.name,
                                            editable=True,
                                            selectable=3)

            elif self.action['view_type'] == 'tree':
                pass  #TODO
Exemple #26
0
    def create(self, params, tg_errors=None):

        params.view_type = params.view_type or params.view_mode[0]

        if params.view_type == 'tree':
            params.editable = True
        form = self.create_form(params, tg_errors)

        if not tg_errors:
            try:
                cherrypy.session.pop('remember_notebooks')
            except:
                self.reset_notebooks()

        editable = form.screen.editable
        mode = form.screen.view_type
        id = form.screen.id
        buttons = TinyDict()  # toolbar
        buttons.new = (not editable or mode == 'tree') and mode != 'diagram'
        buttons.edit = not editable and (mode == 'form' or mode == 'diagram')
        buttons.save = editable and mode == 'form'
        buttons.cancel = editable and mode == 'form'
        buttons.delete = not editable and mode == 'form'
        buttons.pager = mode == 'form' or mode == 'diagram'  # Pager will visible in edit and non-edit mode in form view.
        buttons.can_attach = id and mode == 'form'
        buttons.i18n = not editable and mode == 'form'
        buttons.show_grid = mode == 'diagram'
        buttons.create_node = mode == 'diagram' and editable

        from openerp.widgets import get_registered_views
        buttons.views = []

        for kind, view in get_registered_views():
            buttons.views.append(
                dict(kind=kind, name=view.name, desc=view.desc))

        target = getattr(cherrypy.request, '_terp_view_target', None)
        buttons.toolbar = (target != 'new'
                           and not form.is_dashboard) or mode == 'diagram'
        pager = None
        if buttons.pager:
            pager = tw.pager.Pager(id=form.screen.id,
                                   ids=form.screen.ids,
                                   offset=form.screen.offset,
                                   limit=form.screen.limit,
                                   count=form.screen.count,
                                   view_type=params.view_type)

        can_shortcut = self.can_shortcut_create()
        shortcut_ids = []

        if cherrypy.session.get('terp_shortcuts'):
            for sc in cherrypy.session['terp_shortcuts']:
                if isinstance(sc['res_id'], tuple):
                    shortcut_ids.append(sc['res_id'][0])
                else:
                    shortcut_ids.append(sc['res_id'])

        title = form.screen.string or ''
        display_name = {}
        if params.view_type == 'form':
            if params.id:
                if form.screen.view.get(
                        'fields') and form.screen.view['fields'].get('name'):
                    display_name = {
                        'field': form.screen.view['fields']['name']['string'],
                        'value':
                        ustr(form.screen.view['fields']['name']['value'])
                    }
                    title = ustr(display_name['field']) + ':' + ustr(
                        display_name['value'])
        elif params.view_type == 'diagram':
            display_name = {
                'field':
                form.screen.view['fields']['name']['string'],
                'value':
                rpc.RPCProxy(params.model).name_get(form.screen.id,
                                                    rpc.session.context)[0][1]
            }

        # For Corporate Intelligence visibility.
        obj_process = rpc.RPCProxy('ir.model').search(
            [('model', '=', 'process.process')]) or None

        tips = params.display_menu_tip
        if params.view_type == params.view_mode[0] and tips:
            tips = tips

        is_dashboard = form.screen.is_dashboard or False
        return dict(form=form,
                    pager=pager,
                    buttons=buttons,
                    path=self.path,
                    can_shortcut=can_shortcut,
                    shortcut_ids=shortcut_ids,
                    display_name=display_name,
                    title=title,
                    tips=tips,
                    obj_process=obj_process,
                    is_dashboard=is_dashboard)
Exemple #27
0
    def __init__(self, **attrs):
        super(M2M, self).__init__(**attrs)

        ids = None
        params = getattr(cherrypy.request, 'terp_params', None)
        if not params:
            params = TinyDict()
            params.model = attrs.get('relation', 'model')
            params.ids = attrs.get('value', [])
            params.name = attrs.get('name', '')

        current = params.chain_get(self.name)
        if current and params.source == self.name:
            ids = current.ids

        self.model = attrs.get('relation', 'model')
        self.link = attrs.get('link', 1)
        self.onchange = None # override onchange in js code

        self.relation = attrs.get('relation', '')
        self.domain = attrs.get('domain', [])
        self.context = attrs.get('context', {}) or {}        

        view = attrs.get('views', {})
        mode = str(attrs.get('mode', 'tree,form')).split(',')

        self.view = view

        view_mode = mode
        view_type = mode[0]

        self.switch_to = view_mode[-1]
        if view_type == view_mode[-1]: self.switch_to = view_mode[0]
        
        if ids is None:
            ids = attrs.get('value', [])

        id = (ids or None) and ids[0]

        pprefix = ''
        if '/' in self.name:
            pprefix = self.name[:self.name.rindex('/')]

        current = params.chain_get(self.name)

        if not current:
            current = TinyDict()

        current.offset = current.offset or 0
        current.limit = current.limit or 0
        current.count = len(ids or [])

        if current.view_mode: view_mode = current.view_mode
        if current.view_type: view_type = current.view_type

        if current and params.source == self.name:
            id = current.id

        id = id or None

        current.model = self.model
        current.id = id

        if isinstance(ids, tuple):
            ids = list(ids)

        current.ids = ids or []
        current.view_mode = view_mode
        current.view_type = view_type
        current.domain = current.domain or []
        current.context = current.context or {}
        
        if isinstance(self.context, basestring):
            ctx = cherrypy.request.terp_record
            ctx['current_date'] = time.strftime('%Y-%m-%d')
            ctx['time'] = time
            ctx['context'] = current.context
            ctx['active_id'] = current.id or False

            # XXX: parent record for O2M
            #if self.parent:
            #    ctx['parent'] = EvalEnvironment(self.parent)

            try:
                ctx = tools.expr_eval(self.context, ctx)
                current.context.update(ctx)
            except:
                pass

        if current.view_type == 'tree' and self.readonly:
            self.editable = False

        if self.editable is False:
            selectable = 0
        else:
            selectable = 2

        # try to get original input values if creating validation form
        if not params.filter_action:
            try:
                current.ids = eval(cherrypy.request.terp_data.get(self.name))
            except:
                pass

        self.screen = Screen(current, prefix=self.name, views_preloaded=view,
                             editable=False, readonly=self.editable,
                             selectable=selectable, nolinks=self.link)
        
        if view_type == 'tree':
            limit = 20
            if self.screen.widget.attr_limit:
                limit = self.screen.widget.attr_limit
            if current.limit == 0:
                current.limit = limit
                
            self.screen.widget.pageable = Pager(ids=current.ids, offset=current.offset, limit=current.limit,
                                                count=current.count, def_limit=limit)

        self.screen.widget.checkbox_name = False
        self.screen.widget.m2m = True

        self.validator = validators.many2many()
Exemple #28
0
 def report(self, report_name=None, **kw):
     import actions
     return actions.execute_report(report_name, **TinyDict(**kw))