Esempio n. 1
0
    def gnuhealth_cmd(self,command):

        cmd = command.split()[0]
        args = command.split()[1:]
        domain_name = domain = None
        search_string = '%'

        res = RPCExecute('model', 'gnuhealth.command', 'search_read',
                [('name', '=', cmd)], limit=1,field_names='model.name')

        if (res):
            res = res[0]
            if (res['domain']):
                domain_name = ast.literal_eval(res['domain'])
            model_name = res['model']
            label = res['label']
            if args:
                arg1 = args.pop()
                search_string = "%" + arg1 + "%"

            Window.create(model_name,
                mode=['tree','form'],
                name=label,
                domain=domain_name,
                limit = CONFIG['client.limit'],
                search_value = [('rec_name', 'ilike', search_string)]
                )

        else:
            common.message(_('Command not found.'))
Esempio n. 2
0
    def import_csv(self, csv_data, fields, model):
        # TODO: make it works with references
        fname = csv_data['fname']
        data = list(
            csv.reader(open(fname, 'rb'),
                       quotechar=csv_data['del'],
                       delimiter=csv_data['sep']))[int(csv_data['skip']):]
        datas = []

        for line in data:
            if not line:
                continue
            datas.append(
                [x.decode(csv_data['combo']).encode('utf-8') for x in line])
        try:
            count = RPCExecute('model',
                               model,
                               'import_data',
                               fields,
                               datas,
                               context=self.context)
        except RPCException:
            return
        if count == 1:
            common.message(_('%d record imported!') % count)
        else:
            common.message(_('%d records imported!') % count)
 def import_csv(self, fname, fields):
     # TODO: make it works with references
     skip = self.csv_skip.get_value_as_int()
     encoding = self.get_encoding()
     reader = csv.reader(open(fname, 'rb'),
                         quotechar=self.get_quotechar(),
                         delimiter=self.get_delimiter())
     data = []
     for i, line in enumerate(reader):
         if i < skip or not line:
             continue
         data.append([x.decode(encoding).encode('utf-8') for x in line])
     try:
         count = RPCExecute('model',
                            self.model,
                            'import_data',
                            fields,
                            data,
                            context=self.context)
     except RPCException:
         return
     if count == 1:
         common.message(_('%d record imported.') % count)
     else:
         common.message(_('%d records imported.') % count)
Esempio n. 4
0
 def export_csv(self, fname, fields, result, write_title=False, popup=True):
     try:
         file_p = open(fname, 'wb+')
         writer = csv.writer(file_p)
         if write_title:
             writer.writerow(fields)
         for data in result:
             row = []
             for val in data:
                 if isinstance(type(val), types.StringType):
                     row.append(val.replace('\n', ' ').replace('\t', ' '))
                 else:
                     row.append(val)
             writer.writerow(row)
         file_p.close()
         if popup:
             if len(result) == 1:
                 common.message(_('%d record saved!') % len(result))
             else:
                 common.message(_('%d records saved!') % len(result))
         return True
     except IOError, exception:
         common.warning(_("Operation failed!\nError message:\n%s")
             % (exception.faultCode,), _('Error'))
         return False
Esempio n. 5
0
    def export_csv(self, fname, fields, data, paths, popup=True):
        encoding = self.csv_enc.get_active_text() or 'utf_8_sig'
        locale_format = self.csv_locale.get_active()

        try:
            writer = csv.writer(open(fname, 'w', encoding=encoding,
                                     newline=''),
                                quotechar=self.get_quotechar(),
                                delimiter=self.get_delimiter())
            if self.add_field_names.get_active():
                writer.writerow(fields)
            for row, path in zip_longest(data, paths or []):
                indent = len(path) - 1 if path else 0
                if row:
                    writer.writerow(
                        self.format_row(row,
                                        indent=indent,
                                        locale_format=locale_format))
            if popup:
                if len(data) == 1:
                    common.message(_('%d record saved.') % len(data))
                else:
                    common.message(_('%d records saved.') % len(data))
            return True
        except (IOError, UnicodeEncodeError, csv.Error) as exception:
            common.warning(str(exception), _('Export failed'))
            return False
Esempio n. 6
0
    def sig_logs(self, widget=None):
        current_record = self.screen.current_record
        if not current_record or current_record.id < 0:
            self.message_info(
                _('You have to select one record.'), gtk.MESSAGE_INFO)
            return False

        fields = [
            ('id', _('ID:')),
            ('create_uid.rec_name', _('Creation User:'******'create_date', _('Creation Date:')),
            ('write_uid.rec_name', _('Latest Modification by:')),
            ('write_date', _('Latest Modification Date:')),
        ]

        try:
            res = RPCExecute('model', self.model, 'read', [current_record.id],
                [x[0] for x in fields], context=self.screen.context)
        except RPCException:
            return
        date_format = self.screen.context.get('date_format', '%x')
        datetime_format = date_format + ' %H:%M:%S.%f'
        message_str = ''
        for line in res:
            for (key, val) in fields:
                value = str(line.get(key, False) or '/')
                if line.get(key, False) \
                        and key in ('create_date', 'write_date'):
                    date = timezoned_date(line[key])
                    value = common.datetime_strftime(date, datetime_format)
                message_str += val + ' ' + value + '\n'
        message_str += _('Model:') + ' ' + self.model
        message(message_str)
        return True
Esempio n. 7
0
    def sig_logs(self, widget=None):
        current_record = self.screen.current_record
        if not current_record or current_record.id < 0:
            self.message_info(
                _('You have to select one record.'), gtk.MESSAGE_INFO)
            return False

        fields = [
            ('id', _('ID:')),
            ('create_uid.rec_name', _('Creation User:'******'create_date', _('Creation Date:')),
            ('write_uid.rec_name', _('Latest Modification by:')),
            ('write_date', _('Latest Modification Date:')),
        ]

        try:
            res = RPCExecute('model', self.model, 'read', [current_record.id],
                [x[0] for x in fields], context=self.screen.context)
        except RPCException:
            return
        date_format = self.screen.context.get('date_format', '%x')
        datetime_format = date_format + ' %X.%f'
        message_str = ''
        for line in res:
            for (key, val) in fields:
                value = str(line.get(key, False) or '/')
                if line.get(key, False) \
                        and key in ('create_date', 'write_date'):
                    date = timezoned_date(line[key])
                    value = common.datetime_strftime(date, datetime_format)
                message_str += val + ' ' + value + '\n'
        message_str += _('Model:') + ' ' + self.model
        message(message_str)
        return True
Esempio n. 8
0
    def export_csv(self, fname, fields, data, popup=True):
        encoding = self.csv_enc.get_active_text() or 'UTF-8'

        try:
            writer = csv.writer(open(fname, 'wb+'),
                                quotechar=self.get_quotechar(),
                                delimiter=self.get_delimiter())
            if self.add_field_names.get_active():
                writer.writerow(fields)
            for line in data:
                row = []
                for val in line:
                    if isinstance(type(val), types.StringType):
                        val = val.replace('\n', ' ').replace('\t', ' ')
                        val = val.encode(encoding)
                    row.append(val)
                writer.writerow(row)
            if popup:
                if len(data) == 1:
                    common.message(_('%d record saved.') % len(data))
                else:
                    common.message(_('%d records saved.') % len(data))
            return True
        except IOError, exception:
            common.warning(
                _("Operation failed.\nError message:\n%s") % exception,
                _('Error'))
            return False
Esempio n. 9
0
    def import_csv(self, csv_data, fields, model):
        # TODO: make it works with references
        fname = csv_data['fname']
        data = list(csv.reader(open(fname, 'rb'), quotechar=csv_data['del'],
            delimiter=csv_data['sep']))[int(csv_data['skip']):]
        datas = []

        for line in data:
            if not line:
                continue
            datas.append([x.decode(csv_data['combo']).encode('utf-8')
                    for x in line])
        try:
            res = RPCExecute('model', model, 'import_data', fields, datas)
        except RPCException:
            return False
        if res[0] >= 0:
            if res[0] == 1:
                common.message(_('%d record imported!') % res[0])
            else:
                common.message(_('%d records imported!') % res[0])
        else:
            buf = ''
            for key, val in res[1].items():
                buf += ('\t%s: %s\n' % (str(key), str(val)))
            common.error(_('Importation Error!'),
                _('Error importing record %(record)s\n'
                    '%(error_title)s\n\n%(traceback)s') %
                {'record': buf, 'error_title': res[2], 'traceback': res[3]})
        return True
Esempio n. 10
0
    def export_csv(self, fname, fields, data, popup=True):
        encoding = self.csv_enc.get_active_text() or 'UTF-8'

        try:
            writer = csv.writer(open(fname, 'w+', encoding=encoding),
                                quotechar=self.get_quotechar(),
                                delimiter=self.get_delimiter())
            if self.add_field_names.get_active():
                writer.writerow(fields)
            for line in data:
                row = []
                for val in line:
                    row.append(val)
                writer.writerow(row)
            if popup:
                if len(data) == 1:
                    common.message(_('%d record saved.') % len(data))
                else:
                    common.message(_('%d records saved.') % len(data))
            return True
        except IOError as exception:
            common.warning(
                _("Operation failed.\nError message:\n%s") % exception,
                _('Error'))
            return False
Esempio n. 11
0
 def export_csv(self, fname, fields, result, write_title=False, popup=True):
     try:
         file_p = open(fname, 'wb+')
         writer = csv.writer(file_p)
         if write_title:
             writer.writerow(fields)
         for data in result:
             row = []
             for val in data:
                 if isinstance(type(val), types.StringType):
                     row.append(val.replace('\n', ' ').replace('\t', ' '))
                 else:
                     row.append(val)
             writer.writerow(row)
         file_p.close()
         if popup:
             if len(result) == 1:
                 common.message(_('%d record saved!') % len(result))
             else:
                 common.message(_('%d records saved!') % len(result))
         return True
     except IOError, exception:
         common.warning(
             _("Operation failed!\nError message:\n%s") %
             (exception.faultCode, ), _('Error'))
         return False
Esempio n. 12
0
    def sig_logs(self, widget=None):
        obj_id = self.id_get()
        if obj_id < 0 or obj_id is False:
            self.message_info(_('You have to select one record!'))
            return False

        fields = [
            ('id', _('ID:')),
            ('create_uid.rec_name', _('Creation User:'******'create_date', _('Creation Date:')),
            ('write_uid.rec_name', _('Latest Modification by:')),
            ('write_date', _('Latest Modification Date:')),
        ]

        try:
            res = RPCExecute('model', self.model, 'read', [obj_id],
                [x[0] for x in fields], context=self.screen.context)
        except RPCException:
            return
        message_str = ''
        for line in res:
            for (key, val) in fields:
                value = str(line.get(key, False) or '/')
                if line.get(key, False) \
                        and key in ('create_date', 'write_date'):
                    date = timezoned_date(line[key])
                    value = common.datetime_strftime(date, '%X')
                message_str += val + ' ' + value + '\n'
        message_str += _('Model:') + ' ' + self.model
        message(message_str)
        return True
Esempio n. 13
0
    def exec_keyword(keyword,
                     data=None,
                     context=None,
                     warning=True,
                     alwaysask=False):
        actions = []
        model_id = data.get('id', False)
        try:
            actions = RPCExecute('model', 'ir.action.keyword', 'get_keyword',
                                 keyword, (data['model'], model_id))
        except RPCException:
            return False

        keyact = {}
        for action in actions:
            keyact[action['name'].replace('_', '')] = action

        res = selection(_('Select your action'), keyact, alwaysask=alwaysask)
        if res:
            (name, action) = res
            Action._exec_action(action, data, context=context)
            return (name, action)
        elif not len(keyact) and warning:
            message(_('No action defined.'))
        return False
Esempio n. 14
0
    def sig_logs(self, widget=None):
        obj_id = self.id_get()
        if obj_id < 0 or obj_id is False:
            self.message_info(_('You have to select one record!'))
            return False

        fields = [
            ('id', _('ID:')),
            ('create_uid.rec_name', _('Creation User:'******'create_date', _('Creation Date:')),
            ('write_uid.rec_name', _('Latest Modification by:')),
            ('write_date', _('Latest Modification Date:')),
        ]

        try:
            res = RPCExecute('model', self.model, 'read', [obj_id],
                [x[0] for x in fields], context=self.context)
        except RPCException:
            return
        message_str = ''
        for line in res:
            for (key, val) in fields:
                value = str(line.get(key, False) or '/')
                if line.get(key, False) \
                        and key in ('create_date', 'write_date'):
                    display_format = date_format() + ' %H:%M:%S'
                    date = timezoned_date(line[key])
                    value = common.datetime_strftime(date, display_format)
                message_str += val + ' ' + value + '\n'
        message_str += _('Model:') + ' ' + self.model
        message(message_str)
        return True
Esempio n. 15
0
    def save(self, widget):
        parent = get_toplevel_window()
        dia = gtk.Dialog(_('Image Size'), parent,
                         gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
                         (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OK,
                          gtk.RESPONSE_OK))
        dia.set_icon(GNUHEALTH_ICON)
        dia.set_default_response(gtk.RESPONSE_OK)

        hbox = gtk.HBox(spacing=3)
        dia.vbox.pack_start(hbox, False, True)

        hbox.pack_start(gtk.Label(_('Width:')), False, True)
        spinwidth = gtk.SpinButton()
        spinwidth.configure(gtk.Adjustment(400.0, 0.0, sys.maxint, 1.0, 10.0),
                            climb_rate=1,
                            digits=0)
        spinwidth.set_numeric(True)
        spinwidth.set_activates_default(True)
        hbox.pack_start(spinwidth, True, True)

        hbox.pack_start(gtk.Label(_('Height:')), False, True)
        spinheight = gtk.SpinButton()
        spinheight.configure(gtk.Adjustment(200.0, 0.0, sys.maxint, 1.0, 10.0),
                             climb_rate=1,
                             digits=0)
        spinheight.set_numeric(True)
        spinheight.set_activates_default(True)
        hbox.pack_start(spinheight, True, True)
        dia.show_all()

        filter = gtk.FileFilter()
        filter.set_name(_('PNG image (*.png)'))
        filter.add_mime_type('image/png')
        filter.add_pattern('*.png')

        while True:
            response = dia.run()
            width = spinwidth.get_value_as_int()
            height = spinheight.get_value_as_int()
            if response == gtk.RESPONSE_OK:
                filename = file_selection(_('Save As'),
                                          action=gtk.FILE_CHOOSER_ACTION_SAVE,
                                          preview=False,
                                          filters=[filter])
                if width and height and filename:
                    if not filename.endswith('.png'):
                        filename = filename + '.png'
                    try:
                        self.widgets['root'].export_png(
                            filename, width, height)
                        break
                    except MemoryError:
                        message(_('Image size too large.'), dia,
                                gtk.MESSAGE_ERROR)
            else:
                break
        parent.present()
        dia.destroy()
Esempio n. 16
0
def get_help():
    msg = "========== GNU Health Camera Help ==========\n\n" \
        "a = Attach media file in the current model\n\n" \
        "[space] = Set the picture in model (when available)\n\n" \
        "h = This help message\n\n" \
        "q = Quit the camera application\n\n"

    message(_(msg), )
    return True
Esempio n. 17
0
def verify_document(data):
    """ Verify the digital signature of the document """

    gpg = gnupg.GPG()
    gpg.encoding = 'utf-8'

    document_model = data['model']
    """ Verify that the document handles digital signatures """

    try:
        record_vals = rpc.execute('model', document_model, 'read', data['ids'],
                                  ['document_digest', 'digital_signature'],
                                  rpc.CONTEXT)

    except:
        warning(
            _('Please enable the model for digital signature'),
            _('No Digest or Digital Signature fields found !'),
        )
        return

    # Verify signature
    digital_signature = record_vals[0]['digital_signature']

    # Check that the document has a digital signature associated to it

    if not digital_signature:
        warning(
            _('Unsigned document'),
            _('This document has not been signed yet'),
        )
        return

    # Signature verification
    try:
        verify_signature = gpg.verify(digital_signature)

    except:
        warning(
            _('Error when verifying Digital Signature'),
            _('Please check your GNU Privacy Guard Settings'),
        )

    else:
        # Show message of warning boxes depending on the verification
        if (verify_signature.valid):
            message(_("Valid Signature !\n\n" + verify_signature.stderr))
        else:
            warning(
                _(str(verify_signature.stderr)),
                _(str("Error !")),
            )
def execute(datas):
    result = {}

    for module in MODULES:
        for name, func in module.get_plugins(datas['model']):
            result[name] = func
    if not result:
        common.message(_('No available plugin for this resource!'))
        return False
    res = common.selection(_('Choose a Plugin'), result, alwaysask=True)
    if res:
        res[1](datas)
    return True
Esempio n. 19
0
    def sig_autodetect(self, widget=None):
        fname = self.import_csv_file.get_filename()
        if not fname:
            common.message(_('You must select an import file first.'))
            return True

        encoding = self.get_encoding()
        self.csv_skip.set_value(1)
        try:
            data = csv.reader(open(fname, 'r', encoding=encoding, newline=''),
                              quotechar=self.get_quotechar(),
                              delimiter=self.get_delimiter())
        except (IOError, UnicodeDecodeError, csv.Error) as exception:
            common.warning(str(exception), _("Detection failed"))
            return True
        self.sig_unsel_all()
        word = ''
        for line in data:
            for word in line:
                if word not in self.fields_invert and word not in self.fields:
                    iter = self.model1.get_iter_first()
                    prefix = ''
                    for parent in word.split('/')[:-1]:
                        while iter:
                            if self.model1.get_value(iter, 0) == parent or \
                                    self.model1.get_value(iter, 1) == \
                                    (prefix + parent):
                                self.on_row_expanded(
                                    self.view1, iter,
                                    self.model1.get_path(iter))
                                iter = self.model1.iter_children(iter)
                                prefix = parent + '/'
                                break
                            else:
                                iter = self.model1.iter_next(iter)

                if word in self.fields_invert:
                    name = word
                    field = self.fields_invert[word]
                elif word in self.fields:
                    name = self.fields[word][0]
                    field = word
                else:
                    common.warning(
                        _('Error processing the file at field %s.') % word,
                        _('Error'))
                    return True
                num = self.model2.append()
                self.model2.set(num, 0, name, 1, field)
            break
        return True
Esempio n. 20
0
    def sig_autodetect(self, widget=None):
        fname = self.import_csv_file.get_filename()
        if not fname:
            common.message(_('You must select an import file first!'))
            return True
        csvsep = self.import_csv_sep.get_text() or None
        csvdel = self.import_csv_del.get_text() or None
        csvcode = self.import_csv_enc.get_active_text() or 'UTF-8'

        self.import_csv_skip.set_value(1)
        try:
            data = csv.reader(open(fname, 'rb'),
                              quotechar=csvdel,
                              delimiter=csvsep)
        except IOError:
            common.warning(_('Error opening CSV file'), _('Error'))
            return True
        self.sig_unsel_all()
        word = ''
        for line in data:
            for word in line:
                word = word.decode(csvcode)
                if word not in self.fields_invert and word not in self.fields:
                    iter = self.model1.get_iter_first()
                    prefix = ''
                    for parent in word.split('/')[:-1]:
                        while iter:
                            if self.model1.get_value(iter, 0) == parent or \
                                    self.model1.get_value(iter, 1) == \
                                    (prefix + parent):
                                self.on_row_expanded(
                                    self.view1, iter,
                                    self.model1.get_path(iter))
                                break
                            iter = self.model1.iter_next(iter)
                        prefix = parent + '/'
                if word in self.fields_invert:
                    name = word
                    field = self.fields_invert[word]
                elif word in self.fields:
                    name = self.fields[word][0]
                    field = word
                else:
                    common.warning(
                        _('Error processing the file at field %s.') % word,
                        _('Error'))
                    return True
                num = self.model2.append()
                self.model2.set(num, 0, name, 1, field)
            break
        return True
    def sig_autodetect(self, widget=None):
        fname = self.import_csv_file.get_filename()
        if not fname:
            common.message(_('You must select an import file first!'))
            return True
        csvsep = self.import_csv_sep.get_text()
        csvdel = self.import_csv_del.get_text()
        csvcode = self.import_csv_enc.get_active_text() \
                or 'UTF-8'

        self.import_csv_skip.set_value(1)
        try:
            data = csv.reader(open(fname, 'rb'), quotechar=csvdel,
                    delimiter=csvsep)
        except IOError:
            common.warning(_('Error opening CSV file'), _('Error'))
            return True
        self.sig_unsel_all()
        word = ''
        for line in data:
            for word in line:
                word = word.decode(csvcode)
                if word not in self.fields_invert and word not in self.fields:
                    iter = self.model1.get_iter_first()
                    prefix = ''
                    for parent in word.split('/')[:-1]:
                        while iter:
                            if self.model1.get_value(iter, 0) == parent or \
                                    self.model1.get_value(iter, 1) == \
                                    (prefix + parent):
                                self.on_row_expanded(self.view1, iter,
                                        self.model1.get_path(iter))
                                break
                            iter = self.model1.iter_next(iter)
                        prefix = parent + '/'
                if word in self.fields_invert:
                    name = word
                    field = self.fields_invert[word]
                elif word in self.fields:
                    name = self.fields[word][0]
                    field = word
                else:
                    common.warning(_('Error processing the file at field %s.')
                        % word, _('Error'))
                    return True
                num = self.model2.append()
                self.model2.set(num, 0, name, 1, field)
            break
        return True
Esempio n. 22
0
 def import_csv(self, fname, fields):
     # TODO: make it works with references
     skip = self.csv_skip.get_value_as_int()
     encoding = self.get_encoding()
     locale_format = self.csv_locale.get_active()
     try:
         reader = csv.reader(open(fname, 'r', encoding=encoding),
                             quotechar=self.get_quotechar(),
                             delimiter=self.get_delimiter())
         data = []
         for i, line in enumerate(reader):
             if i < skip or not line:
                 continue
             row = []
             for field, val in zip(fields, line):
                 if locale_format and val:
                     type_ = self.fields_data[field]['type']
                     if type_ in ['integer', 'biginteger']:
                         val = locale.atoi(val)
                     elif type_ == 'float':
                         val = locale.atof(val)
                     elif type_ == 'numeric':
                         val = Decimal(locale.delocalize(val))
                     elif type_ in ['date', 'datetime']:
                         val = date_parse(val, common.date_format())
                     elif type_ == 'binary':
                         val = base64.b64decode(val)
                 row.append(val)
             data.append(row)
     except (IOError, UnicodeDecodeError, csv.Error) as exception:
         common.warning(str(exception), _("Import failed"))
         return
     try:
         count = RPCExecute('model',
                            self.model,
                            'import_data',
                            fields,
                            data,
                            context=self.context)
     except RPCException:
         return
     if count == 1:
         common.message(_('%d record imported.') % count)
     else:
         common.message(_('%d records imported.') % count)
Esempio n. 23
0
 def click_and_relate(self, action, value, path):
     data = {}
     context = {}
     act = action.copy()
     if not(value):
         message(_('You must select a record to use the relation!'))
         return False
     from tryton.gui.window.view_form.screen import Screen
     screen = Screen(self.screen.group.fields[
         path[1].name].attrs['relation'])
     screen.load([value])
     encoder = PYSONEncoder()
     act['domain'] = encoder.encode(screen.current_record.expr_eval(
         act.get('domain', []), check_load=False))
     act['context'] = encoder.encode(screen.current_record.expr_eval(
         act.get('context', {}), check_load=False))
     data['model'] = self.screen.model_name
     data['id'] = value
     data['ids'] = [value]
     return Action._exec_action(act, data, context)
Esempio n. 24
0
    def import_csv(self, csv_data, fields, model):
        # TODO: make it works with references
        fname = csv_data['fname']
        data = list(csv.reader(open(fname, 'rb'), quotechar=csv_data['del'],
            delimiter=csv_data['sep']))[int(csv_data['skip']):]
        datas = []

        for line in data:
            if not line:
                continue
            datas.append([x.decode(csv_data['combo']).encode('utf-8')
                    for x in line])
        try:
            count = RPCExecute('model', model, 'import_data', fields, datas,
                context=self.context)
        except RPCException:
            return
        if count == 1:
            common.message(_('%d record imported!') % count)
        else:
            common.message(_('%d records imported!') % count)
Esempio n. 25
0
    def exec_keyword(keyword, data=None, context=None, warning=True,
            alwaysask=False):
        actions = []
        model_id = data.get('id', False)
        try:
            actions = RPCExecute('model', 'ir.action.keyword',
                'get_keyword', keyword, (data['model'], model_id))
        except RPCException:
            return False

        keyact = {}
        for action in actions:
            keyact[action['name'].replace('_', '')] = action

        res = selection(_('Select your action'), keyact, alwaysask=alwaysask)
        if res:
            (name, action) = res
            Action._exec_action(action, data, context=context)
            return (name, action)
        elif not len(keyact) and warning:
            message(_('No action defined!'))
        return False
Esempio n. 26
0
    def sig_logs(self, widget=None):
        current_record = self.screen.current_record
        if not current_record or current_record.id < 0:
            self.message_info(_('You have to select one record.'),
                              Gtk.MessageType.INFO)
            return False

        fields = [
            ('id', _('ID:')),
            ('create_uid.rec_name', _('Created by:')),
            ('create_date', _('Created at:')),
            ('write_uid.rec_name', _('Edited by:')),
            ('write_date', _('Edited at:')),
        ]

        try:
            data = RPCExecute('model',
                              self.model,
                              'read', [current_record.id],
                              [x[0] for x in fields],
                              context=self.screen.context)[0]
        except RPCException:
            return
        date_format = self.screen.context.get('date_format', '%x')
        datetime_format = date_format + ' %H:%M:%S.%f'
        message_str = ''
        for (key, label) in fields:
            value = data
            keys = key.split('.')
            name = keys.pop(-1)
            for key in keys:
                value = value.get(key + '.', {})
            value = (value or {}).get(name, '/')
            if isinstance(value, datetime.datetime):
                value = timezoned_date(value).strftime(datetime_format)
            message_str += '%s %s\n' % (label, value)
        message_str += _('Model:') + ' ' + self.model
        message(message_str)
        return True
    def translate(self, widget):
        if self.record.id < 0 or self.record.modified:
            common.message(
                _('You need to save the record before adding translations!'))
            return

        try:
            lang_ids = RPCExecute('model', 'ir.lang', 'search', [
                    ('translatable', '=', True),
                    ])
        except RPCException:
            return

        if not lang_ids:
            common.message(_('No other language available!'))
            return
        try:
            languages = RPCExecute('model', 'ir.lang', 'read', lang_ids,
                ['code', 'name'])
        except RPCException:
            return

        TranslateDialog(self, languages)
Esempio n. 28
0
    def translate(self, *args):
        if self.record.id < 0 or self.record.modified:
            common.message(
                _('You need to save the record before adding translations!'))
            return

        try:
            lang_ids = RPCExecute('model', 'ir.lang', 'search', [
                ('translatable', '=', True),
            ])
        except RPCException:
            return

        if not lang_ids:
            common.message(_('No other language available!'))
            return
        try:
            languages = RPCExecute('model', 'ir.lang', 'read', lang_ids,
                                   ['code', 'name'])
        except RPCException:
            return

        TranslateDialog(self, languages)
Esempio n. 29
0
    def export_csv(self, fname, fields, data, popup=True):
        encoding = self.csv_enc.get_active_text() or 'UTF-8'
        locale_format = self.csv_locale.get_active()

        try:
            writer = csv.writer(
                open(fname, 'w', encoding=encoding, newline=''),
                quotechar=self.get_quotechar(),
                delimiter=self.get_delimiter())
            if self.add_field_names.get_active():
                writer.writerow(fields)
            for row in data:
                writer.writerow(self.format_row(row, locale_format))
            if popup:
                if len(data) == 1:
                    common.message(_('%d record saved.') % len(data))
                else:
                    common.message(_('%d records saved.') % len(data))
            return True
        except IOError as exception:
            common.warning(_("Operation failed.\nError message:\n%s")
                % exception, _('Error'))
            return False
Esempio n. 30
0
 def import_csv(self, fname, fields):
     # TODO: make it works with references
     skip = self.csv_skip.get_value_as_int()
     encoding = self.get_encoding()
     reader = csv.reader(
         open(fname, 'rb'),
         quotechar=self.get_quotechar(),
         delimiter=self.get_delimiter())
     data = []
     for i, line in enumerate(reader):
         if i < skip or not line:
             continue
         data.append([x.decode(encoding).encode('utf-8') for x in line])
     try:
         count = RPCExecute(
             'model', self.model, 'import_data', fields, data,
             context=self.context)
     except RPCException:
         return
     if count == 1:
         common.message(_('%d record imported!') % count)
     else:
         common.message(_('%d records imported!') % count)
Esempio n. 31
0
    def export_csv(self, fname, fields, data, popup=True):
        encoding = self.csv_enc.get_active_text() or "UTF-8"

        try:
            writer = csv.writer(open(fname, "wb+"), quotechar=self.get_quotechar(), delimiter=self.get_delimiter())
            if self.add_field_names.get_active():
                writer.writerow(fields)
            for line in data:
                row = []
                for val in line:
                    if isinstance(type(val), types.StringType):
                        val = val.replace("\n", " ").replace("\t", " ")
                        val = val.encode(encoding)
                    row.append(val)
                writer.writerow(row)
            if popup:
                if len(data) == 1:
                    common.message(_("%d record saved!") % len(data))
                else:
                    common.message(_("%d records saved!") % len(data))
            return True
        except IOError, exception:
            common.warning(_("Operation failed!\nError message:\n%s") % exception, _("Error"))
            return False
Esempio n. 32
0
    def export_csv(self, fname, fields, data, popup=True):
        encoding = self.csv_enc.get_active_text() or 'UTF-8'
        locale_format = self.csv_locale.get_active()

        try:
            writer = csv.writer(open(fname, 'w', encoding=encoding,
                                     newline=''),
                                quotechar=self.get_quotechar(),
                                delimiter=self.get_delimiter())
            if self.add_field_names.get_active():
                writer.writerow(fields)
            for line in data:
                row = []
                for val in line:
                    if locale_format:
                        if isinstance(val, Number):
                            val = locale.str(val)
                        elif isinstance(val, datetime.datetime):
                            val = val.strftime(common.date_format() + ' %X')
                        elif isinstance(val, datetime.date):
                            val = val.strftime(common.date_format())
                    elif isinstance(val, bool):
                        val = int(val)
                    row.append(val)
                writer.writerow(row)
            if popup:
                if len(data) == 1:
                    common.message(_('%d record saved.') % len(data))
                else:
                    common.message(_('%d records saved.') % len(data))
            return True
        except IOError as exception:
            common.warning(
                _("Operation failed.\nError message:\n%s") % exception,
                _('Error'))
            return False
Esempio n. 33
0
    def import_csv(self, csv_data, fields, model):
        # TODO: make it works with references
        fname = csv_data['fname']
        data = list(
            csv.reader(open(fname, 'rb'),
                       quotechar=csv_data['del'],
                       delimiter=csv_data['sep']))[int(csv_data['skip']):]
        datas = []

        for line in data:
            if not line:
                continue
            datas.append(
                [x.decode(csv_data['combo']).encode('utf-8') for x in line])
        try:
            res = RPCExecute('model', model, 'import_data', fields, datas)
        except RPCException:
            return False
        if res[0] >= 0:
            if res[0] == 1:
                common.message(_('%d record imported!') % res[0])
            else:
                common.message(_('%d records imported!') % res[0])
        else:
            buf = ''
            for key, val in res[1].items():
                buf += ('\t%s: %s\n' % (str(key), str(val)))
            common.error(
                _('Importation Error!'),
                _('Error importing record %(record)s\n'
                  '%(error_title)s\n\n%(traceback)s') % {
                      'record': buf,
                      'error_title': res[2],
                      'traceback': res[3]
                  })
        return True
Esempio n. 34
0
def set_attachment(data, frame):
    #Store the frame in a container
    rc, container = cv2.imencode(".png", frame)
    container = container.tostring()
    document_model = data['model']
    ref = document_model + ',' + str(data['ids'][0])
    timestamp = str(datetime.now())
    attach_name = "GNU Health media " + timestamp

    #Store the attachment
    save_attach = rpc.execute('model', 'ir.attachment', 'create',
                              [{
                                  'name': attach_name,
                                  'type': 'data',
                                  'resource': ref,
                                  'description': 'From GNU Health camera',
                                  'data': container,
                              }], rpc.CONTEXT)

    if save_attach:
        msg = "Attachment saved correctly !\n\n" \
            "Please refresh the view"
        message(_(msg), )
        return True
Esempio n. 35
0
def sign_document(data):
    """ Retrieve the hash value of the serialized document and
        generates a clearsign signature using the user's private key
        on the client side via GNU Privacy Guard - GPG -"""

    gpg = gnupg.GPG()

    gpg.encoding = 'utf-8'

    document_model = data['model']
    """ Don't allow signing more than one document at a time
        To avoid signing unwanted / unread documents
    """

    if (len(data['ids']) > 1):
        warning(
            _('For security reasons, Please sign one document at a time'),
            _('Multiple records selected !'),
        )
        return
    """ Verify that the document handles digital signatures """

    try:
        record_vals = rpc.execute('model', document_model, 'read', data['ids'],
                                  ['document_digest', 'digital_signature'],
                                  rpc.CONTEXT)

    except:
        warning(
            _('Please enable the model for digital signature'),
            _('No Digest or Digital Signature fields found !'),
        )
        return

    digest = record_vals[0]['document_digest']
    """ Check that the document hasn't been signed already """

    if record_vals[0]['digital_signature']:
        warning(
            _('Document already signed'),
            _('This record has been already signed'),
        )
        return

    # Check that the document has the digest before trying to
    # to sign it.
    if digest:

        try:
            gpg_signature = gpg.sign(digest, clearsign=True)

        except:
            warning(
                _('Error when signing the document'),
                _('Please check your encryption settings'),
            )

    else:
        warning(
            _('No Digest found for this document'),
            _('You need generate the digest'),
        )
        return
    """
    Set the clearsigned digest
    """
    try:
        RPCExecute('model', document_model, 'set_signature', data,
                   str(gpg_signature))

    except:
        warning(
            _('Error when saving the digital signature'),
            _('The signature was generated but NOT saved !'),
        )

    else:
        message(_('Document digitally signed'))
Esempio n. 36
0
    def save(self, widget):
        parent = get_toplevel_window()
        dia = gtk.Dialog(_('Save As'), parent,
                         gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
                         (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OK,
                          gtk.RESPONSE_OK))
        dia.set_icon(TRYTON_ICON)
        dia.set_has_separator(True)
        dia.set_default_response(gtk.RESPONSE_OK)

        dia.vbox.set_spacing(5)
        dia.vbox.set_homogeneous(False)

        title = gtk.Label('<b>' + _('Image Size') + '</b>')
        title.set_alignment(0.0, 0.5)
        title.set_use_markup(True)
        dia.vbox.pack_start(title)

        table = gtk.Table(2, 2)
        table.set_col_spacings(3)
        table.set_row_spacings(3)
        table.set_border_width(1)
        table.attach(gtk.Label(_('Width:')),
                     0,
                     1,
                     0,
                     1,
                     yoptions=False,
                     xoptions=gtk.FILL)
        spinwidth = gtk.SpinButton(
            gtk.Adjustment(400.0, 0.0, sys.maxint, 1.0, 10.0))
        spinwidth.set_numeric(True)
        spinwidth.set_activates_default(True)
        table.attach(spinwidth, 1, 2, 0, 1, yoptions=False, xoptions=gtk.FILL)
        table.attach(gtk.Label(_('Height:')),
                     0,
                     1,
                     1,
                     2,
                     yoptions=False,
                     xoptions=gtk.FILL)
        spinheight = gtk.SpinButton(
            gtk.Adjustment(200.0, 0.0, sys.maxint, 1.0, 10.0))
        spinheight.set_numeric(True)
        spinheight.set_activates_default(True)
        table.attach(spinheight, 1, 2, 1, 2, yoptions=False, xoptions=gtk.FILL)
        dia.vbox.pack_start(table)

        filechooser = gtk.FileChooserWidget(gtk.FILE_CHOOSER_ACTION_SAVE, None)
        filter = gtk.FileFilter()
        filter.set_name(_('PNG image (*.png)'))
        filter.add_mime_type('image/png')
        filter.add_pattern('*.png')
        filechooser.add_filter(filter)
        dia.vbox.pack_start(filechooser)

        dia.show_all()

        while True:
            response = dia.run()
            width = spinwidth.get_value_as_int()
            height = spinheight.get_value_as_int()
            filename = filechooser.get_filename()
            if response == gtk.RESPONSE_OK:
                if width and height and filename:
                    if not filename.endswith('.png'):
                        filename = filename + '.png'
                    try:
                        self.widgets['root'].export_png(
                            filename, width, height)
                        break
                    except MemoryError:
                        message(_('Image size too large!'), dia,
                                gtk.MESSAGE_ERROR)
            else:
                break
        parent.present()
        dia.destroy()
Esempio n. 37
0
    def search_resource(self, widget, *data):
        resource, query, fuzzy_search = data[0].get_text(), \
            data[1].get_text(), data[2].get_active()

        query = query.upper()
        if resource:
            model = 'gnuhealth.federation.config'
            # Retrieve the connection params for Thalamus
            fconn,=rpc.execute(
                'model', model , 'read',
                [0],
                ['host','port','user','password','ssl', \
                    'verify_ssl'],
                rpc.CONTEXT)

            host, port, user, password, ssl, verify_ssl = \
                fconn['host'], fconn['port'], fconn['user'], \
                fconn['password'], fconn['ssl'], fconn['verify_ssl']

            if (ssl):
                protocol = 'https://'
            else:
                protocol = 'http://'

            url = protocol + host + ':' + str(port)
            res = url + '/' + resource

            if resource == "people":
                res = res + '/' + query

            try:
                conn = requests.get(res,
                                    auth=(user, password),
                                    verify=verify_ssl)

            except:
                message(_('Unable to connect to Thalamus'))
                return

            if fuzzy_search:
                # Find the federation ID using fuzzy search
                msg = "Coming up"
                message(_(msg))
            else:
                # Find the federation ID using deterministic algorithm
                # (exact match, return at most one record)
                self.federation_data = requests.get(res,
                                                    params=query,
                                                    auth=(user, password),
                                                    verify=verify_ssl)

                if not self.federation_data:
                    not_found_msg = "The ID "+ query +\
                        " does not exist on Federation"
                    message(_(not_found_msg))

                else:
                    #Cleanup the results liststore at every search
                    self.results.clear()

                    #Populate and pack the result
                    r = []
                    fields = [
                        'id', 'name', 'lastname', 'gender', 'dob', 'phone',
                        'address'
                    ]

                    record = self.federation_data.json()

                    for fname in fields:
                        if fname in record.keys():
                            field = record[fname]
                        else:
                            field = ''
                        r.append(field)

                    self.results.append(r)
Esempio n. 38
0
    def save(self, widget):
        parent = get_toplevel_window()
        dia = Gtk.Dialog(
            title=_('Image Size'), transient_for=parent, modal=True,
            destroy_with_parent=True)
        Main().add_window(dia)
        cancel_button = dia.add_button(
            set_underline(_("Cancel")), Gtk.ResponseType.CANCEL)
        cancel_button.set_image(IconFactory.get_image(
                'tryton-cancel', Gtk.IconSize.BUTTON))
        cancel_button.set_always_show_image(True)
        ok_button = dia.add_button(
            set_underline(_("OK")), Gtk.ResponseType.OK)
        ok_button.set_image(IconFactory.get_image(
                'tryton-ok', Gtk.IconSize.BUTTON))
        ok_button.set_always_show_image(True)
        dia.set_icon(TRYTON_ICON)
        dia.set_default_response(Gtk.ResponseType.OK)

        hbox = Gtk.HBox(spacing=3)
        dia.vbox.pack_start(hbox, expand=False, fill=True, padding=0)

        hbox.pack_start(
            Gtk.Label(label=_('Width:')), expand=False, fill=True, padding=0)
        spinwidth = Gtk.SpinButton()
        spinwidth.configure(Gtk.Adjustment(
                value=400.0, lower=0.0, upper=sys.maxsize,
                step_increment=1.0, page_increment=10.0),
            climb_rate=1, digits=0)
        spinwidth.set_numeric(True)
        spinwidth.set_activates_default(True)
        hbox.pack_start(spinwidth, expand=True, fill=True, padding=0)

        hbox.pack_start(
            Gtk.Label(label=_('Height:')), expand=False, fill=True, padding=0)
        spinheight = Gtk.SpinButton()
        spinheight.configure(Gtk.Adjustment(
                value=200.0, lower=0.0, upper=sys.maxsize,
                step_increment=1.0, page_increment=10.0),
            climb_rate=1, digits=0)
        spinheight.set_numeric(True)
        spinheight.set_activates_default(True)
        hbox.pack_start(spinheight, expand=True, fill=True, padding=0)
        dia.show_all()

        filter = Gtk.FileFilter()
        filter.set_name(_('PNG image (*.png)'))
        filter.add_mime_type('image/png')
        filter.add_pattern('*.png')

        while True:
            response = dia.run()
            width = spinwidth.get_value_as_int()
            height = spinheight.get_value_as_int()
            if response == Gtk.ResponseType.OK:
                filename = file_selection(
                    _('Save As'),
                    action=Gtk.FileChooserAction.SAVE,
                    preview=False,
                    filters=[filter])
                if width and height and filename:
                    if not filename.endswith('.png'):
                        filename = filename + '.png'
                    try:
                        self.widgets['root'].export_png(
                            filename, width, height)
                        break
                    except MemoryError:
                        message(
                            _('Image size too large.'), dia,
                            Gtk.MessageType.ERROR)
            else:
                break
        parent.present()
        dia.destroy()
Esempio n. 39
0
 def message():
     gmodel = global_search_completion.get_model()
     if not len(gmodel):
         common.message(_('No result found.'))
     else:
         widget.emit('changed')
Esempio n. 40
0
def save(widget, graph):
    parent = common.get_toplevel_window()
    dia = gtk.Dialog(_('Save As'), parent,
        gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
        (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OK, gtk.RESPONSE_OK))
    dia.set_icon(TRYTON_ICON)
    dia.set_has_separator(True)
    dia.set_default_response(gtk.RESPONSE_OK)

    dia.vbox.set_spacing(5)
    dia.vbox.set_homogeneous(False)

    title = gtk.Label('<b>' + _('Image Size') + '</b>')
    title.set_alignment(0.0, 0.5)
    title.set_use_markup(True)
    dia.vbox.pack_start(title)

    table = gtk.Table(2, 2)
    table.set_col_spacings(3)
    table.set_row_spacings(3)
    table.set_border_width(1)
    table.attach(gtk.Label(_('Width:')), 0, 1, 0, 1, yoptions=False,
            xoptions=gtk.FILL)
    spinwidth = gtk.SpinButton(gtk.Adjustment(400.0,
            0.0, sys.maxint, 1.0, 10.0))
    spinwidth.set_numeric(True)
    spinwidth.set_activates_default(True)
    table.attach(spinwidth, 1, 2, 0, 1, yoptions=False, xoptions=gtk.FILL)
    table.attach(gtk.Label(_('Height:')), 0, 1, 1, 2, yoptions=False,
            xoptions=gtk.FILL)
    spinheight = gtk.SpinButton(gtk.Adjustment(200.0,
            0.0, sys.maxint, 1.0, 10.0))
    spinheight.set_numeric(True)
    spinheight.set_activates_default(True)
    table.attach(spinheight, 1, 2, 1, 2, yoptions=False, xoptions=gtk.FILL)
    dia.vbox.pack_start(table)

    filechooser = gtk.FileChooserWidget(gtk.FILE_CHOOSER_ACTION_SAVE, None)
    filechooser.set_current_folder(CONFIG['client.default_path'])
    filter = gtk.FileFilter()
    filter.set_name(_('PNG image (*.png)'))
    filter.add_mime_type('image/png')
    filter.add_pattern('*.png')
    filechooser.add_filter(filter)
    dia.vbox.pack_start(filechooser)

    dia.show_all()

    while True:
        response = dia.run()
        width = spinwidth.get_value_as_int()
        height = spinheight.get_value_as_int()
        filename = filechooser.get_filename()
        if filename:
            filename = filename.decode('utf-8')
            try:
                CONFIG['client.default_path'] = \
                       os.path.dirname(filename)
                CONFIG.save()
            except IOError:
                pass
        if response == gtk.RESPONSE_OK:
            if width and height and filename:
                if not filename.endswith('.png'):
                    filename = filename + '.png'
                try:
                    graph.export_png(filename, width, height)
                    break
                except MemoryError:
                    common.message(_('Image size too large!'), dia,
                            gtk.MESSAGE_ERROR)
        else:
            break
    parent.present()
    dia.destroy()
    return