Beispiel #1
0
    def post(self):
        user = users.get_current_user()
        if user:
            project_key = self.request.get('project_key')

            if project_key <> '':
                key = db.Key(project_key)
                q = FunctionPointProject.gql("WHERE __key__ =:1", key)
                projects = q.fetch(1)
                project = None
                for p in projects:
                    project = p
                    break

                functions = list_functions(project_key)

                return self.response.out.write(
                    json.write({
                        'project': project.to_dict(),
                        'items': functions
                    }))
            else:
                err = {'error': common.message('project_not_selected')}
                return self.response.out.write(json.write(err))
        else:
            err = {
                'error': common.message('login_err', common.AppSettings('/fp'))
            }
            return self.response.out.write(json.write(err))

        err = {'error': 'Unknown Error'}
        return self.response.out.write(json.write(err))
Beispiel #2
0
    def post(self):
        user = users.get_current_user()
        if user:
            project_key = self.request.get('project_key')
            function_type = self.request.get('function_type')

            if project_key <> '':
                func_entity = FunctionEntity(
                    project_key=project_key,
                    function_type=function_type,
                    function_name='',
                    measurement_index1=0,
                    measurement_index2=0,
                    sort_order=99,
                )
                func_entity.put()

                return self.response.out.write(
                    json.write(func_entity.to_dict()))
            else:
                err = {'error': common.message('project_not_selected')}
                return self.response.out.write(json.write(err))
        else:
            err = {
                'error': common.message('login_err', common.AppSettings('/fp'))
            }
            return self.response.out.write(json.write(err))

        err = {'error': 'Unknown Error'}
        return self.response.out.write(json.write(err))
Beispiel #3
0
    def post(self):
        user = users.get_current_user()
        if user:
            key_str = self.request.get('project_profile_key')
            if key_str.strip() == '':
                err = {'error': common.message('project_not_selected')}
                return self.response.out.write(json.write(err))

            #
            data_communications = self.request.get('data_communications')
            distoributed_processing = self.request.get(
                'distoributed_processing')
            performance = self.request.get('performance')
            heavily_used_configuration = self.request.get(
                'heavily_used_configuration')
            transaction_rate = self.request.get('transaction_rate')
            online_data_entry = self.request.get('online_data_entry')
            enduser_efficiency = self.request.get('enduser_efficiency')
            online_update = self.request.get('online_update')
            complex_processing = self.request.get('complex_processing')
            reusability = self.request.get('reusability')
            installation_ease = self.request.get('installation_ease')
            operational_ease = self.request.get('operational_ease')
            multiple_sites = self.request.get('multiple_sites')
            facilitate_change = self.request.get('facilitate_change')
            #

            key = db.Key(key_str)
            q = FunctionPointProject.gql("WHERE __key__ =:1", key)

            projects = q.fetch(1)
            for project in projects:
                project.data_communications = to_idx(data_communications)
                project.distoributed_processing = to_idx(
                    distoributed_processing)
                project.performance = to_idx(performance)
                project.heavily_used_configuration = to_idx(
                    heavily_used_configuration)
                project.transaction_rate = to_idx(transaction_rate)
                project.online_data_entry = to_idx(online_data_entry)
                project.enduser_efficiency = to_idx(enduser_efficiency)
                project.online_update = to_idx(online_update)
                project.complex_processing = to_idx(complex_processing)
                project.reusability = to_idx(reusability)
                project.installation_ease = to_idx(installation_ease)
                project.operational_ease = to_idx(operational_ease)
                project.multiple_sites = to_idx(multiple_sites)
                project.facilitate_change = to_idx(facilitate_change)

                project.put()

            return self.response.out.write(json.write(project.to_dict()))
        else:
            err = {
                'error': common.message('login_err', common.AppSettings('/fp'))
            }
            return self.response.out.write(json.write(err))

        err = {'error': 'Unknown Error'}
        return self.response.out.write(json.write(err))
Beispiel #4
0
    def get_resource(self, widget=None, get_id=None):
        ## This has been done due to virtual ids coming from
        ## crm meeting. like '3-20101012155505' which are not in existence
        ## and needed to be converted to real ids
        if isinstance(get_id, str):
            get_id = int(get_id.split('-')[0])

        if widget:
            get_id = int(widget.get_value())

        # We need listed / searched set of IDS when we switch back to a view
        listed_ids = self.screen.ids_get()

        ## If the record is already among the previously searched records or inside
        ## the listed_ids, we do not need to call search
        record_exists = False
        if get_id in listed_ids:
            self.screen.display(get_id)
            record_exists = True
        else:
            # User is trying to see the record with Ctrl + G option! So we search domainless, limitless!
            record_exists = rpc.session.rpc_exec_auth('/object', 'execute',
                                                      self.model, 'search',
                                                      [('id', '=', get_id)],
                                                      False, False, False,
                                                      self.screen.context)
            if record_exists:
                self.screen.load([get_id])

        if get_id and record_exists:
            self.screen.current_view.set_cursor()
        else:
            common.message(_('Resource ID does not exist for this object!'))
Beispiel #5
0
def open_excel(fields, result):
    if os.name == 'nt':
        try:
            from win32com.client import Dispatch
            xlApp = Dispatch("Excel.Application")
            xlApp.Workbooks.Add()
            for col in range(len(fields)):
                xlApp.ActiveSheet.Cells(1, col + 1).Value = fields[col]
            sht = xlApp.ActiveSheet
            for a in result:
                for b in range(len(a)):
                    if type(a[b]) == type(''):
                        a[b] = a[b].decode('utf-8', 'replace')
                    elif type(a[b]) == type([]):
                        if len(a[b]) == 2:
                            a[b] = a[b][1].decode('utf-8', 'replace')
                        else:
                            a[b] = ''
            sht.Range(sht.Cells(2, 1), sht.Cells(len(result) + 1,
                                                 len(fields))).Value = result
            xlApp.Visible = 1
        except:
            common.error(_('Error Opening Excel !'), '')
    else:
        common.message(
            _("Function only available for MS Office !\nSorry, OOo users :("))
Beispiel #6
0
 def check_codegen(self, widget=None, language=None):
     """\
     Checks whether widget has a suitable code generator for the given
     language (default: the current active language). If not, the user is
     informed with a message.
     """
     if language is None: language = self.language
     if widget is not None:
         cname = common.class_names[widget.__class__.__name__]
         if language != 'XRC':
             ok = cname in common.code_writers[language].obj_builders
         else:
             # xrc is special...
             xrcgen = common.code_writers['XRC']
             ok = xrcgen.obj_builders.get(cname, None) is not \
                  xrcgen.NotImplementedXrcObject
         if not ok:
             common.message(_('WARNING'),
                            _('No %s code generator for %s (of type %s)'
                            ' available'),
                            language.capitalize(), widget.name, cname)
     else:
         # in this case, we check all the widgets in the tree
         def check_rec(node):
             if node.widget is not None:
                 self.check_codegen(node.widget)
             if node.children:
                 for c in node.children:
                     check_rec(c)
         if common.app_tree.root.children:
             for c in common.app_tree.root.children:
                 check_rec(c)
Beispiel #7
0
def parse(url):
    appid = pat.search(url).group(2)
    api = api_url.format(appid)

    with get_session() as s:
        data = s.get(api).json()

    if data.get('success', False):
        return message(code='product_not_found')

    data = data[appid]['data']
    if data['is_free']:
        price = price_sale = 0
    else:
        prices = data['price_overview']
        if not prices['final_formatted']:
            return message(code='out_of_stock')

        price = price_sale = prices['final_formatted'].replace('CLP', '')
        if prices['initial_formatted']:
            price = prices['initial_formatted'].replace('CLP', '')

    return dict(
        url=url,
        name=data['name'],
        price=price,
        price_sale=price_sale,
        price_card=price_sale,
        image=data['header_image'],
        raw=data
    )
Beispiel #8
0
def print_data(data):
    if 'result' not in data:
        common.message(
            _('Error! No Data found. Make sure you have enough data to print!')
        )
        return
    if data.get('code', 'normal') == 'zlib':
        import zlib
        content = zlib.decompress(base64.decodestring(data['result']))
    else:
        content = base64.decodestring(data['result'])

    if data['format'] in printer.openers.keys():
        import tempfile
        if data['format'] == 'html' and os.name == 'nt':
            data['format'] = 'doc'
        (fileno, fp_name) = tempfile.mkstemp('.' + data['format'], 'openerp_')
        fp = file(fp_name, 'wb+')
        fp.write(content)
        fp.close()
        os.close(fileno)
        printer.print_file(fp_name, data['format'])
    else:
        fname = common.file_selection(_('Save As...'),
                                      filename='report.' + data['format'],
                                      action=gtk.FILE_CHOOSER_ACTION_SAVE)
        if fname:
            try:
                fp = file(fname, 'wb+')
                fp.write(content)
                fp.close()
            except:
                common.message(_('Error writing the file!'))
Beispiel #9
0
def parse(url):
    with get_session() as s:
        req = s.get(url)

    if 'https://schema.org/OutOfStock' in req.text:
        return message(code='out_of_stock')

    try:
        data_json = find_str(req.text, '"variants":', ',"layoutType"')
        data_prod = json.loads(data_json)[0]
    except (json.decoder.JSONDecodeError, TypeError):
        return message(code='invalid_url')

    prices = {
        i['type']: int(i['price'][0].replace('.', ''))
        for i in data_prod['prices']
    }
    price = prices.get('normalPrice', prices.get('internetPrice', 0))
    price_sale = prices.get('internetPrice', price)
    price_card = prices.get('cmrPrice', price_sale)

    return dict(url=url,
                name=data_prod['name'],
                price=price,
                price_sale=price_sale,
                price_card=price_card,
                image=media_url.format(data_prod['id']),
                raw=data_prod)
Beispiel #10
0
    def sig_action(self,
                   widget=None,
                   keyword='tree_but_action',
                   id=None,
                   report_type='pdf',
                   warning=True):
        ids = self.ids_get()

        if not id and ids and len(ids):
            id = ids[0]
        if id:
            ctx = self.context.copy()
            if 'active_ids' in ctx:
                del ctx['active_ids']
            if 'active_id' in ctx:
                del ctx['active_id']
            obj = service.LocalService('action.main')
            return obj.exec_keyword(keyword, {
                'model': self.model,
                'id': id,
                'ids': ids,
                'report_type': report_type,
                'window': self.window
            },
                                    context=ctx,
                                    warning=warning)
        else:
            common.message(_('No resource selected!'))
        return False
Beispiel #11
0
        def callback_label(self, widget, event, model, name, src, window=None):
            lang_ids = rpc.session.rpc_exec_auth('/object', 'execute',
                                                 'res.lang', 'search',
                                                 [('translatable', '=', '1')])
            if not lang_ids:
                common.message(_('No other language available!'),
                               parent=window)
                return False
            langs = rpc.session.rpc_exec_auth('/object', 'execute', 'res.lang',
                                              'read', lang_ids,
                                              ['code', 'name'])

            win = gtk.Dialog(_('Add Translation'), window,
                             gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT)
            win.vbox.set_spacing(5)
            win.set_position(gtk.WIN_POS_CENTER_ON_PARENT)
            win.set_icon(common.OPENERP_ICON)
            vbox = gtk.VBox(spacing=5)

            entries_list = []
            for lang in langs:
                code = lang['code']
                val = rpc.session.rpc_exec_auth('/object', 'execute', model,
                                                'read_string', False, [code],
                                                [name])
                if val and code in val:
                    val = val[code]
                else:
                    val = {'code': code, 'name': src}
                label = gtk.Label(lang['name'])
                entry = gtk.Entry()
                entry.set_text(val[name])
                entries_list.append((code, entry))
                hbox = gtk.HBox(homogeneous=True)
                hbox.pack_start(label, expand=False, fill=False)
                hbox.pack_start(entry, expand=True, fill=True)
                vbox.pack_start(hbox, expand=False, fill=True)
            vp = gtk.Viewport()
            vp.set_shadow_type(gtk.SHADOW_NONE)
            vp.add(vbox)
            sv = gtk.ScrolledWindow()
            sv.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
            sv.set_shadow_type(gtk.SHADOW_NONE)
            sv.add(vp)
            win.vbox.add(sv)
            win.add_button(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL)
            win.add_button(gtk.STOCK_OK, gtk.RESPONSE_OK)
            win.resize(400, 200)
            win.show_all()
            res = win.run()
            if res == gtk.RESPONSE_OK:
                to_save = map(lambda x: (x[0], x[1].get_text()), entries_list)
                while to_save:
                    code, val = to_save.pop()
                    rpc.session.rpc_exec_auth('/object', 'execute', model,
                                              'write_string', False, [code],
                                              {name: val})
            window.present()
            win.destroy()
            return res
Beispiel #12
0
def parse(url):
    clean_url = pat.findall(url)[0]
    with get_session() as s:
        data = s.get(clean_url, cookies=conf).text

    try:
        page_data = json.loads(find_str(data, 'data: ', ',\n'))
    except JSONDecodeError:
        return message(code='product_not_found')

    if not page_data or 'priceModule' not in page_data:
        return message(code='product_not_found')

    prices = page_data['priceModule']
    price_offer = price = prices['formatedPrice']
    if 'formatedActivityPrice' in prices:
        price_offer = prices['formatedActivityPrice']

    return dict(url=clean_url,
                name=page_data['pageModule']['title'],
                price=price,
                price_sale=price_offer,
                price_card=price_offer,
                image=page_data['pageModule']['imagePath'],
                raw=page_data)
Beispiel #13
0
 def get_value(self, model, timezone=True):
     str = self.entry.get_text()
     if str == '':
         return False
     try:
         date = DT.strptime(str[:19], self.format)
     except:
         return False
     if rpc.session.context.get('tz', False) and timezone:
         try:
             lzone = pytz.timezone(rpc.session.context['tz'])
             szone = pytz.timezone(rpc.session.timezone)
             ldt = lzone.localize(date, is_dst=True)
             sdt = ldt.astimezone(szone)
             date = sdt
         except pytz.UnknownTimeZoneError:
             # Timezones are sometimes invalid under Windows
             # and hard to figure out, so as a low-risk fix
             # in stable branch we will simply ignore the
             # exception and consider client in server TZ
             # (and sorry about the code duplication as well,
             # this is fixed properly in trunk)
             pass
     try:
         return date.strftime(DHM_FORMAT)
     except ValueError:
         common.message(
             _('Invalid datetime value! Year must be greater than 1899 !'))
         return time.strftime(DHM_FORMAT)
Beispiel #14
0
 def exec_report(self, name, data, context={}):
     datas = data.copy()
     ids = datas['ids']
     del datas['ids']
     if not ids:
         ids = rpc.session.rpc_exec_auth('/object', 'execute',
                                         datas['model'], 'search', [])
         if ids == []:
             common.message(_('Nothing to print!'))
             return False
         datas['id'] = ids[0]
     ctx = rpc.session.context.copy()
     ctx.update(context)
     report_id = rpc.session.rpc_exec_auth('/report', 'report', name, ids,
                                           datas, ctx)
     state = False
     attempt = 0
     max_attemps = int(options.options.get('client.timeout') or 0)
     while not state:
         val = rpc.session.rpc_exec_auth('/report', 'report_get', report_id)
         if not val:
             return False
         state = val['state']
         if not state:
             time.sleep(1)
             attempt += 1
         if attempt > max_attemps:
             common.message(_('Printing aborted, too long delay !'))
             return False
     printer.print_data(val)
     return True
Beispiel #15
0
 def rpc_exec(self, obj, method, *args):
     try:
         sock = self._gw(self._url, self.db, self.uid, self._passwd, obj)
         return sock.execute(method, *args)
     except socket.error, e:
         common.message(str(e), title=_('Connection refused !'), type=gtk.MESSAGE_ERROR)
         raise rpc_exception(69, _('Connection refused!'))
Beispiel #16
0
 def rpc_exec_auth(self, obj, method, *args):
     if self._open:
         try:
             sock = self._gw(self._url, self.db, self.uid, self._passwd, obj)
             return sock.exec_auth(method, *args)
         except socket.error, e:
             common.message(_('Unable to reach to OpenERP server !\nYou should check your connection to the network and the OpenERP server.'), _('Connection Error'), type=gtk.MESSAGE_ERROR)
             raise rpc_exception(69, 'Connection refused!')
         except Exception, e:
             if isinstance(e, (xmlrpclib.Fault, tiny_socket.Myexception)):
                 a = rpc_exception(e.faultCode, e.faultString)
                 if isinstance(e.faultCode, int):
                     a.type = 'UserError'
                     a.message = 'Error %s' % e.faultCode
                     a.data = e.faultString
                 if a.type in ('warning','UserError'):
                     if a.message in ('ConcurrencyException') and len(args) > 4:
                         if common.concurrency(args[0], args[2][0], args[4]):
                             if CONCURRENCY_CHECK_FIELD in args[4]:
                                 del args[4][CONCURRENCY_CHECK_FIELD]
                             return self.rpc_exec_auth(obj, method, *args)
                     else:
                         common.warning(a.data, a.message)
                 else:
                     common.error(_('Application Error'), e.faultCode, e.faultString)
             else:
                 common.error(_('Application Error'), _('View details'), str(e))
             #TODO Must propagate the exception?
             raise
Beispiel #17
0
    def sig_select(self, widget=None):
        try:
            # Add the filename from the field with the filename attribute in the view
            filters = []
            if not self.filters:
                filter_file = gtk.FileFilter()
                filter_file.set_name(_('All Files'))
                filter_file.add_pattern('*')
                filters.append(filter_file)
            else:
                for pat in self.filters:
                    filter_file = gtk.FileFilter()
                    filter_file.set_name(str(pat))
                    filter_file.add_pattern(pat)
                    filters.append(filter_file)

            filename = common.file_selection(_('Select a file...'),
                                             parent=self._window,
                                             filters=filters)
            if filename:
                self.model_field.set_client(
                    self._view.model,
                    base64.encodestring(file(filename, 'rb').read()))
                if self.has_filename:
                    self._view.model.set(
                        {self.has_filename: os.path.basename(filename)},
                        modified=True)
                self._view.display(self._view.model)
        except Exception, ex:
            common.message(_('Error reading the file: %s') % str(ex))
Beispiel #18
0
        def send(widget):
            def get_text_from_text_view(textView):
                """Retrieve the buffer from a text view and return the content of this buffer"""
                buffer = textView.get_buffer()
                return buffer.get_text(buffer.get_start_iter(),
                                       buffer.get_end_iter())

            # Use details_buffer
            tb = get_text_from_text_view(
                xmlGlade.get_widget('details_explanation'))
            explanation = get_text_from_text_view(
                xmlGlade.get_widget('explanation_textview'))
            remarks = get_text_from_text_view(
                xmlGlade.get_widget('remarks_textview'))
            summary = xmlGlade.get_widget('summary_entry').get_text()

            if rpc.session.rpc_exec_auth_try('/object', 'execute',
                                             'maintenance.contract', 'send',
                                             tb, explanation, remarks,
                                             summary):
                common.message(_(
                    'Your problem has been sent to the quality team !\nWe will recontact you after analysing the problem.'
                ),
                               parent=win)
                win.destroy()
            else:
                common.message(_(
                    'Your problem could *NOT* be sent to the quality team !\nPlease report this error manually at:\n\t%s'
                ) % ('http://openerp.com/report_bug.html', ),
                               title=_('Error'),
                               type=gtk.MESSAGE_ERROR,
                               parent=win)
Beispiel #19
0
    def cal_open(self, widget, event, model=None, window=None):
        if self.readonly:
            common.message(_('This widget is readonly !'))
            return True

        win = gtk.Dialog(_('OpenERP - Date selection'), window,
                         gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
                         (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OK,
                          gtk.RESPONSE_OK))

        hbox = gtk.HBox()
        hbox.pack_start(gtk.Label(_('Hour:')), expand=False, fill=False)
        hour = gtk.SpinButton(gtk.Adjustment(0, 0, 23, 1, 5), 1, 0)
        hbox.pack_start(hour, expand=True, fill=True)
        hbox.pack_start(gtk.Label(_('Minute:')), expand=False, fill=False)
        minute = gtk.SpinButton(gtk.Adjustment(0, 0, 59, 1, 10), 1, 0)
        hbox.pack_start(minute, expand=True, fill=True)
        win.vbox.pack_start(hbox, expand=False, fill=True)

        cal = gtk.Calendar()
        cal.display_options(gtk.CALENDAR_SHOW_HEADING
                            | gtk.CALENDAR_SHOW_DAY_NAMES
                            | gtk.CALENDAR_SHOW_WEEK_NUMBERS)
        cal.connect('day-selected-double-click',
                    lambda *x: win.response(gtk.RESPONSE_OK))
        win.vbox.pack_start(cal, expand=True, fill=True)
        win.show_all()

        try:
            val = self.get_value(model, timezone=False)
            if val:
                hour.set_value(int(val[11:13]))
                minute.set_value(int(val[-5:-3]))
                cal.select_month(int(val[5:7]) - 1, int(val[0:4]))
                cal.select_day(int(val[8:10]))
            else:
                hour.set_value(time.localtime()[3])
                minute.set_value(time.localtime()[4])
        except ValueError:
            pass
        response = win.run()
        if response == gtk.RESPONSE_OK:
            hr = int(hour.get_value())
            mi = int(minute.get_value())
            dt = cal.get_date()
            month = int(dt[1]) + 1
            day = int(dt[2])
            date = DT(dt[0], month, day, hr, mi)
            try:
                value = date.strftime(DHM_FORMAT)
            except ValueError:
                common.message(
                    _('Invalid datetime value! Year must be greater than 1899 !'
                      ))
            else:
                self.show(value, timezone=False)

        self._focus_out()
        win.destroy()
Beispiel #20
0
	def sig_add(self, widget=None):
		try:
			filename = common.file_selection(_('Select the file to picture(jpg,jpeg,gif,png)'))			
			#self.wid_text.set_text(filename)
			self.value=base64.encodestring(file(filename).read())
			self.preview()
		except:
			common.message(_('Error reading the file'))		
Beispiel #21
0
	def sig_save_as(self, widget=None):
		try:
			filename = common.file_selection(_('Save attachment as...'))
			fp = file(filename,'wb+')
			fp.write(base64.decodestring(self.value))
			fp.close()
		except:
			common.message(_('Error writing the file!'))
Beispiel #22
0
 def sig_chroot(self, widget=None):
     ids = self.ids_get()
     if len(ids) and self.domain:
         id = ids[0]
         datas = {'domain_field': self.domain[0][0], 'domain_value': id[0], 'res_id':id[0]}
         obj = service.LocalService('gui.window')
         obj.create(self.view, self.model, id[0], (self.domain[0],id[0]) )
     else:
         common.message(_('Unable to chroot: no tree resource selected'))
Beispiel #23
0
 def sig_remove(self, widget=None):
     ids = self.ids_get()
     if len(ids):
         if common.sur(_('Are you sure you want\nto remove this record?')):
             try:
                 rpc.session.rpc_exec_auth('/object', 'execute', self.model, 'unlink', ids)
                 self.sig_reload()
             except xmlrpclib.Fault, err:
                 common.message(_('Error removing resource!'))
 def click_and_action(self, type):
     pos = self.tree_view.pos_get()
     if pos!=None:
         val = self._value[pos]
         id = val.get('id', False)
         obj = service.LocalService('action.main')
         res = obj.exec_keyword(type, {'model':self.model, 'id': id or False, 'ids':[id], 'report_type': 'pdf'})
         return True
     else:
         common.message(_('You have to select a resource !'))
         return False
Beispiel #25
0
 def get_resource(self,widget):
     all_ids = rpc.session.rpc_exec_auth('/object', 'execute', self.model, 'search', [])
     get_id = int(widget.get_value())
     if get_id in all_ids:
         current_ids = self.screen.ids_get()
         if get_id in current_ids:
             self.screen.display(get_id)
         else:
             self.screen.load([get_id])    
         self.screen.current_view.set_cursor()
     else:
         common.message(_('Resource ID does not exist for this object!'))    
Beispiel #26
0
    def cal_open(self, widget, event, dest, parent=None):
        win = gtk.Dialog(_('OpenERP - Date selection'), parent,
                gtk.DIALOG_MODAL|gtk.DIALOG_DESTROY_WITH_PARENT,
                (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
                gtk.STOCK_OK, gtk.RESPONSE_OK))

        hbox = gtk.HBox()
        hbox.pack_start(gtk.Label(_('Hour:')), expand=False, fill=False)
        hour = gtk.SpinButton(gtk.Adjustment(0, 0, 23, 1, 5), 1, 0)
        hbox.pack_start(hour, expand=True, fill=True)
        hbox.pack_start(gtk.Label(_('Minute:')), expand=False, fill=False)
        minute = gtk.SpinButton(gtk.Adjustment(0, 0, 59, 1, 10), 1, 0)
        hbox.pack_start(minute, expand=True, fill=True)
        win.vbox.pack_start(hbox, expand=False, fill=True)

        cal = gtk.Calendar()
        cal.display_options(gtk.CALENDAR_SHOW_HEADING|gtk.CALENDAR_SHOW_DAY_NAMES|gtk.CALENDAR_SHOW_WEEK_NUMBERS)
        cal.connect('day-selected-double-click', lambda *x: win.response(gtk.RESPONSE_OK))
        win.vbox.pack_start(cal, expand=True, fill=True)
        win.show_all()

        try:
            val = self.get_value(dest, timezone=False)
            if val:
                val = DT.datetime.strptime(val[:len(DHM_FORMAT) + 2], DHM_FORMAT)
                hour.set_value(val.hour)
                minute.set_value(val.minute)
                cal.select_month(val.month-1, val.year)
                cal.select_day(val.day)
            elif dest == self.entry1:
                hour.set_value(0)
                minute.set_value(0)
            elif dest == self.entry2:
                hour.set_value(23)
                minute.set_value(59)
        except ValueError:
            pass
        response = win.run()
        if response == gtk.RESPONSE_OK:
            hr = int(hour.get_value())
            mi = int(minute.get_value())
            year, month, day = cal.get_date()
            date = DT.datetime(year, month+1, day, hr, mi)
            try:
                value = date.strftime(DHM_FORMAT)
            except ValueError:
                common.message(_('Invalid datetime value! Year must be greater than 1899 !'))
            else:
                self.set_datetime(value, dest, timezone=False)

        win.destroy()
Beispiel #27
0
 def sig_edit(self, widget=None):
     id = False
     ids = self.ids_get()
     if ids:
         id = ids[0]
     elif self.tree_res.toolbar:
         wid = self.glade.get_widget('tree_toolbar')
         for w in wid.get_children():
             if w.get_active():
                 id = w.get_data('id')
     if id:
         obj = service.LocalService('gui.window')
         obj.create(None, self.model, id, self.domain)
     else:
         common.message(_('No resource selected!'))
Beispiel #28
0
    def get_value(self, model):
        str = self.entry.get_text()
        if str == '':
            return False
        try:
            date1 = DT.strptime(str[:10], self.format)
        except:
            return False

        try:
            return date1.strftime(DT_FORMAT)
        except ValueError:
            common.message(
                _('Invalid date value! Year must be greater than 1899 !'))
            return time.strftime(DT_FORMAT)
Beispiel #29
0
 def _click_and_relate(self, action, value, model):
     data={}
     context={}
     act=action.copy()
     if not(value):
         common.message(_('You must select a record to use the relation !'))
         return False
     from widget.screen import Screen
     screen = Screen(model)
     screen.load([value])
     act['domain'] = screen.current_model.expr_eval(act['domain'], check_load=False)
     act['context'] = str(screen.current_model.expr_eval(act['context'], check_load=False))
     obj = service.LocalService('action.main')
     value = obj._exec_action(act, data, context)
     return value
Beispiel #30
0
    def get_vm_list(self, filter_params={}):
        self.header_keys = [
            'region', 'name', 'type', 'public_ips', 'private_ips', 'state'
        ]
        self.header_titles = [
            'Region', 'Name', 'Instance Type', 'Public Ips', 'Private Ips',
            'state'
        ]
        p_region = filter_params.get("region", "")
        p_instance = filter_params.get("instance", "")
        info = False
        if p_instance:
            info = True
        ec2_regions = []
        available_ec2_regions = boto3.session.Session().get_available_regions(
            self.instance_type)
        if p_region > "":
            if p_region in available_ec2_regions:
                ec2_regions = [p_region]
            else:
                msg = str(p_region) + " is not a valid region for ec2."
                exit_message(msg, 1, self.isJson)
        else:
            ec2_regions = available_ec2_regions

        ec2_hosts = []
        for region in ec2_regions:
            try:
                msg = "Searching " + region + "..."
                message(msg, "info", self.isJson)
                ec2 = get_client('ec2', region=region)
                hosts = ec2.describe_instances()
                for host in hosts['Reservations']:
                    for h in host['Instances']:
                        if p_instance > "":
                            if p_instance != h['InstanceId']:
                                continue
                        vm = AwsVM(h)
                        vm.region = region
                        if p_instance:
                            vm.set_extra_info(h)
                        if self.verbose:
                            print_verbose(vm.__dict__)
                        ec2_hosts.append(vm.__dict__)
            except Exception as e:
                pass

        return ec2_hosts