Ejemplo n.º 1
0
    def load(self, model, fieldsInfo):
        if self.rowCount() > 0:
            self.removeRows(0, self.rowCount())
        ir_export = Rpc.RpcProxy('ir.exports')
        ir_export_line = Rpc.RpcProxy('ir.exports.line')
        export_ids = ir_export.search([('resource', '=', model)])
        for export in ir_export.read(export_ids):
            fields = ir_export_line.read(export['export_fields'])

            allFound = True
            for f in fields:
                if not f['name'] in fieldsInfo:
                    allFound = False
                    break
            if not allFound:
                continue

            items = [
                QStandardItem(', '.join([f['name'] for f in fields])),
                QStandardItem(str(export['id'])),
                QStandardItem(export['name']),
                QStandardItem(', '.join(
                    [fieldsInfo[f['name']]['string'] for f in fields]))
            ]
            self.rootItem.appendRow(items)
Ejemplo n.º 2
0
        def __init__(self, parent=None):
            QWebView.__init__(self, parent)
            self.setWindowFlags(Qt.Popup)
            self.setFixedSize(600, 400)
            self.manager = Rpc.RpcNetworkAccessManager(
                self.page().networkAccessManager())
            self.page().setNetworkAccessManager(self.manager)
            self.page().setLinkDelegationPolicy(QWebPage.DelegateExternalLinks)
            self.connect(self, SIGNAL('linkClicked(QUrl)'), self.openLink)

            # Determine appropiate position for the popup
            screenHeight = QApplication.desktop().screenGeometry().height()
            screenWidth = QApplication.desktop().screenGeometry().width()
            pos = parent.parent().mapToGlobal(parent.pos())

            # Fix y coordinate
            y = pos.y() + parent.height()
            if y + self.height() > screenHeight:
                y = pos.y() - self.height()
                if y < 0:
                    y = screenHeight - self.height()
            # Fix x coordinate
            x = pos.x()
            if x < 0:
                x = 0
            elif x + self.width() > screenWidth:
                x = screenWidth - self.width()

            self.move(x, y)

            self._label = ''
            self._help = ''
            self._filter = ()
            self._type = None
Ejemplo n.º 3
0
    def search(self):
        if self.isCustomSearch():
            # Do not emit the signal if the server raises an exception with the search
            # which unfortunately can happen in some cases such as some searches with properties.
            # (ie. [('property_product_pricelist.name','ilike','a')])
            value = self.value()
            proxy = Rpc.RpcProxy(self.model, useExecute=False)
            try:
                proxy.search(value, 0, False, False, Rpc.session.context)
            except Rpc.RpcException as e:
                number = 0
                for item in value:
                    if not isinstance(item, tuple):
                        continue

                    valid = True
                    try:
                        self.uiCustomContainer.setItemValid
                        proxy.search([item], 0, False, False,
                                     Rpc.session.context)
                    except Rpc.RpcException as e:
                        valid = False

                    self.uiCustomContainer.setItemValid(number, valid)
                    number += 1

                QMessageBox.warning(
                    self, _('Search Error'),
                    _('Some items of custom search cannot be used. Please, change those in red and try again.'
                      ))
                return

            self.uiCustomContainer.setAllItemsValid(True)

        self.emit(SIGNAL('search()'))
Ejemplo n.º 4
0
 def removeExport(self):
     idx = self.uiPredefined.selectionModel().selectedRows(1)
     if len(idx) != 1:
         return
     idx = idx[0]
     id = int(str(self.storedModel.itemFromIndex(idx).text()))
     ir_export = Rpc.RpcProxy('ir.exports')
     ir_export.unlink([id])
     self.storedModel.load(self.model, self.fieldsInfo)
Ejemplo n.º 5
0
 def updateCompany(self, company=None):
     if not company:
         users = Rpc.RpcProxy('res.users')
         records = users.read([Rpc.session.uid], ['company_id'],
                              Rpc.session.context)
         company = records[0]['company_id']
         if company:
             company = company[1]
         else:
             company = ''
     self.pushCompany.setText(company)
Ejemplo n.º 6
0
 def changeCompany(self):
     action = self.sender()
     company_id = action.data().toInt()[0]
     users = Rpc.RpcProxy('res.users')
     users.write([Rpc.session.uid], {
         'company_id': company_id,
     }, Rpc.session.context)
     Rpc.session.reloadContext()
     self.updateCompany()
     self.closeAllTabs()
     self.openMenuTab()
Ejemplo n.º 7
0
        def __init__(self, parent=None):
            QWidget.__init__(self, parent)
            WebWidgetUi.__init__(self)
            self.setupUi(self)

            self.manager = Rpc.RpcNetworkAccessManager(
                self.uiWeb.page().networkAccessManager())
            self.uiWeb.page().setNetworkAccessManager(self.manager)

            self.name = ''
            self.handlers = {
                'Previous': self.previous,
                'Next': self.__next__,
                'Reload': self.reload,
                'Find': self.find,
            }
Ejemplo n.º 8
0
    def save(self):
        name, ok = QInputDialog.getText(self, '',
                                        _('What is the name of this export?'))
        if not ok:
            return
        ir_export = Rpc.RpcProxy('ir.exports')
        fields = []
        for x in range(0, self.selectedModel.rowCount()):
            fields.append(str(self.selectedModel.item(x).data().toString()))

        ir_export.create({
            'name': str(name),
            'resource': self.model,
            'export_fields': [(0, 0, {
                'name': f
            }) for f in fields]
        })
        self.storedModel.load(self.model, self.fieldsInfo)
Ejemplo n.º 9
0
    def startRequestsTimer(self):
        # Every X minutes check for new requests and put the number of open
        # requests in the appropiate space in the status bar
        frequency = Settings.value('koo.requests_refresh_interval', 5 * 60,
                                   int) * 1000
        if frequency > 0:
            self.requestsTimer.start(frequency)
        else:
            self.requestsTimer.stop()

        # Check for new Koo releases after logging in.
        self.checkNewRelease()

        # We always use the Subscriber as the class itself will handle
        # whether the module exists on the server or not
        self.subscriber = Rpc.Subscriber(Rpc.session, self)
        # Subscribe to changes to res.request (if 'koo' module is installed in the server).
        self.subscriber.subscribe('updated_model:res.request',
                                  self.updateRequestsStatus)
Ejemplo n.º 10
0
    def save(self, reload=True):
        """
        Save the record to the database. It doesn't matter if the record is
        new or already exists.

        :param reload:
        :return:
        """

        from .Group import RecordGroup

        if self.before_save_fnc:
            self.before_save_fnc()

        self.ensureIsLoaded()
        if not self.id:
            value = self.get(get_readonly=False)
            self.id = self.rpc.create(value, self.context())
        else:
            if not self.isModified():
                return self.id
            value = self.get(get_readonly=False, get_modifiedonly=True)
            context = self.context()
            context = context.copy()
            context[ConcurrencyCheckField] = time.time() - self.read_time
            if not self.rpc.write([self.id], value, context):
                return False
        self._loaded = False

        # Delete elements
        for key_name, value in self.values.items():
            if isinstance(value, RecordGroup):
                if value.removedRecords:
                    model = value.resource
                    ids = value.removedRecords
                    Rpc.RpcProxy(model).unlink(ids)
        if reload:
            self.reload()
        if self.group:
            self.group.written(self.id)
        self.modified = False
        return self.id
Ejemplo n.º 11
0
    def inheritView(self):
        view_id = self.attrs.get('x-view')
        if not view_id:
            return
        view_id = re.findall('\d+', view_id)
        if not view_id:
            return
        view_id = int(view_id[0])
        view = Rpc.RpcProxy('ir.ui.view')
        records = view.read([view_id], ['name', 'model', 'xml_id'])
        record = records[0]

        id = record['xml_id'].split('.')[-1]

        arch = """
<openerp>
<data>
    <record model="ir.ui.view" id="%(id)s">
        <field name="name">%(name)s</field>
        <field name="model">%(model)s</field>
	<field name="type">form</field>
        <field name="inherit_id" ref="%(xml_id)s"/>
        <field name="arch" type="xml">
            <field name="%(field)s" position="after">
		<field name=""/>
            </field>
        </field>
    </record>
</data>
</openerp>""" % {
            'id': id,
            'name': record['name'],
            'model': record['model'],
            'xml_id': record['xml_id'],
            'field': self.attrs.get('name', ''),
        }
        fd, fileName = tempfile.mkstemp(suffix='.txt')
        os.write(fd, arch)
        os.close(fd)
        Common.openFile(fileName)
Ejemplo n.º 12
0
    def save(self, reload=True):
        """
        Save the record to the database. It doesn't matter if the record is
        new or already exists.

        :param reload:
        :return:
        """
        from .Group import RecordGroup
        self.ensureIsLoaded()
        dialog_container = False
        is_modal = False
        action = ''
        write_res = False
        create_res = False
        try:
            try:
                dialog_container = self.sender().parentWidget().parentWidget(
                ).parentWidget()
                is_modal = dialog_container.isModal()
            except Exception:
                pass
            if not self.id:
                values = self.get(get_readonly=False)
                action = 'create'
                context = self.context()
                fill_geom = (
                    'geom' in context
                    and ('geom' not in values or
                         ('geom' in values and not values.get('geom', True)))
                    and 'geom' in self.rpc.fields_get())
                if fill_geom:
                    values['geom'] = context['geom']
                create_res = self.rpc.create_qread(values,
                                                   self.group.allFieldNames(),
                                                   context, '_classic_read')
                self.id = create_res['id']
            else:
                context = self.context()
                if not self.isModified():
                    if is_modal:
                        QTimer.singleShot(0, dialog_container.accept)
                    if self.after_save_function and context.get(
                            'from_search', False):
                        self.after_save_function(self.id, {})
                    return self.id
                values = self.get(get_readonly=False, get_modifiedonly=True)
                context = context.copy()
                context[ConcurrencyCheckField] = time.time() - self.read_time
                action = 'write'
                write_res = self.rpc.write_qread(self.id, values,
                                                 self.group.allFieldNames(),
                                                 context, '_classic_read')
                if not write_res:
                    if is_modal:
                        QTimer.singleShot(0, dialog_container.accept)
                    return False
            self._loaded = False

            # Delete elements
            for key_name, value in self.values.items():
                if isinstance(value, RecordGroup):
                    if value.removedRecords:
                        model = value.resource
                        ids = value.removedRecords
                        Rpc.RpcProxy(model).unlink(ids)
            if write_res:
                self.set(write_res, signal=False)
                Rpc.session.context['skip_reload'] = True
            elif create_res:
                self.set(create_res, signal=False)
                Rpc.session.context['skip_reload'] = True
            elif reload:
                self.reload()
                Rpc.session.context['skip_reload'] = True
            if self.group:
                self.group.written(self.id)
            self.modified = False
            if self.after_save_function:
                self.after_save_function(self.id, values)
            if is_modal:
                QTimer.singleShot(0, dialog_container.accept)
            return self.id
        except Exception as e:
            if action == 'create':
                # Si venim d'un CREATE s'ha de fer rollback i donar info de
                # l'error.
                if self.error_procedure:
                    self.error_procedure(action, e)
                if is_modal:
                    QTimer.singleShot(0, dialog_container.accept)
            elif action == 'write':
                # Si venim d'un WRITE s'ha de donar info de l'error i de que
                # l'accio s'ha invalidat i no ha tingut cap efecte
                if self.error_procedure:
                    self.error_procedure(action, e)
            return False
Ejemplo n.º 13
0
    def __init__(self,
                 model,
                 res_id=False,
                 domain=None,
                 view_type=None,
                 view_ids=None,
                 context=None,
                 parent=None,
                 name=False):
        QWidget.__init__(self, parent)
        FormWidgetUi.__init__(self)
        self.setupUi(self)

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

        # This variable holds the id used to update status (and show number of attachments)
        # If it doesn't change we won't update the number of attachments, avoiding some server
        # calls.
        self.previousId = False
        self.previousAttachments = False

        # Workaround: In some cases (detected in some CRM actions) view_type and view_ids
        # may contain duplicate entries. Here we remove duplicates (ensuring lists order is kept).
        if view_type:
            new_view_ids = []
            new_view_type = []
            for i in range(len(view_type)):
                if not view_type[i] in new_view_type:
                    if i < len(view_ids):
                        new_view_ids.append(view_ids[i])
                    new_view_type.append(view_type[i])
            view_ids = new_view_ids
            view_type = new_view_type

        if not view_type:
            view_type = ['form', 'tree']
        else:
            if view_type[0] in ['graph'] and not res_id:
                res_id = Rpc.session.execute('/object', 'execute', model,
                                             'search', domain)
        fields = {}
        self.model = model
        self.previousAction = None
        self.fields = fields
        self.domain = domain
        self.context = context
        self.viewTypes = view_type
        self.viewIds = view_ids

        self._switchViewMenu = QMenu(self)
        self._viewActionGroup = QActionGroup(self)
        self._viewActionGroup.setExclusive(True)
        for view in self.viewTypes:
            action = ViewFactory.viewAction(view, self)
            if not action:
                continue
            self.connect(action, SIGNAL('triggered()'), self.switchView)
            self._switchViewMenu.addAction(action)
            self._viewActionGroup.addAction(action)

        self.group = RecordGroup(self.model, context=self.context)
        if Settings.value('koo.sort_mode') == 'visible_items':
            self.group.setSortMode(RecordGroup.SortVisibleItems)
        self.group.setDomain(domain)
        self.connect(self.group, SIGNAL('modified'), self.notifyRecordModified)

        self.screen.setRecordGroup(self.group)
        self.screen.setEmbedded(False)
        self.connect(self.screen, SIGNAL('activated()'), self.switchToForm)
        self.connect(self.screen, SIGNAL('currentChanged()'),
                     self.updateStatus)
        self.connect(self.screen, SIGNAL('closed()'), self.closeWidget)
        self.connect(self.screen, SIGNAL('recordMessage(int,int,int)'),
                     self.updateRecordStatus)
        self.connect(self.screen, SIGNAL('statusMessage(QString)'),
                     self.updateStatus)

        self._allowOpenInNewWindow = True

        # Remove ids with False value
        self.screen.setupViews(view_type, view_ids)

        if name:
            self.name = name
        else:
            self.name = self.screen.currentView().title

        self.handlers = {
            'New': self.new,
            'Save': self.save,
            'Export': self.export,
            'Import': self.import_,
            'Delete': self.remove,
            'Find': self.search,
            'Previous': self.previous,
            'Next': self.__next__,
            'GoToResourceId': self.goto,
            'AccessLog': self.showLogs,
            'Reload': self.reload,
            'Switch': self.switchView,
            'Attach': self.showAttachments,
            'Duplicate': self.duplicate,
            'BatchInsert': self.batchInsert,
            'BatchUpdate': self.batchUpdate,
            'BatchButton': self.batchButton,
            'BatchUpdateField': self.batchUpdateField,
            'StoreViewSettings': self.storeViewSettings,
        }

        if res_id:
            if isinstance(res_id, int):
                res_id = [res_id]
            self.screen.load(res_id)
        else:
            if len(view_type) and view_type[0] == 'form':
                self.screen.new()

        self.updateSwitchView()

        self.reloadTimer = QTimer(self)
        self.connect(self.reloadTimer, SIGNAL('timeout()'), self.autoReload)
        self.pendingReload = False

        # We always use the Subscriber as the class itself will handle
        # whether the module exists on the server or not
        self.subscriber = Rpc.Subscriber(Rpc.session, self)
        if Settings.value('koo.auto_reload'):
            self.subscriber.subscribe('updated_model:%s' % model,
                                      self.autoReload)