def guest_remove(self, operator, username): """ Set a new expire-quarantine that starts now. The guest account will be blocked from export to any system. """ account = self._get_account(username) self.ba.can_remove_personal_guest(operator.get_entity_id(), guest=account) # Deactivate the account (expedite quarantine) and adjust expire_date try: end_date = account.get_entity_quarantine( self.const.quarantine_guest_old)[0]['start_date'] if end_date < DateTime.now(): raise CerebrumError("Account '%s' is already deactivated" % account.account_name) account.delete_entity_quarantine(self.const.quarantine_guest_old) except IndexError: self.logger.warn('Guest %s didn\'t have expire quarantine, ' 'deactivated anyway.', account.account_name) account.add_entity_quarantine(qtype=self.const.quarantine_guest_old, creator=operator.get_entity_id(), description='New guest account', start=DateTime.now()) account.expire_date = DateTime.now() account.write_db() return 'Ok, %s quarantined, will be removed' % account.account_name
def test_get_quarantine(entity, initial_account, quar_x, quar_y): entity.add_entity_quarantine(quar_x, initial_account.entity_id, start=dt.now() + 1) quars = entity.get_entity_quarantine() assert len(quars) == 1 quars = entity.get_entity_quarantine(qtype=quar_y) assert len(quars) == 0 entity.add_entity_quarantine(quar_y, initial_account.entity_id, start=dt.now() - 1) entity.disable_entity_quarantine(quar_y, dt.now() + 1) quars = entity.get_entity_quarantine() assert len(quars) == 2 quars = entity.get_entity_quarantine(qtype=quar_x) assert len(quars) == 1 assert quars[0]['quarantine_type'] == quar_x quars = entity.get_entity_quarantine(qtype=quar_x, only_active=True) assert len(quars) == 0 quars = entity.get_entity_quarantine(qtype=quar_y, filter_disable_until=True) assert len(quars) == 0
def guest_remove(self, operator, username): """ Set a new expire-quarantine that starts now. The guest account will be blocked from export to any system. """ account = self._get_account(username) self.ba.can_remove_personal_guest(operator.get_entity_id(), guest=account) # Deactivate the account (expedite quarantine) and adjust expire_date try: end_date = account.get_entity_quarantine( self.const.quarantine_guest_old)[0]['start_date'] if end_date < DateTime.now(): raise CerebrumError("Account '%s' is already deactivated" % account.account_name) account.delete_entity_quarantine(self.const.quarantine_guest_old) except IndexError: self.logger.warn( 'Guest %s didn\'t have expire quarantine, ' 'deactivated anyway.', account.account_name) account.add_entity_quarantine(qtype=self.const.quarantine_guest_old, creator=operator.get_entity_id(), description='New guest account', start=DateTime.now()) account.expire_date = DateTime.now() account.write_db() return 'Ok, %s quarantined, will be removed' % account.account_name
def IsScriptValid(self, script): hasAccess = self.access if hasAccess: self.SetAccessToFunctionality(0) self.output.AppendText("*** Begin Validation - %s ***\n" % str(DateTime.now())) isValid, error = self.GetDocument().IsScriptValid(script, self.output) if not isValid: self.SetStatus(ILLICIT) for e in error[-4:]: self.output.AppendText(e + "\n") else: self.SetStatus(VALID) if isValid: self.output.AppendText("\nYour observing script is syntactically correct!\n\n") self.output.AppendText("*** End Validation - %s ***\n" % str(DateTime.now())) self.output.AppendText("\n\n") if hasAccess: self.SetAccessToFunctionality(1) return isValid
def format_report(roles, names, ansatt_nr, stedkoder): """Generate a report.""" start_time = DateTime.now() logger.debug('Generating report') lines = [ '%-35s %-10s %-8s %-10s %-8s %s\n' % ('Navn', 'AnsattNr', 'Rolle', 'Journal', 'Stedkode', 'Standardrolle') ] for p_id in roles.keys(): try: l = '%-35s %-10s ' % (names[p_id], ansatt_nr[p_id]) except KeyError: l = '%-35s %-10s ' % (names[p_id], '') rs = roles[p_id] role = rs.pop(0) l += '%-8s %-10s %-8s %s\n' % ( str(co.EphorteRole(role['role_type'])), str(co.EphorteJournalenhet(role['journalenhet'])), stedkoder[role['adm_enhet']], role['standard_role']) for role in rs: l += '%-47s%-8s %-10s %-8s %s\n' % ( '', str(co.EphorteRole(role['role_type'])), str(co.EphorteJournalenhet(role['journalenhet'])), stedkoder[role['adm_enhet']], role['standard_role']) lines.append(l) logger.debug('Report generated in %s' % str(DateTime.now() - start_time)) return lines
def collect_expired_roles(age): """Collectis and returns all roles that belong to people who have had their last affiliation from SAP deleted age days ago.""" now = DateTime.now() oldness = now - int(age) logger.debug('Collecting expired roles') logger.debug('Selecting by affiliation deleted before %s' % str(oldness)) expired_person_ids = [] roles = {} for row in er.list_roles(): roles.setdefault(row['person_id'], []).extend([row]) for p_id in roles.keys(): exp = True for aff in pe.list_affiliations(person_id=p_id, source_system=co.system_sap, include_deleted=True): if not aff['deleted_date'] or aff['deleted_date'] > oldness: exp = False if exp: expired_person_ids.append(p_id) for key in roles.keys(): if not key in expired_person_ids: del roles[key] logger.debug('%d roles collected in %s' % (len(roles), str(DateTime.now() - now))) return roles
def format_report(roles, names, ansatt_nr, stedkoder): """Generate a report.""" start_time = DateTime.now() logger.debug('Generating report') lines = ['%-35s %-10s %-8s %-10s %-8s %s\n' % ('Navn', 'AnsattNr', 'Rolle', 'Journal', 'Stedkode', 'Standardrolle')] for p_id in roles.keys(): try: l = '%-35s %-10s ' % (names[p_id], ansatt_nr[p_id]) except KeyError: l = '%-35s %-10s ' % (names[p_id], '') rs = roles[p_id] role = rs.pop(0) l += '%-8s %-10s %-8s %s\n' % (str(co.EphorteRole(role['role_type'])), str(co.EphorteJournalenhet(role['journalenhet'])), stedkoder[role['adm_enhet']], role['standard_role']) for role in rs: l += '%-47s%-8s %-10s %-8s %s\n' % ('', str(co.EphorteRole(role['role_type'])), str(co.EphorteJournalenhet(role['journalenhet'])), stedkoder[role['adm_enhet']], role['standard_role']) lines.append(l) logger.debug('Report generated in %s' % str(DateTime.now() - start_time)) return lines
def __verify_detect_packet(self, packet): lines = string.split(packet, cClinitek50.EOL) # product ID: 6510 = Clinitek 50 tmp = lines[1][:4] if tmp != cClinitek50.dev_id: _log.Log(gmLog.lErr, 'device does not seem to be a Clinitek 50, product ID is [%s], expected [%s]' % (tmp, cClinitek50.dev_id)) _log.Log(gmLog.lData, lines) return None # product revision tmp = lines[1][4:6] if tmp not in cClinitek50.known_good_dev_revs: _log.Log(gmLog.lWarn, 'product revision [%s] untested, trying to continue anyways' % tmp) # software version tmp = lines[1][6:11] if tmp not in cClinitek50.known_good_sw_versions: _log.Log(gmLog.lWarn, 'software version [%s] untested, trying to continue anyways' % tmp) # date/time timestamp = mxDT.strptime(lines[1][12:22], self.__date_format + cClinitek50.time_format) _log.Log(gmLog.lInfo, 'device timestamp: %s' % timestamp) _log.Log(gmLog.lInfo, 'system timestamp: %s' % mxDT.now()) age = mxDT.Age(mxDT.now(), timestamp) if age.hours > 6: _log.Log(gmLog.lErr, 'device time is off by %s, please correct that' % age) return None # language-unit profile (lang, units) = string.split(lines[2], ' - ') _log.Log(gmLog.lInfo, 'language: %s' % lang) _log.Log(gmLog.lInfo, 'unit system: %s' % units) # STIX type stix_type = string.strip(lines[3]) if not stix_type in cClinitek50.known_stix_types: _log.Log(gmLog.lErr, "don't know how to handle stix of type %s" % stix_type) return None # seems valid return 1
def test_reldat(self): # Picking values for relative datetime tests is difficult - the clock # is running, and first-of-month (etc) change the result. ds = self._get_reldate_ds() self.assertRaises(ValueError, Filter.DatasetFilter, ds, 'test_filter', 'a >= reldate(days=-1, months=-1)') self.assertRaises(TypeError, Filter.DatasetFilter, ds, 'test_filter', 'a >= reldate(poo=1)') self.assertRaises(ValueError, Filter.DatasetFilter, ds, 'test_filter', 'a >= reldate(align="xxx")') self._test(ds, 'a >= reldate(days=+1)', [0]) self._test(ds, 'a >= reldate()', [0, 1]) self._test(ds, 'a >= reldate(days=0)', [0, 1]) self._test(ds, 'a >= reldate(days=-1)', [0, 1, 2]) if DateTime.now().day_of_week == 0: self._test(ds, 'a >= reldate(days=-7)', [0, 1, 2, 3, 4]) # this fails on Mondays! else: self._test(ds, 'a >= reldate(days=-7)', [0, 1, 2, 3]) # this fails on Mondays! self._test(ds, 'a >= reldate(days=-7, align="monday")', [0, 1, 2, 3, 4]) if DateTime.now().day == 1: expect = [0, 1, 2, 3, 4, 5, 6] else: expect = [0, 1, 2, 3, 4, 5] self._test(ds, 'a >= reldate(months=-1)', expect) self._test(ds, 'a >= reldate(months=-1, align="bom")', [0, 1, 2, 3, 4, 5, 6]) if DateTime.now().day == 1 and DateTime.now().month == DateTime.January: expect = [0, 1, 2, 3, 4, 5, 6, 7, 8] else: expect = [0, 1, 2, 3, 4, 5, 6, 7] self._test(ds, 'a >= reldate(years=-1)', expect) self._test(ds, 'a >= reldate(years=-1, align="boy")', [0, 1, 2, 3, 4, 5, 6, 7, 8]) if DateTime.now().day_of_week == 0: self._test(ds, 'a between(reldate(days=-7), reldate(days=-2))', [3, 4]) # also fails on Mondays else: self._test(ds, 'a between(reldate(days=-7), reldate(days=-2))', [3])
def _carnet_before(self): import mx.DateTime as dt res = {} res_list = [] today = dt.now() before_date = dt.now() + dt.RelativeDateTime(months=1) before_date = before_date.strftime("%Y-%m-%d") today = today.strftime("%Y-%m-%d") carnet_obj = self.pool.get('cci_missions.ata_carnet') carnet_ids = carnet_obj.search(self.cr, self.uid, [('validity_date', '<=', before_date), ('validity_date', '>=', today), ('state', '>=', 'created')]) carnet_data = carnet_obj.browse(self.cr, self.uid, carnet_ids) for carnet in carnet_data: flag = False address = '' for letter in carnet.letter_ids: if letter.letter_type == 'Rappel avant echeance': flag = True if not flag: if carnet.partner_id.address: for add in carnet.partner_id.address: if add.type == 'default': address = (add.street or '') + ' ' + ( add.street2 or '') + '\n' + ( add.zip_id and add.zip_id.name or '') + ' ' + (add.city or '') + '\n' + ( add.state_id and add.state_id.name or '') + ' ' + (add.country_id and add.country_id.name or '') continue else: address = (add.street or '') + ' ' + ( add.street2 or '') + '\n' + ( add.zip_id and add.zip_id.name or '') + ' ' + (add.city or '') + '\n' + ( add.state_id and add.state_id.name or '') + ' ' + (add.country_id and add.country_id.name or '') res = { 'partner_name': carnet.partner_id.name, 'partner_address': address, 'type': carnet.type_id.name, 'name': carnet.name, 'creation_date': carnet.creation_date, 'validity_date': carnet.validity_date } res_letter = { 'letter_type': 'Rappel avant echeance', 'date': time.strftime('%Y-%m-%d'), 'ata_carnet_id': carnet.id, } id = self.pool.get('cci_missions.letters_log').create( self.cr, self.uid, res_letter) res_list.append(res) return res_list
def _create_ou(self, input): """Create the project OU based on given input.""" pname = input['p_id'] ou.clear() pid = ou.create_project(pname) logger.debug("New project %s named: %s", pid, pname) # The gateway should not be informed about new projects before they're # approved, so if we should create the project in the GW, we must also # execute: gateway.freeze_project(pid) longname = input['p_name'] logger.debug("Storing project name: %s", longname) ou.add_name_with_language(name_variant=co.ou_name_long, name_language=co.language_en, name=longname) shortname = input['p_shortname'] logger.debug("Storing project short name: %s", shortname) ou.add_name_with_language(name_variant=co.ou_name_long, name_language=co.language_en, name=shortname) ou.write_db() # Always start projects quarantined, needs to be approved first! logger.debug("Project %s starting in quarantine 'not_approved'", pid) ou.add_entity_quarantine(qtype=co.quarantine_not_approved, creator=systemaccount_id, description='Project not approved yet', start=DateTime.now()) ou.write_db() # Storing the start and end date: endtime = input['project_end'] if endtime < DateTime.now(): raise BadInputError("End date of project has passed: %s" % endtime) ou.add_entity_quarantine(qtype=co.quarantine_project_end, creator=systemaccount_id, description='Initial requested lifetime for project', start=endtime) ou.write_db() starttime = input['project_start'] # We always set the start time quarantine, even if the start time has # passed. This is to let the administrators see the start time in bofh. ou.add_entity_quarantine(qtype=co.quarantine_project_start, creator=systemaccount_id, description='Initial requested starttime for project', start=DateTime.now() - 1000, end=starttime) ou.write_db() ou.populate_trait(co.trait_project_institution, target_id=ou.entity_id, strval=input['inst_address']) ou.populate_trait(co.trait_project_rek, target_id=ou.entity_id, strval=input['legal_notice']) # TODO: Should we have a mapping of vm_descr? ou.populate_trait(co.trait_project_vm_type, target_id=ou.entity_id, strval=input['vm_descr']) ou.write_db() logger.debug("New project created successfully: %s", pid) # The project will not be properly set up before it gets approved. The # gateway will for instance not hear about it before it's approved. return ou
def __init__(self, id): """Feed the authenticator instance with the identifier of the authenticated entity.""" if not id: raise AuthenticationError('Empty identitifer is not allowed') self.authenticated = True self.id = id self.started = DateTime.now() self.lastAccessed = DateTime.now()
def date_today(self, cr, uid, ids, context): for sheet in self.browse(cr, uid, ids, context): if DateTime.now() <= DateTime.strptime(sheet.date_from, "%Y-%m-%d"): self.write(cr, uid, [sheet.id], {"date_current": sheet.date_from}) elif DateTime.now() >= DateTime.strptime(sheet.date_to, "%Y-%m-%d"): self.write(cr, uid, [sheet.id], {"date_current": sheet.date_to}) else: self.write(cr, uid, [sheet.id], {"date_current": time.strftime("%Y-%m-%d")}) return True
def _default_date_to(self, cr, uid, context={}): user = self.pool.get("res.users").browse(cr, uid, uid, context) r = user.company_id and user.company_id.timesheet_range or "month" if r == "month": return (DateTime.now() + DateTime.RelativeDateTime(months=+1, day=1, days=-1)).strftime("%Y-%m-%d") elif r == "week": return (DateTime.now() + DateTime.RelativeDateTime(weekday=(DateTime.Sunday, 0))).strftime("%Y-%m-%d") elif r == "year": return time.strftime("%Y-12-31") return time.strftime("%Y-%m-%d")
def _get_out(self, cr, uid, data, context): args = {} pool = pooler.get_pool(cr.dbname) statement_obj= pool.get('account.bank.statement') product_obj= pool.get('product.template') productp_obj= pool.get('product.product') res_obj = pool.get('res.users') curr_company = res_obj.browse(cr,uid,uid).company_id.id statement_id = statement_obj.search(cr,uid, [('journal_id','=',data['form']['journal_id']),('company_id','=',curr_company),('user_id','=',uid),('state','=','open')]) monday = (DateTime.now() + DateTime.RelativeDateTime(weekday=(DateTime.Monday,0))).strftime('%Y-%m-%d') sunday = (DateTime.now() + DateTime.RelativeDateTime(weekday=(DateTime.Sunday,0))).strftime('%Y-%m-%d') done_statmt = statement_obj.search(cr,uid, [('date','>=',monday+' 00:00:00'),('date','<=',sunday+' 23:59:59'),('journal_id','=',data['form']['journal_id']),('company_id','=',curr_company),('user_id','=',uid)]) stat_done = statement_obj.browse(cr,uid, done_statmt) address_u = pool.get('res.users').browse(cr,uid,uid).address_id am = 0.0 amount_check = productp_obj.browse(cr,uid,data['form']['product_id']).am_out or False for st in stat_done: for s in st.line_ids: if address_u and s.partner_id==address_u.partner_id and s.am_out: am+=s.amount if (-data['form']['amount'] or 0.0)+ am <-(res_obj.browse(cr,uid,uid).company_id.max_diff or 0.0) and amount_check: val = (res_obj.browse(cr,uid,uid).company_id.max_diff or 0.0)+ am raise wizard.except_wizard(_('Error !'), _('The maximum value you can still withdraw is exceeded. \n Remaining value is equal to %d ')%(val)) acc_id = product_obj.browse(cr,uid,data['form']['product_id']).property_account_income if not acc_id: raise wizard.except_wizard(_('Error !'), _('please check that account is set to %s')%(product_obj.browse(cr,uid,data['form']['product_id']).name)) if not statement_id: raise wizard.except_wizard(_('Error !'), _('You have to open at least one cashbox')) if statement_id: statement_id = statement_id[0] if not statement_id: statement_id = statement_obj.create(cr,uid,{'date':time.strftime('%Y-%m-%d 00:00:00'), 'journal_id':data['form']['journal_id'], 'company_id':curr_company, 'user_id':uid, }) args['statement_id']= statement_id args['journal_id']= data['form']['journal_id'] if acc_id: args['account_id']= acc_id.id amount= data['form']['amount'] or 0.0 if data['form']['amount'] > 0: amount= -data['form']['amount'] args['amount'] = amount if productp_obj.browse(cr,uid,data['form']['product_id']).am_out: args['am_out'] = True args['ref'] = data['form']['ref'] or '' args['name'] = "%s: %s "%(product_obj.browse(cr,uid,data['form']['product_id']).name, data['form']['name'].decode('utf8')) address_u = pool.get('res.users').browse(cr,uid,uid).address_id if address_u: partner_id = address_u.partner_id and address_u.partner_id.id or None args['partner_id'] = partner_id statement_line_id = pool.get('account.bank.statement.line').create(cr, uid, args) return {}
def writeContent(self, trans=None): # # this servlet creates Vendor data # account = self.transaction.request().field('account','') page = self.transaction.request().field('page','Main') # # create vendor object # globalSetVars = self._globalSetVars store = globalSetVars['store'] if self.transaction.request().field('VendorNr',None)[-1:] == "0": storeObjects = store.fetchObjectsOfClass('IDs','WHERE %s = "%s"' % ('Tablename',self.storeName)) if (len(storeObjects) == 1) and self.transaction.request().field('ID',None): id = storeObjects[0] id.setLastID(int(self.transaction.request().field('VendorNr',None))) vendor = AccountsVE() # # change vendor object # for attr in vendorAttrs: if attr not in standardAttrs: if vendorFields[attr][vendorType] == 'string': vendor.setValueForKey(attr, string.strip(self.transaction.request().field(attr,''))) elif vendorFields[attr][vendorType] == 'float': vendor.setValueForKey(attr, float(string.replace(self.transaction.request().field(attr,'0,0'),',','.'))) elif (vendorFields[attr][vendorType] == 'datetime') and self.request.field(attr,''): vendor.setValueForKey(attr, DateTime.DateTimeFrom(self.transaction.request().field(attr,''))) elif (vendorFields[attr][vendorType] == 'date') and self.transaction.request().field(attr,''): vendor.setValueForKey(attr, DateTime.DateTimeFrom(self.transaction.request().field(attr,''))) # # set standard attributes # vendor.setErsteingabeAm(DateTime.now()) vendor.setChangedBy(self.transaction.session().value('authenticated_user','')) vendor.setChangedAt(DateTime.now()) vendor.setChangedOn(self.getSite()) # # store vendor in database # store.addObject(vendor) try: store.saveChanges() # # back to vendor page # self.transaction.response().sendRedirect('VendorView?index=' + account[2:]) except OperationalError,x: store.discardEverything() errorCode,errorText = x # # back to error page # self.transaction.response().sendRedirect('Error?problem=Daten+konnten+nicht+gespeichert+werden!&reason=' + urlEncode(str(errorText)))
def collect_person_names(): """Collect and return all full names in a dict, indexed by entity_id.""" start_time = DateTime.now() logger.debug('Collecting person names') names_by_id = {} for row in pe.search_person_names(name_variant=co.name_full, source_system=co.system_cached): names_by_id[row['person_id']] = row['name'] logger.debug('%d names collected in %s' % (len(names_by_id), str(DateTime.now() - start_time))) return names_by_id
def collect_ansattnr(): """Collect and return all ansattnrs in a dict, indexed by entity_id.""" start_time = DateTime.now() logger.debug('Collecting all ansattnrs') ansattnr_by_id = {} for row in pe.list_external_ids(source_system=co.system_sap, id_type=co.externalid_sap_ansattnr): ansattnr_by_id[row['entity_id']] = row['external_id'] logger.debug('%d ansattnrs collected in %s' % (len(ansattnr_by_id), str(DateTime.now() - start_time))) return ansattnr_by_id
def writeContent(self, trans=None): # # this servlet creates Expenses data # page = self.transaction.request().field('page','Main') # # create Expenses object # globalSetVars = self._globalSetVars store = globalSetVars['store'] ExpensesNr=self.transaction.request().field('Nr','') Expenses = AccountsAK() # # change Expenses object # for attr in ExpensesAttrs: if attr not in standardAttrs: if ExpensesFields[attr][ExpensesType] == 'string': print self.transaction.request().field(attr,'') Expenses.setValueForKey(attr, self.transaction.request().field(attr,'')) elif ExpensesFields[attr][ExpensesType] == 'float': Expenses.setValueForKey(attr, float(string.replace(self.transaction.request().field(attr,'0,0'),',','.'))) elif (ExpensesFields[attr][ExpensesType] == 'datetime') and self.request.field(attr,''): Expenses.setValueForKey(attr, DateTime.DateTimeFrom(self.transaction.request().field(attr,''))) elif (ExpensesFields[attr][ExpensesType] == 'date') and self.transaction.request().field(attr,''): Expenses.setValueForKey(attr, DateTime.DateTimeFrom(self.transaction.request().field(attr,''))) # # set standard attributes # Expenses.setID('AK'+ExpensesNr) Expenses.setErsteingabeAm(DateTime.now()) Expenses.setChangedBy(self.transaction.session().value('authenticated_user','')) Expenses.setChangedAt(DateTime.now()) Expenses.setChangedOn(self.getSite()) # # store Expenses in database # store.addObject(Expenses) try: store.saveChanges() # # back to Expenses page # self.transaction.response().sendRedirect('ExpensesView?index=' + ExpensesNr) except OperationalError,x: store.discardEverything() errorCode,errorText = x # # back to error page # self.transaction.response().sendRedirect('Error?problem=Daten+konnten+nicht+gespeichert+werden!&reason=' + urlEncode(str(errorText)))
def OnPlotBeam(self, event): try: self.output.AppendText("*** Begin Plot Beam - %s ***\n" % str(DateTime.now())) pts = self.GetDocument().PlotBeam(self.editor.GetText(), self.output) # This will fail, currently, because of incompatible versions of matplotlib # but *should* work in theory once that is fixed mapper = BeamMap(pts) mapper.main() self.output.AppendText("\n\n*** End Plot Beam - %s ***\n" % str(DateTime.now())) self.output.AppendText("\n\n") except: exc = sys.exc_info() print "WHOOPS %s, %s, %s"%(exc[0],exc[1],exc[2].tb_lineno)
def collect_stedkoder(): """Collect and return all stedkoder in a dict, indexed by entity_id.""" start_time = DateTime.now() logger.debug('Collecting all stedkoder') ous = ou.get_stedkoder() stedkoder = {} for x in ous: stedkoder[x['ou_id']] = '%02d%02d%02d' % ( x['fakultet'], x['institutt'], x['avdeling']) logger.debug('%d stedkoder collected in %s' % (len(stedkoder), str(DateTime.now() - start_time))) return stedkoder
def writeContent(self, trans=None): # # this servlet creates Member data # account = self.transaction.request().field('account','') page = self.transaction.request().field('page','Main') # # create personal object # globalSetVars = self._globalSetVars store = globalSetVars['store'] personal = AccountsTR() # # change personal object # for attr in personalAttrs: if attr not in standardAttrs: if personalFields[attr][personalType] == 'string': print self.transaction.request().field(attr,'') personal.setValueForKey(attr, self.transaction.request().field(attr,'')) elif personalFields[attr][personalType] == 'float': if string.strip(self.transaction.request().field(attr,'')): personal.setValueForKey(attr, float(string.replace(self.transaction.request().field(attr,'0,00'),',','.'))) else: personal.setValueForKey(attr, None) elif (personalFields[attr][personalType] == 'datetime') and self.request.field(attr,''): personal.setValueForKey(attr, DateTime.DateTimeFrom(self.transaction.request().field(attr,''))) elif (personalFields[attr][personalType] == 'date') and self.transaction.request().field(attr,''): personal.setValueForKey(attr, DateTime.DateTimeFrom(self.transaction.request().field(attr,''))) # # set standard attributes # personal.setErsteingabeAm(DateTime.now()) personal.setChangedBy(self.transaction.session().value('authenticated_user','')) personal.setChangedAt(DateTime.now()) personal.setChangedOn(self.getSite()) # # store personal in database # store.addObject(personal) try: store.saveChanges() except OperationalError,x: store.discardEverything() errorCode,errorText = x # # back to error page # self.transaction.response().sendRedirect('Error?problem=Daten+konnten+nicht+gespeichert+werden!&reason=' + urlEncode(str(errorText)))
def collect_stedkoder(): """Collect and return all stedkoder in a dict, indexed by entity_id.""" start_time = DateTime.now() logger.debug('Collecting all stedkoder') ous = ou.get_stedkoder() stedkoder = {} for x in ous: stedkoder[x['ou_id']] = '%02d%02d%02d' % (x['fakultet'], x['institutt'], x['avdeling']) logger.debug('%d stedkoder collected in %s' % (len(stedkoder), str(DateTime.now() - start_time))) return stedkoder
def create_project(self, pid): """ See .Gateway.GatewayClient. """ self.logger.info("Creating project: %s", pid) try: self._get_project_idx(pid) except Err: pass else: raise Err("Project %s exists" % pid) p = {'frozen': None, 'expires': DateTime.now()+10, 'name': pid, 'created': DateTime.now(), } self._projects.append(p) return p
def get_requests(self, request_id=None, operator_id=None, entity_id=None, operation=None, destination_id=None, given=False, only_runnable=False): cols = {} if request_id is not None: cols['request_id'] = request_id if entity_id is not None: cols['entity_id'] = entity_id if operator_id is not None: cols['requestee_id'] = operator_id if operation is not None: cols['operation'] = int(operation) if destination_id is not None: cols['destination_id'] = int(destination_id) where = ["%s = :%s" % (x, x) for x in cols.keys()] if only_runnable: cols['now'] = DateTime.now() where.append("run_at <= :now") qry = """ SELECT request_id, requestee_id, run_at, operation, entity_id, destination_id, state_data FROM [:table schema=cerebrum name=bofhd_request] WHERE """ ret = self._db.query(qry + " AND ".join(where), cols) if given: group = Factory.get('Group')(self._db) tmp = [str(x["group_id"]) for x in group.search(member_id=operator_id, indirect_members=True)] extra_where = "" if len(tmp) > 0: extra_where = "AND destination_id IN (%s)" % ", ".join(tmp) ret.extend(self._db.query(qry + "operation=:op %s" % extra_where, {'op': int(self.co.bofh_move_give)})) return ret
def init_report(self, lab=None): self.report_id = None self.notes = '' self.completed = None self.lab_options = list(labs) self.lab_options.insert(0, choose) if lab: for name, label in labs: if name.lower() == lab.lower(): lab = name break else: lab = None if lab: self.lab = lab self.lab_readonly = True else: self.lab = self.lab_options[0][0] self.lab_readonly = False prev_week = DateTime.RelativeDateTime(weeks=-1) self.week_options = [] d = DateTime.now() + \ DateTime.RelativeDateTime(days=-4, weekday=(DateTime.Friday, 0), hour=0, minute=0, second=0) for n in range(8): self.week_options.append(d.strftime('%Y-%m-%d')) d += prev_week self.week_options.reverse() self.week = self.week_options[-1] self.__monitor = Monitor(self, *self.report_cols)
def _start_job_process(self, cr, uid, ids=None, use_new_cursor=False, context=None): if not context: context = {} maxdate = DateTime.now() if use_new_cursor: cr = pooler.get_db(use_new_cursor).cursor() wf_service = netsvc.LocalService("workflow") process_obj = self.pool.get('etl.job.process') if not ids: ids = process_obj.search(cr, uid, [('state', '=', 'open')]) for process in process_obj.browse(cr, uid, ids): if process.schedule_date: if maxdate.strftime( '%Y-%m-%d %H:%M:%S') >= process.schedule_date: wf_service.trg_validate(uid, 'etl.job.process', process.id, 'start_process', cr) if use_new_cursor: cr.commit()
def format_phone_table(co, phone_table): now = DateTime.now() lastweek = now - DateTime.TimeDelta(24 * 7) table = [] for i, entry in enumerate(sorted(phone_table)): ssys = entry['ssys'] ssys_s = '{0: <8}'.format(text_type(co.AuthoritativeSystem(ssys))) status = entry['status'] if status: status_s = '{0: <24}'.format(text_type(co.human2constant(status))) else: status_s = '{0: <24}'.format(text_type('invalid affiliation')) number = entry['number'] if number: num_s = '{0: >18}'.format(text_type(number)) mod_date = entry['date'] if mod_date and mod_date > lastweek: date_s = ' (changed {} days ago)'.format( int((now - mod_date).days)) else: date_s = ' date is OK' else: num_s = '{0: >18}'.format(None) date_s = ' None' if i == 0: k0, k1, k2, k3 = 'ssys0', 'status0', 'number0', 'date_str0' else: k0, k1, k2, k3 = 'ssysn', 'statusn', 'numbern', 'date_strn' table.append({k0: ssys_s, k1: status_s, k2: num_s, k3: date_s}) return table
def _time_to_expire(self, cr, uid, ids, field_name, arg, context={}): res = {} now = DateTime.now() date = DateTime.DateTime(now.year, now.month, now.day) for fleet in self.browse(cr, uid, ids, context): res[fleet.id] = fleet.expire_time and int((DateTime.strptime(fleet.expire_time, '%Y-%m-%d') - date).days) or False return res
def match(self, url, datetime=None): """ Return 1/0 depending on whether the Cookie matches the given url or not. datetime is used to check for expiration in case the Cookie is a temporary one. It defaults to the current date/time. """ url = URL.URL(url) if self.expires is not None: if datetime is None: datetime = DateTime.now() if self.expires < datetime: if _debug: print 'expired' return 0 if TextTools.prefix(url.path, (self.path, )) is None: if _debug: print 'path does not match' return 0 if TextTools.suffix(url.host, (self.domain, )) is None: if _debug: print 'domain does not match' return 0 return 1
def OnButtonClick(self, event): if self.radio12to24.GetValue(): self.time24.SetValue(self.time12.GetValue()) elif self.radio24to12.GetValue(): self.time12.SetValue(self.time24.GetValue()) elif self.radioWx.GetValue(): now = wx.DateTime.Now() self.time12.SetValue(now) # (demonstrates that G/SetValue returns/takes a wx.DateTime) self.time24.SetValue(self.time12.GetValue(as_wxDateTime=True)) # (demonstrates that G/SetValue returns/takes a wx.TimeSpan) self.spinless_ctrl.SetValue( self.time12.GetValue(as_wxTimeSpan=True)) elif self.radioMx.GetValue(): from mx import DateTime now = DateTime.now() self.time12.SetValue(now) # (demonstrates that G/SetValue returns/takes a DateTime) self.time24.SetValue(self.time12.GetValue(as_mxDateTime=True)) # (demonstrates that G/SetValue returns/takes a DateTimeDelta) self.spinless_ctrl.SetValue( self.time12.GetValue(as_mxDateTimeDelta=True))
def create_host(self, pid, fqdn): """ See .Gateway.GatewayClient. """ self.logger.info("Create host: %s", fqdn) self._get_project_idx(pid) try: self._get_host_idx(fqdn, pid) except Err: pass else: raise Err("Host %s exists in project %s" % (fqdn, pid)) n = {'name': fqdn, 'project': pid, 'created': DateTime.now(), 'expires': DateTime.now()+10, 'ips': [], 'frozen': None, } self._hosts.append(n) return n
def _ac_add_new_traits(ac): """Give an account new traits, as defined in procconf.NEW_ACCOUNT_TRAITS. This method should be called when creating and restoring accounts. """ for trait in getattr(procconf, 'NEW_ACCOUNT_TRAITS', ()): ac.populate_trait(code=trait, date=DateTime.now())
def timesForRange(self, start=None, end=None, grain=1): """ returns a list of times where the spec matches within the range from start to end, stepped through by grain. """ if start is None: start=M.now() + _second_zero elif isinstance(start, int): start=M.DateTimeFromTicks(start) if end is None: end=start+M.oneDay elif isinstance(end, int): end=M.DateTimeFromTicks(end) if start > end: raise ValueError, "start time %s greater than end time %s" % \ (start.asctime(), end.asctime()) if grain<1: raise ValueError, "grain must be at least one minute" incr=M.RelativeDateTime(minutes=grain) times=[] while start<=end: if self.matchTime(start): times.append(start) start=start+incr return times
def set_homedir(self, *args, **kw): """Remove quota information when the user is moved to a disk without quotas or where the default quota is larger than his existing explicit quota.""" ret = self.__super.set_homedir(*args, **kw) if kw.get('current_id') and kw.get('disk_id'): disk = Factory.get("Disk")(self._db) disk.find(kw['disk_id']) has_quota = disk.has_quota() def_quota = disk.get_default_quota() dq = DiskQuota(self._db) try: info = dq.get_quota(kw['current_id']) except Errors.NotFoundError: pass else: if not has_quota: # No quota on new disk, so remove the quota information. dq.clear(kw['current_id']) elif def_quota is None: # No default quota, so keep the quota information. pass else: if (info['override_expiration'] and DateTime.now() < info['override_expiration']): old_quota = info['override_quota'] else: old_quota = info['quota'] if old_quota <= def_quota: dq.clear(kw['current_id']) return ret
def find_candidates(exclude_aff=[], grace=0, quarantine=None): """Find persons who should be quarantined and dequarantined. :param list exclude_aff: A list of affiliations/statuses that should be ignored when finding the candidates. Persons with only affiliations from this list will be considered as not affiliated. The list contains tuples, either with affiliation or affiliation- and status-codes. :param int grace: Defines a grace period for when affiliations are still considered active, after their end period. :param None/QuarantineCode/sequence(QuarantineCode) quarantine: If not None, will filter the `quarantined` return value only to have these quarantines. :rtype: dict :return: Three elements are included in the dict: - `affiliated`: A set with person-IDs for those considered affiliatied. - `not_affiliated`: A set with person-IDs for those *not* affiliatied. - `quarantined`: A set with account-IDs for all quarantined accounts. """ datelimit = DateTime.now() - int(grace) logger.debug2("Including affiliations deleted after: %s", datelimit) def is_aff_considered(row): """Check for if an affiliation should be considered or not.""" # Exclude affiliations deleted before the datelimit: if row['deleted_date'] and row['deleted_date'] < datelimit: return False if (row['affiliation'], row['status']) in exclude_aff: return False if (row['affiliation'],) in exclude_aff: return False return True affs = filter(is_aff_considered, pe.list_affiliations(include_deleted=True)) affed = set(x['person_id'] for x in affs) logger.debug('Found %d persons with affiliations', len(affed)) naffed = set(x['person_id'] for x in pe.list_persons()) - affed logger.debug('Found %d persons without affiliations', len(naffed)) if quarantine is None: quarantined = QuarantineHandler.get_locked_entities( db, entity_types=co.entity_account) else: quarantined = set(x['entity_id'] for x in ac.list_entity_quarantines( entity_types=co.entity_account, only_active=True, quarantine_types=quarantine)) logger.debug('Found %d quarantined accounts', len(quarantined)) return {'affiliated': affed, 'not_affiliated': naffed, 'quarantined': quarantined}
def check_account(self, account): """ Check if account is OK. """ if account is None: return False if account.expire_date and account.expire_date < DateTime.now(): return False return True
def OnButtonClick( self, event ): if self.radio12to24.GetValue(): self.time24.SetValue( self.time12.GetValue() ) elif self.radio24to12.GetValue(): self.time12.SetValue( self.time24.GetValue() ) elif self.radioWx.GetValue(): now = wx.DateTime_Now() self.time12.SetValue( now ) # (demonstrates that G/SetValue returns/takes a wx.DateTime) self.time24.SetValue( self.time12.GetValue(as_wxDateTime=True) ) # (demonstrates that G/SetValue returns/takes a wx.TimeSpan) self.spinless_ctrl.SetValue( self.time12.GetValue(as_wxTimeSpan=True) ) elif self.radioMx.GetValue(): from mx import DateTime now = DateTime.now() self.time12.SetValue( now ) # (demonstrates that G/SetValue returns/takes a DateTime) self.time24.SetValue( self.time12.GetValue(as_mxDateTime=True) ) # (demonstrates that G/SetValue returns/takes a DateTimeDelta) self.spinless_ctrl.SetValue( self.time12.GetValue(as_mxDateTimeDelta=True) )
def __init__(self, db, const): self._db = db self.co = const midnight = DateTime.today() now = DateTime.now() # if we are past 22:00 this day, schedule for tomorrow evening if (now - midnight) > DateTime.TimeDeltaFrom(hours=22): self.batch_time = midnight + DateTime.TimeDeltaFrom(days=1, hours=22) # ... otherwise, schedule for this day else: self.batch_time = midnight + DateTime.TimeDeltaFrom(hours=22) self.now = now # "None" means _no_ conflicts, there can even be several of # that op pending. All other ops implicitly conflict with # themselves, so there can only be one of each op. self.conflicts = { int(const.bofh_move_user): [ const.bofh_move_student, const.bofh_move_user_now, const.bofh_move_request, const.bofh_delete_user ], int(const.bofh_move_student): [ const.bofh_move_user, const.bofh_move_user_now, const.bofh_move_request, const.bofh_delete_user ], int(const.bofh_move_user_now): [ const.bofh_move_student, const.bofh_move_user, const.bofh_move_request, const.bofh_delete_user ], int(const.bofh_move_request): [ const.bofh_move_user, const.bofh_move_user_now, const.bofh_move_student, const.bofh_delete_user ], int(const.bofh_move_give): None, int(const.bofh_archive_user): [ const.bofh_move_user, const.bofh_move_user_now, const.bofh_move_student, const.bofh_delete_user ], int(const.bofh_delete_user): [ const.bofh_move_user, const.bofh_move_user_now, const.bofh_move_student, const.bofh_email_create ], int(const.bofh_email_create): [const.bofh_email_delete, const.bofh_delete_user], int(const.bofh_email_delete): [const.bofh_email_create], int(const.bofh_email_convert): [const.bofh_email_delete], int(const.bofh_sympa_create): [const.bofh_sympa_remove], int(const.bofh_sympa_remove): [const.bofh_sympa_create], int(const.bofh_quarantine_refresh): None, int(const.bofh_email_restore): [const.bofh_email_create], int(const.bofh_homedir_restore): [ const.bofh_move_user, const.bofh_move_user_now, const.bofh_move_student, const.bofh_delete_user ] }
def filter_valid_affiliations(affiliations): """Filter out valid affiliations""" now = DateTime.now() for aff in affiliations: del_date = aff['deleted_date'] if not del_date or del_date > now: yield {'ssys': aff['source_system'], 'status': aff['status']}
def __init__(self, iter_ous, include_ou=None): """ :param iter_ous: Iterable with DataOU objects. :param include_ou: A callable that takes a DataOU object, and returns True if the ou should be included in a tree, or False if it should not. """ # Maps <sko-tuple> -> (<parent-sko-tuple>, <show-ou>) self.map = dict() now = DateTime.now() include_ou = include_ou or (lambda ou: True) for ou in iter_ous: sko, parent = ou.get_id(DataOU.NO_SKO), ou.parent if not sko: continue if ou.start_date and ou.start_date > now: continue if ou.end_date and ou.end_date < now: continue if parent is not None: parent_type, parent = parent if not parent_type == DataOU.NO_SKO: raise ValueError( "Invalid parent OU type {0!r}".format(parent)) self.map[sko] = parent, include_ou(ou)
def store_group(self, group): """Stores a group in Cerebrum.""" if self._group is None: self._group = Factory.get("Group")(self.db) self._group.clear() try: self._group.find_by_name(group.name) except Errors.NotFoundError: # No group found pass self._group.populate( creator_id=self.default_creator_id, visibility=self.co.group_visibility_all, name=group.name, description=group.desc, group_type=self.co.group_type_unknown, ) self._add_external_ids(self._group, group._ids) ret = self._group.write_db() self._process_tags(self._group, group._tags) self._group.populate_trait(self.co.trait_group_imported, date=DateTime.now()) self._group.write_db() # Add group to "seen" cache. self._groups.setdefault(group.name, []) return ret
def button_lunch(self, cr, uid, ids, context=None): att_obj = self.pool.get('hr.attendance') comp_obj = self.pool.get('res.company') company_id = comp_obj._company_default_get(cr, uid, 'hr.attendance', context=context) company = comp_obj.browse(cr, uid, company_id, context=context) if not company.lunch_duration: raise osv.except_osv(_('Error'), _("Please specify a 'Lunch Duration' in the company configuration!")) # time of sign_out is always 12:00 lunch_time = DateTime.now() + DateTime.RelativeDateTime(hour=10, minute=0, second=0) for sheet in self.browse(cr, uid, ids): vals = { 'name': lunch_time.strftime('%Y-%m-%d %H:%M:%S'), 'sheet_id': sheet.id, 'action': 'sign_out', 'flag': 'B', 'employee_id': sheet.employee_id.id, } att_obj.create(cr, uid, vals, context=context) vals['name'] = (lunch_time + DateTime.RelativeDateTime(minutes= company.lunch_duration)).strftime('%Y-%m-%d %H:%M:%S') vals['action'] = 'sign_in' att_obj.create(cr, uid, vals, context=context) return True
def _checkUserPQuota(self, userpquota): """Checks the user quota on a printer and deny or accept the job.""" # then we check the user's own quota # if we get there we are sure that policy is not EXTERNAL user = userpquota.User printer = userpquota.Printer enforcement = self.config.getPrinterEnforcement(printer.Name) self.logdebug("Checking user %s's quota on printer %s" % (user.Name, printer.Name)) (policy, dummy) = self.config.getPrinterPolicy(userpquota.Printer.Name) if not userpquota.Exists: # Unknown userquota if policy == "ALLOW": action = "POLICY_ALLOW" else: action = "POLICY_DENY" self.printInfo( _("Unable to match user %s on printer %s, applying default policy (%s)" ) % (user.Name, printer.Name, action)) else: pagecounter = int(userpquota.PageCounter or 0) if enforcement == "STRICT": pagecounter += self.softwareJobSize if userpquota.SoftLimit is not None: softlimit = int(userpquota.SoftLimit) if pagecounter < softlimit: action = "ALLOW" else: if userpquota.HardLimit is None: # only a soft limit, this is equivalent to having only a hard limit action = "DENY" else: hardlimit = int(userpquota.HardLimit) if softlimit <= pagecounter < hardlimit: now = DateTime.now() if userpquota.DateLimit is not None: datelimit = DateTime.ISO.ParseDateTime( str(userpquota.DateLimit)[:19]) else: datelimit = now + self.config.getGraceDelay( printer.Name) userpquota.setDateLimit(datelimit) if now < datelimit: action = "WARN" else: action = "DENY" else: action = "DENY" else: if userpquota.HardLimit is not None: # no soft limit, only a hard one. hardlimit = int(userpquota.HardLimit) if pagecounter < hardlimit: action = "ALLOW" else: action = "DENY" else: # Both are unset, no quota, i.e. accounting only action = "ALLOW" return action
def create_user(self, pid, username, uid, realname=None): """ See .Gateway.GatewayClient. """ self.logger.info("Creating user: %s", username) self._get_project_idx(pid) try: self._get_user_idx(username, pid) except Err: pass else: raise Err("User %s exists in project %s" % (username, pid)) n = {'username': username, 'created': DateTime.now(), 'frozen': None, 'expires': DateTime.now()+10, 'project': pid, 'groups': []} self._users.append(n) return n
def apple_biofix_process(request): try: # retrieve input if request.form: try: now = DateTime.now() if request.form['submit field'] == 'Submit': outfil = open( '/static/NEWA/apple_biofix_%s.txt' % now.year, 'w') for key in request.form.keys(): if key != 'submit field' and request.form[key] != '': outfil.write('%s, %s\n' % (key, request.form[key])) outfil.close return newaInput_io.apple_biofix_results( 'Biofix results saved.') else: return newaInput_io.apple_biofix_results( 'No changes saved.') except: print_exception() raise program_exit('Error processing form') else: return newaModel_io.errmsg('Error processing form; no form') except program_exit, msg: print msg return newaModel_io.errmsg('Error processing form')
def body(self): fontSize = 2.1*self.di.pageHeight/210.0 linex = fontSize*6 s="" versionString = self.postscriptEscape(versionNumber) dateString = self.postscriptEscape(DateTime.now() \ .strftime("Generated at: %Y-%m-%dT%H:%M:%S%Z")) urlString = "http://adelie.cx/makediary/" s = s + "% --- Version page\n" \ + "/Courier %5.3f selectfont " % fontSize \ + "%5.3f %5.3f M (%s) SH\n" % (linex, fontSize*12, versionString) \ + "%5.3f %5.3f M (%s) SH\n" % (linex, fontSize*10, dateString) \ + "%5.3f %5.3f M (%s) SH\n" % (linex, fontSize*8, urlString) liney = self.di.pageHeight*0.9 s = s + "%5.3f %5.3f M (Command:) SH\n" % (linex, liney) liney = liney - fontSize*1.25 s = s + "%5.3f %5.3f M ( %s) SH\n" % (linex, liney, self.di.myname) liney = liney - fontSize*1.25 for i in range(len(self.di.opts)): s = s + "%5.3f %5.3f M ( %s) SH\n" % (linex, liney, self.postscriptEscape(self.di.opts[i])) liney = liney - fontSize*1.25 liney = liney - fontSize*2.5 for i in range(len(self.di.usageStrings)): s = s + "%5.3f %5.3f M (%s) SH\n" % (linex, liney, self.postscriptEscape(self.di.usageStrings[i])) liney = liney - fontSize*1.25 return s
def phase_hunt(sdate=DateTime.now()): """Find time of phases of the moon which surround the current date. Five phases are found, starting and ending with the new moons which bound the current lunation. """ if not hasattr(sdate, 'jdn'): sdate = DateTime.DateTimeFromJDN(sdate) adate = sdate + DateTime.RelativeDateTime(days=-45) k1 = floor((adate.year + ((adate.month - 1) * (1.0 / 12.0)) - 1900) * 12.3685) nt1 = meanphase(adate, k1) adate = nt1 sdate = sdate.jdn while 1: adate = adate + c.synodic_month k2 = k1 + 1 nt2 = meanphase(adate, k2) if nt1 <= sdate < nt2: break nt1 = nt2 k1 = k2 phases = list(map(truephase, [k1, k1, k1, k1, k2], [0/4.0, 1/4.0, 2/4.0, 3/4.0, 0/4.0])) return phases