示例#1
0
    def initGui(self):
        actionId = Rpc.session.execute('/object', 'execute', 'res.users',
                                       'action_get', {})
        action = Rpc.session.execute('/object', 'execute',
                                     'ir.actions.act_window', 'read',
                                     [actionId], False, Rpc.session.context)[0]

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

        self.group = RecordGroup('res.users')
        self.group.load([Rpc.session.uid])
        self.screen.setRecordGroup(self.group)
        self.screen.setupViews(['form'], [viewIds[0]])
        self.screen.display(Rpc.session.uid)

        # Adjust size and center the dialog
        self.adjustSize()
        if self.parent():
            rect = self.parent().geometry()
        else:
            rect = QApplication.desktop().availableGeometry(self)
        self.move(rect.x() + (rect.width() / 2) - (self.width() / 2),
                  rect.y() + (rect.height() / 2) - (self.height() / 2))

        QApplication.restoreOverrideCursor()
 def executeRelation(self, action, id):
     group = RecordGroup(action['model_name'])
     group.load([id])
     record = group.modelByIndex(0)
     action['domain'] = record.evaluateExpression(action['domain'],
                                                  checkLoad=False)
     action['context'] = str(
         record.evaluateExpression(action['context'], checkLoad=False))
     Api.instance.executeAction(action)
示例#3
0
class ScreenDialog(QDialog, ScreenDialogUi):
    def __init__(self, parent):
        QWidget.__init__(self, parent)
        ScreenDialogUi.__init__(self)
        self.setupUi(self)

        self.setMinimumWidth(800)
        self.setMinimumHeight(600)

        self.connect(self.pushOk, SIGNAL("clicked()"), self.accepted)
        self.connect(self.pushCancel, SIGNAL("clicked()"), self.rejected)
        self.group = None
        self.record = None
        self.recordId = None
        self._recordAdded = False
        self._context = {}
        self._domain = []

    def setup(self, model, id=None):
        if self.group:
            return
        self.group = RecordGroup(model, context=self._context)
        self.group.setDomain(self._domain)
        self.screen.setRecordGroup(self.group)
        self.screen.setViewTypes(['form'])
        if id:
            self._recordAdded = False
            self.screen.load([id])
        else:
            self._recordAdded = True
            self.screen.new()
        self.screen.display()
        self.layout().insertWidget(0, self.screen)
        self.screen.show()

    def setAttributes(self, attrs):
        if ('string' in attrs) and attrs['string']:
            self.setWindowTitle(self.windowTitle() + ' - ' + attrs['string'])

    def setContext(self, context):
        self._context = context

    def setDomain(self, domain):
        self._domain = domain

    def rejected(self):
        if self._recordAdded:
            self.screen.remove()
        self.reject()

    def accepted(self):
        self.screen.currentView().store()

        if self.screen.save():
            self.record = self.screen.currentRecord().name()
            self.recordId = self.screen.currentRecord().id
            self.accept()
示例#4
0
class PreferencesDialog(QDialog, PreferencesDialogUi):
    def __init__(self, parent=None):
        QDialog.__init__(self, parent)
        PreferencesDialogUi.__init__(self)
        self.setupUi(self)

        self.connect(self.pushAccept, SIGNAL('clicked()'), self.slotAccept)

        self.setWindowTitle(_('User Preferences'))
        QApplication.setOverrideCursor(Qt.WaitCursor)
        QTimer.singleShot(0, self.initGui)

    def initGui(self):
        actionId = Rpc.session.execute('/object', 'execute', 'res.users',
                                       'action_get', {})
        action = Rpc.session.execute('/object', 'execute',
                                     'ir.actions.act_window', 'read',
                                     [actionId], False, Rpc.session.context)[0]

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

        self.group = RecordGroup('res.users')
        self.group.load([Rpc.session.uid])
        self.screen.setRecordGroup(self.group)
        self.screen.setupViews(['form'], [viewIds[0]])
        self.screen.display(Rpc.session.uid)

        # Adjust size and center the dialog
        self.adjustSize()
        if self.parent():
            rect = self.parent().geometry()
        else:
            rect = QApplication.desktop().availableGeometry(self)
        self.move(rect.x() + (rect.width() / 2) - (self.width() / 2),
                  rect.y() + (rect.height() / 2) - (self.height() / 2))

        QApplication.restoreOverrideCursor()

    def slotAccept(self):
        if not self.screen.currentRecord().validate():
            return

        if self.screen.currentRecord().fieldExists('context_lang'):
            Settings.setValue(
                'client.language',
                self.screen.currentRecord().value('context_lang'))
            Settings.saveToFile()

        Rpc.session.execute('/object', 'execute', 'res.users', 'write',
                            [Rpc.session.uid], self.screen.get())
        Rpc.session.reloadContext()
        self.accept()
示例#5
0
 def create(self, record):
     from Koo.Model.Group import RecordGroup
     group = RecordGroup(resource=self.attrs['relation'],
                         fields={},
                         parent=record,
                         context=self.context(record, eval=False))
     group.setDomainForEmptyGroup()
     group.tomanyfield = self
     self.connect(group, SIGNAL('modified'), self.groupModified)
     return group
示例#6
0
 def executeRelation(self, record, action):
     id = record.get()[self.name]
     group = RecordGroup(self.attributes['relation'])
     group.load([id])
     record = group.modelByIndex(0)
     action = action.copy()
     action['domain'] = record.evaluateExpression(action['domain'],
                                                  checkLoad=False)
     action['context'] = str(
         record.evaluateExpression(action['context'], checkLoad=False))
     Api.instance.executeAction(action)
示例#7
0
 def initGui(self):
     if self.record:
         group = self.record.value(self.name)
     else:
         group = None
     if not group:
         group = RecordGroup(self.attrs['relation'])
         group.setDomainForEmptyGroup()
     self.screen.setRecordGroup(group)
     self.screen.setViewTypes(['tree'])
     self.screen.setEmbedded(True)
示例#8
0
    def init(self):
        self.currentCode = Rpc.session.context.get('lang', 'en_US')

        languageIds = Rpc.session.execute('/object', 'execute', 'res.lang',
                                          'search',
                                          [('translatable', '=', '1')])
        languages = Rpc.session.execute('/object', 'execute', 'res.lang',
                                        'read', languageIds, ['code', 'name'])

        arch = []
        fields = {}
        for lang in languages:
            if self.type == TranslationDialog.LineEdit:
                widget = 'char'
                fieldType = 'char'
            elif self.type == TranslationDialog.TextEdit:
                widget = 'text'
                fieldType = 'text'
            else:
                widget = 'text_tag'
                fieldType = 'text'

            arch.append(
                """<field name="%s" widget="%s" use="{'lang':'%s'}"/>""" %
                (lang['code'], widget, lang['code']))
            fields[lang['code']] = {
                'string': lang['name'],
                'type': fieldType,
            }
            if lang['code'] == self.currentCode:
                self.values[lang['code']] = self.value
                continue

            context = copy.copy(Rpc.session.context)
            context['lang'] = self.adaptContext(lang['code'])
            val = Rpc.session.execute('/object', 'execute', self.model, 'read',
                                      [self.id], [self.fieldName], context)
            val = val[0]

            self.values[lang['code']] = val[self.fieldName]

        arch = '<form string="%s" col="2">%s</form>' % (
            _('Translation Dialog'), ''.join(arch))

        self.group = RecordGroup('translator')
        # Do not allow record loading as most probably 'wizard.'+name model
        # won't exist in the server
        self.group.setDomainForEmptyGroup()
        self.uiScreen.setRecordGroup(self.group)
        self.uiScreen.new(default=False)
        self.uiScreen.addView(arch, fields, display=True)
        self.uiScreen.currentRecord().set(self.values)
        self.uiScreen.display()
示例#9
0
    def __init__(self, arch, fields, state, name, datas, parent=None):
        QDialog.__init__(self, parent)
        self.setModal(True)
        buttons = []
        self.datas = datas
        self.buttonsLayout = QHBoxLayout()
        self.buttonsLayout.addStretch()
        for x in state:
            but = QPushButton(Common.normalizeLabel(x[1]))
            # We store the value to return into objectName property
            but.setObjectName(x[0])
            # The third element is the gtk-icon
            if len(x) >= 3:
                but.setIcon(Icons.kdeIcon(x[2]))
            # The forth element is True if the button is the default one
            if len(x) >= 4 and x[3]:
                but.setDefault(True)
            self.buttonsLayout.addWidget(but)
            but.clicked.connect(self.slotPush)

        val = {}
        for f in fields:
            if 'value' in fields[f]:
                val[f] = fields[f]['value']

        self.group = RecordGroup('wizard.' + name)
        # Do not allow record loading as most probably 'wizard.'+name model
        # won't exist in the server
        self.group.setDomainForEmptyGroup()
        self.screen = Screen(self)
        self.screen.setRecordGroup(self.group)
        self.screen.new(default=False)
        # We don't want the toolbar to be shown at the wizard
        self.screen.setToolbarVisible(False)
        self.screen.addView(arch, fields, display=True)
        # Set default values
        self.screen.currentRecord().set(val)
        # Set already stored values
        self.screen.currentRecord().set(self.datas)
        self.screen.display()

        # Set minimum and maximum dialog size
        size = self.screen.sizeHint()
        self.setMinimumSize(size.width() + 100, min(600, size.height() + 25))
        size = QApplication.desktop().availableGeometry(self).size()
        size -= QSize(50, 50)
        self.setMaximumSize(size)

        self.layout = QVBoxLayout(self)
        self.layout.addWidget(self.screen)
        self.layout.addLayout(self.buttonsLayout)
        self.setWindowTitle(self.screen.currentView().title)
示例#10
0
 def executeRelation(self, action):
     id = self.record.get()[self.name]
     group = RecordGroup(self.attrs['relation'])
     group.load([id])
     record = group.modelByIndex(0)
     # Copy action so we do not update the action, othewise, domain and context would only be
     # evaluated fo the first record but not the following ones.
     action = action.copy()
     action['domain'] = record.evaluateExpression(action['domain'],
                                                  checkLoad=False)
     action['context'] = str(
         record.evaluateExpression(action['context'], checkLoad=False))
     Api.instance.executeAction(action)
示例#11
0
	def initGui(self):
		if self.record:
			group = self.record.value(self.name)
		else:
			group = None
		if not group:
			group = RecordGroup( self.attrs['relation'] )
			group.setDomainForEmptyGroup()

		self.screen.setRecordGroup( group )
		self.screen.setPreloadedViews( self.attrs.get('views', {}) )
		self.screen.setEmbedded( True )
		self.screen.setViewTypes( self.attrs.get('mode', 'tree,form').split(',') )
		self.uiTitle.setText( self.screen.currentView().title )
 def setup(self, model, ident=None):
     if self.group:
         return
     self.group = RecordGroup(model, context=self._context)
     self.group.setDomain(self._domain)
     self.screen.setRecordGroup(self.group)
     self.screen.setViewTypes(['form'])
     if ident:
         self._recordAdded = False
         self.screen.load([ident])
     else:
         self._recordAdded = True
         self.screen.new()
     self.screen.display()
     self.layout().insertWidget(0, self.screen)
     self.screen.show()
示例#13
0
    def createScreen(self):
        self.group = RecordGroup(self.model, context=self.context)
        self.group.setDomainForEmptyGroup()

        screen = Screen()
        screen.setRecordGroup(self.group)
        screen.setEmbedded(True)
        if 'form' in self.viewTypes:
            queue = ViewQueue()
            queue.setup(self.viewTypes, self.viewIds)
            type = ''
            while type != 'form':
                id, type = next(queue)
            screen.setupViews(['form'], [id])
        else:
            screen.setupViews(['form'], [False])
示例#14
0
    def initGui(self):
        group = RecordGroup(self.attrs['relation'])
        group.setDomainForEmptyGroup()

        self.screen.setRecordGroup(group)
        self.screen.setEmbedded(True)
        #self.screen.setViewTypes( ['tree'] )
        # Set the view first otherwise, default values created by self.screen.new()
        # would only be set for those values handled by the current view.
        if 'views' in self.attrs and 'tree' in self.attrs['views']:
            arch = self.attrs['views']['tree']['arch']
            fields = self.attrs['views']['tree']['fields']
            self.screen.addView(arch, fields, display=True)
        else:
            self.screen.addViewByType('tree', display=True)
        treeView = self.screen.currentView().widget
        treeView.setHeaderHidden(True)
    def __init__(self, parent, view, attrs={}):
        AbstractFieldWidget.__init__(self, parent, view, attrs)
        ActionFieldWidgetUi.__init__(self)
        self.setupUi(self)

        self.colors['normal'] = self.palette().color(self.backgroundRole())
        self.act_id = attrs['name']
        res = Rpc.session.execute('/object', 'execute', 'ir.actions.actions',
                                  'read', [self.act_id], ['type'],
                                  Rpc.session.context)
        if not res:
            raise Exception('ActionNotFound')
        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'] = '[]'
            self.context = {'active_id': False, 'active_ids': []}
            self.context.update(
                eval(self.action.get('context', '{}'), self.context.copy()))
            a = self.context.copy()
            a['time'] = time
            a['datetime'] = datetime
            self.domain = Rpc.session.evaluateExpression(
                self.action['domain'], a)

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

                self.recordGroup = RecordGroup(self.action['res_model'],
                                               context=self.context)
                self.recordGroup.setDomain(self.domain)

                # Try to make the impression that it loads faster...
                QTimer.singleShot(0, self.createScreen)
            elif self.action['view_type'] == 'tree':
                pass  # TODO
        self.screen = None
    def setup(self, viewTypes, viewIds):
        if not self.group:
            self.group = RecordGroup(self.model, context=self.context)
            self.group.setDomainForEmptyGroup()
            self.isGroupNew = True

        self.screen.setRecordGroup(self.group)
        self.screen.setEmbedded(True)
        if 'form' in viewTypes:
            queue = ViewQueue()
            queue.setup(viewTypes, viewIds)
            type = ''
            while type != 'form':
                id, type = next(queue)
            self.screen.setupViews(['form'], [id])
        else:
            self.screen.setupViews(['form'], [False])
        self.screen.new()
示例#17
0
    def test_record_field_exist(self):
        """
        Test that fieldExists works

        :return:
        """
        rg = RecordGroup("res.partner", {"name": {"type": "char"}})
        rec = Record(1, rg)
        self.assertTrue(rec.fieldExists("name"))
        self.assertFalse(rec.fieldExists("fail"))
示例#18
0
    def test_record_modified(self):
        """
        Tests that the record is modifed

        :return: None
        """
        rg = RecordGroup("res.partner")
        rec = Record(1, rg)
        self.assertFalse(rec.isModified())
        rec.set({"name": "hola"}, True, False)
        self.assertTrue(rec.isModified())
示例#19
0
    def test_missingFields(self):
        """
        Test the function isFullyLoaded

        :return: None
        """
        fields = {
            "name": {
                "type": "char"
            },
        }

        rg = RecordGroup("res.partner", fields)
        rec = Record(1, rg)
        self.assertEqual(["name"], rec.missingFields())
        rec.set({"name": "ok"})
        self.assertEqual(rec.missingFields(), [])
示例#20
0
 def set(self, record, value, test_state=False, modified=False):
     from Koo.Model.Group import RecordGroup
     # We can't add the context here as it might cause an infinite loop in
     # some cases where a field of the parent appears in the context,
     # and the parent is just being loaded.
     # This has crashed when switching view of the 'account.invoice.line'
     # one2many field in 'account.invoice' view.
     group = RecordGroup(resource=self.attrs['relation'], fields={
     }, parent=record, context=self.context(record, eval=False))
     group.tomanyfield = self
     group.modified.connect(self.groupModified)
     group.setDomain([('id', 'in', value)])
     group.load(value)
     record.values[self.name] = group
     if modified:
         self.changed(record)
示例#21
0
    def test_isFullyLoaded(self):
        """
        Test the function isFullyLoaded

        :return: None
        """
        fields = {
            "name": {
                "type": "char"
            },
        }

        rg = RecordGroup("res.partner", fields)
        rec = Record(1, rg)
        self.assertFalse(rec.isFullyLoaded())
        rec._loaded = True
        self.assertFalse(rec.isFullyLoaded())
        rec.set({"name": "ok"})
        self.assertTrue(rec.isFullyLoaded())
示例#22
0
	def __init__(self, parent=None):
		QDialog.__init__(self, parent)
		loadUi( 'opentemplate.ui', self )

		visible = ['name', 'boxes']
		print Rpc.session.url
		print 'open: ', Rpc.session
		self.fields = Rpc.session.execute('/object', 'execute', 'nan.template', 'fields_get', visible)
		ids = Rpc.session.execute('/object', 'execute', 'nan.template', 'search', [])
		self.group = RecordGroup( 'nan.template', self.fields, ids )
		self.treeModel = KooModel( self )
		self.treeModel.setRecordGroup( self.group )
		self.treeModel.setFields( self.fields )
		self.treeModel.setShowBackgroundColor( False )
		self.treeModel.setMode( KooModel.ListMode )
		self.treeModel.setFieldsOrder( ['name', 'boxes'] )

		self.treeView.setModel( self.treeModel )

		self.connect( self.pushOpen, SIGNAL('clicked()'), self.open )
示例#23
0
    def test_defaults(self):
        """
        Tets the defaults

        :return: None
        """

        fields = {
            "name": {
                "type": "char",
                "required": True
            },
        }

        rg = RecordGroup("res.partner", fields)
        rec = Record(1, rg)
        defaults = {"name": "default value", "no_exists": "somthing"}
        rec.setDefaults(defaults)
        self.assertDictEqual(rec.defaults(), {"name": "default value"})
        self.assertEqual(rec.default("name"), "default value")
示例#24
0
    def batchButton(self):
        viewTypes = self.viewTypes
        viewIds = self.viewIds

        group = RecordGroup(self.model, context=self.context)
        group.setDomainForEmptyGroup()
        group.load(self.screen.selectedIds())

        screen = Screen(self)
        screen.setRecordGroup(self.group)
        screen.setEmbedded(True)
        if 'form' in viewTypes:
            queue = ViewQueue()
            queue.setup(viewTypes, viewIds)
            type = ''
            while type != 'form':
                ident, type = next(queue)
            screen.setupViews(['form'], [ident])
        else:
            screen.setupViews(['form'], [False])

        from Koo.Fields.Button import ButtonFieldWidget
        from Koo.Common import Common

        buttons = {}
        for key, widget in screen.currentView().widgets.items():
            if isinstance(widget, ButtonFieldWidget):
                buttons[str(widget.button.text())] = widget.name

        selectionDialog = Common.SelectionDialog(
            _('Choose action to apply to selected records'), buttons, self)
        if selectionDialog.exec_() == QDialog.Rejected:
            return

        buttonString = selectionDialog.result[0]
        buttonName = selectionDialog.result[1]

        if QMessageBox.question(
                self, _("Batch Update"),
                _("Do you really want to push button '%s' of all selected records?") % buttonString,
                QMessageBox.Yes|QMessageBox.No
        ) == 1:
            return

        for ident in self.screen.selectedIds():
            screen.display(ident)
            screen.currentView().widgets[buttonName].executeButton(screen, ident)

        self.reload()
示例#25
0
    def test_get(self):
        """
        Test the get method

        :return: None
        """

        fields = {
            "name": {
                "type": "char",
                "required": True
            },
        }

        rg = RecordGroup("res.partner", fields)
        rec = Record(1, rg)
        rec.set({"name": "ok"}, True, False)
        # To avoid to try to load from XML RPC connection
        rec._loaded = True
        self.assertDictEqual(rec.get(), {"name": "ok"})
示例#26
0
    def setup(self):
        fields = Rpc.session.execute('/object', 'execute', self.model,
                                     'fields_view_get', False, 'form',
                                     Rpc.session.context)
        fields = fields['fields']
        if self.availableFields:
            for field in list(fields.keys()):
                if not field in self.availableFields:
                    del fields[field]

        oneToManyFields = [(fields[field]['string'], field) for field in fields
                           if fields[field]['type'] == 'many2one']
        oneToManyFields = dict(oneToManyFields)
        selectionDialog = Common.SelectionDialog(
            _('Choose field to insert in batch action'), oneToManyFields, self)
        if selectionDialog.exec_() == QDialog.Rejected:
            return False
        fieldString = selectionDialog.result[0]
        fieldName = selectionDialog.result[1]
        self.newField = fieldName
        fieldModel = fields[fieldName]['relation']
        fields = {
            'many2many': {
                'string': fieldString,
                'name': 'many2many',
                'type': 'many2many',
                'relation': fieldModel,
            }
        }
        arch = ''
        arch += '<?xml version="1.0"?>'
        arch += '<form string="%s">\n' % _('Batch Insert')
        arch += '<label string="%s" colspan="4"/>' % fieldString
        arch += '<field name="many2many" colspan="4" nolabel="1"/>'
        arch += '</form>'
        group = RecordGroup(fieldModel, fields)
        self.screen.setRecordGroup(group)
        self.screen.new(default=False)
        self.screen.addView(arch, fields, display=True)
        return True
示例#27
0
    def test_required(self):
        """
        Test required field works

        :return:
        """
        fields = {
            "name_required": {
                "type": "char",
                "required": True
            },
            "name_required2": {
                "type": "char",
                "required": "True"
            },
            "name_no_required": {
                "type": "char",
                "required": False
            },
            "name_no_required2": {
                "type": "char",
                "required": 'False'
            }
        }

        rg = RecordGroup("res.partner", fields)
        rec = Record(
            1,
            rg,
        )
        # Test isFieldReadOnly with boolean value
        self.assertTrue(rec.isFieldRequired("name_required"))
        self.assertFalse(rec.isFieldRequired("name_no_required"))

        # Test isFieldReadOnly with str value
        self.assertTrue(rec.isFieldRequired("name_required"))
        self.assertFalse(rec.isFieldRequired("name_no_required2"))

        # Checks if a non existing filed readonly is false
        self.assertFalse(rec.isFieldRequired("fail"))
示例#28
0
    def __init__(self,
                 model,
                 sel_multi=True,
                 ids=None,
                 context=None,
                 domain=None,
                 parent=None):
        QDialog.__init__(self, parent)
        SearchDialogUi.__init__(self)
        self.setupUi(self)

        if ids is None:
            ids = []
        if context is None:
            context = {}
        if domain is None:
            domain = []

        self.setModal(True)

        self.ids = ids
        self.result = None
        self.context = context
        self.context.update(Rpc.session.context)
        self.allowMultipleSelection = sel_multi

        self.modelGroup = RecordGroup(model, context=self.context)
        if Settings.value('koo.sort_mode') == 'visible_items':
            self.modelGroup.setSortMode(RecordGroup.SortVisibleItems)
        self.modelGroup.setDomain(domain)
        if self.ids:
            self.modelGroup.setFilter([('id', 'in', ids)])
            #self.reload()

        self.screen.setRecordGroup(self.modelGroup)
        self.screen.setViewTypes(['tree'])

        self.view = self.screen.currentView()
        self.view.setAllowMultipleSelection(self.allowMultipleSelection)
        self.view.setReadOnly(True)
        self.connect(self.view, SIGNAL('activated()'), self.accepted)

        self.model = model

        view_form = Rpc.session.execute('/object', 'execute', self.model,
                                        'fields_view_get', False, 'form',
                                        self.context)
        self.form.setup(view_form['arch'], view_form['fields'], model, domain)
        self.form.hideButtons()
        self.connect(self.form, SIGNAL('keyDownPressed()'),
                     self.setFocusToList)

        self.title = _('Search: %s') % self.form.name
        self.titleResults = _('Search: %s (%%d result(s))') % self.form.name

        self.setWindowTitle(self.title)

        # TODO: Use Designer Widget Promotion instead
        layout = self.layout()
        layout.insertWidget(0, self.screen)
        layout.insertWidget(0, self.form)

        self.form.setFocus()

        self.connect(self.pushNew, SIGNAL("clicked()"), self.new)
        self.connect(self.pushAccept, SIGNAL("clicked()"), self.accepted)
        self.connect(self.pushCancel, SIGNAL("clicked()"), self.reject)
        self.connect(self.pushFind, SIGNAL("clicked()"), self.find)
        self.connect(self.form, SIGNAL("search()"), self.find)

        # Selects all items
        self.select()
示例#29
0
class BatchInsertDialog(QDialog, BatchInsertDialogUi):
    def __init__(self, parent=None):
        QDialog.__init__(self, parent)
        BatchInsertDialogUi.__init__(self)
        self.setupUi(self)

        self.connect(self.pushAccept, SIGNAL('clicked()'), self.save)

        self.ids = []
        self.model = None
        self.context = None
        self.updateOnServer = True
        self.newValues = {}
        self.availableFields = []

    def setModel(self, model):
        self.model = model

    def setContext(self, context):
        self.context = context

    def setAvailableFields(self, fields):
        self.availableFields = fields

    def setUpdateOnServer(self, update):
        self.updateOnServer = update

    def setViewTypes(self, viewTypes):
        self.viewTypes = viewTypes

    def setViewIds(self, viewIds):
        self.viewIds = viewIds

    def setup(self):
        fields = Rpc.session.execute('/object', 'execute', self.model,
                                     'fields_view_get', False, 'form',
                                     Rpc.session.context)
        fields = fields['fields']
        if self.availableFields:
            for field in list(fields.keys()):
                if not field in self.availableFields:
                    del fields[field]

        oneToManyFields = [(fields[field]['string'], field) for field in fields
                           if fields[field]['type'] == 'many2one']
        oneToManyFields = dict(oneToManyFields)
        selectionDialog = Common.SelectionDialog(
            _('Choose field to insert in batch action'), oneToManyFields, self)
        if selectionDialog.exec_() == QDialog.Rejected:
            return False
        fieldString = selectionDialog.result[0]
        fieldName = selectionDialog.result[1]
        self.newField = fieldName
        fieldModel = fields[fieldName]['relation']
        fields = {
            'many2many': {
                'string': fieldString,
                'name': 'many2many',
                'type': 'many2many',
                'relation': fieldModel,
            }
        }
        arch = ''
        arch += '<?xml version="1.0"?>'
        arch += '<form string="%s">\n' % _('Batch Insert')
        arch += '<label string="%s" colspan="4"/>' % fieldString
        arch += '<field name="many2many" colspan="4" nolabel="1"/>'
        arch += '</form>'
        group = RecordGroup(fieldModel, fields)
        self.screen.setRecordGroup(group)
        self.screen.new(default=False)
        self.screen.addView(arch, fields, display=True)
        return True

    def createScreen(self):
        self.group = RecordGroup(self.model, context=self.context)
        self.group.setDomainForEmptyGroup()

        screen = Screen()
        screen.setRecordGroup(self.group)
        screen.setEmbedded(True)
        if 'form' in self.viewTypes:
            queue = ViewQueue()
            queue.setup(self.viewTypes, self.viewIds)
            type = ''
            while type != 'form':
                id, type = next(queue)
            screen.setupViews(['form'], [id])
        else:
            screen.setupViews(['form'], [False])

    def save(self):
        self.screen.currentView().store()
        record = self.screen.currentRecord()
        self.newValues = [x.id for x in record.value('many2many')]
        if record.isModified() and self.newValues:
            if QMessageBox.question(
                    self, _('Batch Insert'),
                    _('Are you sure you want to insert %d records?') %
                    len(self.newValues), _("Yes"), _("No")) == 1:
                return
            if self.updateOnServer:
                screen = self.createScreen()
                for value in self.newValues:
                    record = self.group.create()
                    record.setValue(self.newField, value)
                self.group.save()
        self.accept()
示例#30
0
class ActionFieldWidget(AbstractFieldWidget, ActionFieldWidgetUi):
    def __init__(self, parent, view, attrs={}):
        AbstractFieldWidget.__init__(self, parent, view, attrs)
        ActionFieldWidgetUi.__init__(self)
        self.setupUi(self)

        self.colors['normal'] = self.palette().color(self.backgroundRole())
        self.act_id = attrs['name']
        res = Rpc.session.execute('/object', 'execute', 'ir.actions.actions',
                                  'read', [self.act_id], ['type'],
                                  Rpc.session.context)
        if not res:
            raise Exception('ActionNotFound')
        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'] = '[]'
            self.context = {'active_id': False, 'active_ids': []}
            self.context.update(
                eval(self.action.get('context', '{}'), self.context.copy()))
            a = self.context.copy()
            a['time'] = time
            self.domain = Rpc.session.evaluateExpression(
                self.action['domain'], a)

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

                self.recordGroup = RecordGroup(self.action['res_model'],
                                               context=self.context)
                self.recordGroup.setDomain(self.domain)

                # Try to make the impression that it loads faster...
                QTimer.singleShot(0, self.createScreen)
            elif self.action['view_type'] == 'tree':
                pass  # TODO
        self.screen = None

    def createScreen(self):
        QApplication.setOverrideCursor(Qt.WaitCursor)
        try:
            self.screen = Screen(self)
            self.screen.setRecordGroup(self.recordGroup)
            #self.screen.setDomain( self.domain )
            self.screen.setEmbedded(True)
            if int(self.attrs.get('koo.show_toolbar', '0')):
                self.screen.setToolbarVisible(True)
            else:
                self.screen.setToolbarVisible(False)
            self.connect(self.screen, SIGNAL('activated()'), self.switch)
            mode = (self.action['view_mode'] or 'form,tree').split(',')
            # if self.view_id:
            #self.screen.setViewIds( self.view_id )
            # else:
            #self.screen.setViewTypes( mode )
            self.screen.setupViews(mode, self.view_id)
            self.uiTitle.setText(QString(self.attrs['string'] or ""))
            layout = QVBoxLayout(self.uiGroup)
            layout.setContentsMargins(0, 0, 0, 0)
            layout.addWidget(self.screen)

            self.connect(self.pushSearch, SIGNAL('clicked()'), self.slotSearch)
            self.connect(self.pushSwitchView, SIGNAL('clicked()'), self.switch)
            self.connect(self.pushOpen, SIGNAL('clicked()'), self.slotOpen)

            self.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding)
        except Rpc.RpcException as e:
            pass
        QApplication.restoreOverrideCursor()

    def sizeHint(self):
        return QSize(200, 400)

    def switch(self):
        self.screen.switchView()

    def slotSearch(self):
        win = SearchDialog(self.action['res_model'],
                           domain=self.domain,
                           context=self.context)
        win.exec_()
        if win.result:
            self.screen.clear()
            self.screen.load(win.result)

    def slotOpen(self):
        Api.instance.execute(self.act_id)

    def storeValue(self):
        self.screen.currentView().store()

    def showValue(self):
        if self.screen:
            self.screen.reload()