def create_period(self, cr, uid, ids, context={}, interval=0, name='Daily'): for p in self.browse(cr, uid, ids, context): dt = p.date_start ds = mx.DateTime.strptime(p.date_start, '%Y-%m-%d') while ds.strftime('%Y-%m-%d') < p.date_stop: de = ds + RelativeDateTime(days=interval) if name == 'Daily': new_name = de.strftime('%Y-%m-%d') if name == "Weekly": new_name = de.strftime('%Y, week %W') self.pool.get('stock.period').create( cr, uid, { 'name': new_name, 'date_start': ds.strftime('%Y-%m-%d'), 'date_stop': de.strftime('%Y-%m-%d'), }) ds = ds + RelativeDateTime(days=interval) + 1 return { 'view_type': 'form', "view_mode": 'tree', 'res_model': 'stock.period', 'type': 'ir.actions.act_window', }
def calc_tick_labels(self): """ Generate ticks & tick labels. If the density of the ticks looks like it will be too high, we start skipping ticks (tick_stride). """ assert self.n_bins assert self.bin_span tick_labels = [] ticks = [] tick_stride = int(math.ceil(self.n_bins / float(self.max_ticks))) tick = self.first if self.bin_span.days == 1: adj = 0 if tick_stride == 1: step = RelativeDateTime(days=1) elif tick_stride <= 7: step = RelativeDateTime(weeks=1, weekday=(Monday,0)) tick += step elif tick_stride <= 14: step = RelativeDateTime(weeks=2, weekday=(Monday,0)) tick += RelativeDateTime(weeks=1, weekday=(Monday,0)) else: step = RelativeDateTime(day=1, months=1) tick += step else: adj = -0.5 step = self.bin_span * tick_stride while tick < self.last: bin = (tick - self.first) / self.bin_span ticks.append(bin+adj) tick_labels.append(str(datetime.mx_parse_date(tick))) tick += step return ticks, tick_labels
def compute(self, cr, uid, id, value, date_ref=False, context=None): result = super(account_payment_term, self).compute(cr, uid, id, value, date_ref, context) term = self.browse(cr, uid, id, context) if not term.payment_days: return result # Admit space, dash and colon separators. days = term.payment_days.replace(' ', '-').replace(',', '-') days = [x.strip() for x in days.split('-') if x] if not days: return result days = [int(x) for x in days] days.sort() new_result = [] for line in result: new_date = None date = mx.DateTime.strptime(line[0], '%Y-%m-%d') for day in days: if date.day <= day: if day > date.days_in_month: day = date.days_in_month new_date = date + RelativeDateTime(day=day) break if not new_date: day = days[0] if day > date.days_in_month: day = date.days_in_month new_date = date + RelativeDateTime(day=day, months=1) new_result.append((new_date.strftime('%Y-%m-%d'), line[1])) return new_result
def create_period(self, cr, uid, ids, context={}, interval=1): for fy in self.browse(cr, uid, ids, context): dt = fy.date_start ds = mx.DateTime.strptime(fy.date_start, '%Y-%m-%d') while ds.strftime('%Y-%m-%d') < fy.date_stop: de = ds + RelativeDateTime(months=interval, days=-1) self.pool.get('account.period').create( cr, uid, { 'name': ds.strftime('%Y%m'), 'code': ds.strftime('%Y%m'), 'date_start': ds.strftime('%Y-%m-%d'), 'date_stop': de.strftime('%Y-%m-%d'), 'fiscalyear_id': fy.id, }) ds = ds + RelativeDateTime(months=interval) return True
def check_too_many_attempts(self, account): """ Checks if a user has tried to use the service too many times. Creates the trait if it doesn't exist, and increments the numval. Raises an exception when too many attempts occur in the block period. """ attempts = 0 trait = account.get_trait(self.co.trait_password_failed_attempts) block_period = now() - RelativeDateTime( seconds=cereconf.INDIVIDUATION_ATTEMPTS_BLOCK_PERIOD) if trait and trait['date'] > block_period: attempts = int(trait['numval']) logger.debug('User %r has tried %r times', account.account_name, attempts) if attempts > cereconf.INDIVIDUATION_ATTEMPTS: logger.info("User %r too many attempts, temporarily blocked", account.account_name) raise Errors.CerebrumRPCException('toomanyattempts') account.populate_trait(code=self.co.trait_password_failed_attempts, target_id=account.entity_id, date=now(), numval=attempts + 1) account.write_db() account._db.commit()
def create_from_ui(self, cr, uid, orders, context=None): order_ids = super(pos_order, self).create_from_ui(cr, uid, orders, context=context) data = orders[0]['data'] if data.has_key('coupon_redeemed') and data['coupon_redeemed']: i = 0 while (i < len(data['coupon_redeemed'])): iddd = self.pool.get('gift.voucher').search( cr, uid, [('voucher_serial_no', '=', data['coupon_redeemed'][i])]) browse_id = self.pool.get('gift.voucher').browse( cr, uid, iddd[0]) self.pool.get('gift.voucher').write(cr, uid, [int(iddd[0])], { 'in': True, }) i = i + 1 if data.has_key('coupon_name') and data['coupon_name'] == True: coup_id = data['coupon_id'] c_unique_no = data['coupon_unique_no'] i = 0 while (i < len(c_unique_no)): # _id=self.pool.get('product.product').search(cr,uid,[('id','=',coup_id[i])]) # b_id=self.pool.get('product.product').browse(cr, uid, _id[0]) # prod_tmpl_id=b_id.product_tmpl_id # coupon_id=self.pool.get('product.template').search(cr,uid,[('id','=',prod_tmpl_id.id)]) # browse_id=self.pool.get('product.template').browse(cr, uid, coupon_id[0]) # coupon = self.pool.get('product.product').browse( cr, uid, int(coup_id[i])) # coupon_name = browse_id.name; # coupon_price = browse_id.list_price # uom = browse_id.uom_id.id; # p_id = browse_id.id validity_in_days = coupon.validity order_date = mx.DateTime.strptime(str(datetime.date.today()), '%Y-%m-%d') exp_date = order_date + RelativeDateTime(days=validity_in_days) self.pool.get('gift.voucher').create( cr, uid, { 'voucher_name': coupon.name, 'qty': 1.0, 'uom': coupon.uom_id.id, 'shop_id': data['shop'], 'company_id': data['company'], 'date': order_date, 'voucher_serial_no': data['coupon_unique_no'][i], 'source': data['name'], 'out': True, 'amount': coupon.list_price, 'voucher_validity': validity_in_days, 'last_date': exp_date, 'product_id': coupon.id, }) i = i + 1 return order_ids
def fleet_id_change(self, cr, uid, ids, order_fleet_id=False, fleet_id=False, product_id=False, maintenance_start_date=False, maintenance_product_qty=False): result = {} result['value'] = {} fleet_id = order_fleet_id or fleet_id if fleet_id: fleet = self.pool.get('stock.location').browse(cr, uid, fleet_id) if fleet.expire_time and not fleet.is_expired: start_date = DateTime.strptime( fleet.expire_time, '%Y-%m-%d') + RelativeDateTime( days=fixed_days_before_month_end + 1) else: start_date = maintenance_start_date and DateTime.strptime( maintenance_start_date, '%Y-%m-%d') or DateTime.strptime( self.default_maintenance_start_date(cr, uid, {}), '%Y-%m-%d') end_date = self._get_end_date_from_start_date( cr, uid, start_date, fleet) result['value'].update({'fleet_id': fleet_id}) if product_id: product = self.pool.get('product.product').browse( cr, uid, product_id) if product.is_maintenance: maintenance_month_qty = self._get_maintenance_month_qty_from_start_end( cr, uid, start_date, end_date) result['value'].update({ 'maintenance_start_date': start_date.strftime('%Y-%m-%d') }) result['value'].update({ 'maintenance_end_date': end_date.strftime('%Y-%m-%d') }) result['value'].update( {'maintenance_month_qty': maintenance_month_qty}) result['value'].update({ 'product_uom_qty': maintenance_product_qty * maintenance_month_qty }) result['value'].update({ 'product_uos_qty': maintenance_product_qty * maintenance_month_qty }) # TODO * product_obj.uos_coeff return result
def get_phone_numbers(self, person, only_first_affiliation=True): """Return a list of the registered phone numbers for a given person. Only the defined source systems and contact types are searched for, and the person must have an active affiliation from a system before a number could be retrieved from that same system. Note that only the person affiliation with the highest priority is checked for phone numbers, as long as L{only_first_affiliation} is True. This is to separate the user types and avoid e.g. a student's phone getting changed and thus be able to get hold of the employee account for the same person. """ old_limit = now() - RelativeDateTime( days=cereconf.INDIVIDUATION_AFF_GRACE_PERIOD) pe_systems = [ int(af['source_system']) for af in person.list_affiliations(person_id=person.entity_id, include_deleted=True) if (af['deleted_date'] is None or af['deleted_date'] > old_limit) ] log.debug("Person has affiliations in the systems: %s" % pe_systems) phones = [] for systems in self._get_priorities(): sys_codes = [getattr(self.co, s) for s in systems] if not any(s in sys_codes for s in pe_systems): # person has no affiliation at this priority go to next priority continue for system, values in systems.iteritems(): types = [getattr(self.co, t) for t in values['types']] sys = getattr(self.co, system) if not types: # support empty lists, to be able to block e.g. employees # from the service continue for row in person.list_contact_info(entity_id=person.entity_id, contact_type=types, source_system=sys): phones.append({ 'number': row['contact_value'], 'system': sys, 'system_name': system, 'type': self.co.ContactInfo(row['contact_type']), }) log.debug( "Phones for person_id:%s from (%s): %s" % (person.entity_id, ','.join(s for s in systems), ','.join( '%s:%s:%s' % (p['system_name'], p['type'], p['number']) for p in phones))) if only_first_affiliation: return phones return phones
def calc_span(self): """ Find the first and last date, then round them down and up (respecively). """ assert self.dates if self.lower_dates: dates = filter(None, self.dates + self.lower_dates) else: dates = filter(None, self.dates) if not dates: raise Error('No date records found') start_of_day = RelativeDateTime(hour=0, minute=0, second=0) start_of_next_day = RelativeDateTime(days=1, hour=0, minute=0, second=0) self.first = min(dates) + start_of_day self.last = max(dates) + start_of_next_day self.span = self.last - self.first assert isinstance(self.first, DateTimeType) assert isinstance(self.last, DateTimeType)
def create_commissions_periods(self, cr, uid, ids, context={}, interval=1): for gy in self.browse(cr, uid, ids, context): ds = mx.DateTime.strptime(gy.date_start, '%Y-%m-%d') while ds.strftime('%Y-%m-%d') < gy.date_stop: de = ds + RelativeDateTime(months=interval, days=-1) if de.strftime('%Y-%m-%d') > gy.date_stop: de = mx.DateTime.strptime(gy.date_stop, '%Y-%m-%d') self.pool.get('sale.commissionsperiod').create( cr, uid, { 'name': ds.strftime('%m/%Y'), 'code': ds.strftime('%m'), 'date_start': ds.strftime('%Y-%m-%d'), 'date_stop': de.strftime('%Y-%m-%d'), 'commissionsyear_id': gy.id, }) ds = ds + RelativeDateTime(months=interval) return True
def __ending_date__(self, loan): start_date = loan.approve_date total_inst = loan.total_installment i = 366 j = 12 if j == total_inst: end_date = mx.DateTime.strptime( start_date, '%Y-%m-%d') + RelativeDateTime(days=i) else: while j < total_inst: j = j + 12 i = i + 365 end_date = mx.DateTime.strptime( start_date, '%Y-%m-%d') + RelativeDateTime(days=i) return end_date.date
def create_period_monthly(self, cr, uid, ids, context={}, interval=1): for p in self.browse(cr, uid, ids, context): dt = p.date_start ds = mx.DateTime.strptime(p.date_start, '%Y-%m-%d') while ds.strftime('%Y-%m-%d') < p.date_stop: de = ds + RelativeDateTime(months=interval, days=-1) self.pool.get('stock.period').create( cr, uid, { 'name': ds.strftime('%Y/%m'), 'date_start': ds.strftime('%Y-%m-%d'), 'date_stop': de.strftime('%Y-%m-%d'), }) ds = ds + RelativeDateTime(months=interval) return { 'view_type': 'form', "view_mode": 'tree', 'res_model': 'stock.period', 'type': 'ir.actions.act_window', }
def create_period(self, cr, uid, ids, context={}, interval=1, tp='all'): for gy in self.browse(cr, uid, ids, context): ds = mx.DateTime.strptime(gy.date_start, '%Y-%m-%d') while ds.strftime('%Y-%m-%d') < gy.date_stop: de = ds + RelativeDateTime(months=interval, days=-1) if de.strftime('%Y-%m-%d') > gy.date_stop: de = mx.DateTime.strptime(gy.date_stop, '%Y-%m-%d') self.pool.get('period.generalperiod').create( cr, uid, { 'name': ds.strftime('%m/%Y'), 'code': ds.strftime('%m/%Y'), 'date_start': ds.strftime('%Y-%m-%d'), 'date_stop': de.strftime('%Y-%m-%d'), 'generalyear_id': gy.id, 'type': tp, }) ds = ds + RelativeDateTime(months=interval) return True
def __ending_date__(self): loan_pool = pooler.get_pool(self.cr.dbname).get('account.loan') loan = loan_pool.browse(self.cr, self.uid, self.ids) start_date = loan[0].approve_date total_inst = loan[0].total_installment i = 366 j = 12 if j == total_inst: end_date = mx.DateTime.strptime( start_date, '%Y-%m-%d') + RelativeDateTime(days=i) else: while j < total_inst: j = j + 12 i = i + 365 end_date = mx.DateTime.strptime( start_date, '%Y-%m-%d') + RelativeDateTime(days=i) return end_date.date
def compute(self, cr, uid, id, value, paydays, date_ref=False, context={}): if not date_ref: date_ref = now().strftime('%Y-%m-%d') pt = self.browse(cr, uid, id, context) amount = value result = [] aux_date = mx.DateTime.strptime(date_ref, '%Y-%m-%d') # logger.notifyChannel('aux_date',netsvc.LOG_INFO, aux_date) for line in pt.line_ids: if line.value == 'fixed': amt = line.value_amount elif line.value == 'procent': amt = round(amount * line.value_amount, 2) elif line.value == 'balance': amt = amount if amt: next_date = aux_date + RelativeDateTime(days=line.days) # logger.notifyChannel('_date',netsvc.LOG_INFO, next_date) if line.condition == 'end of month': next_date += RelativeDateTime(day=-1) # Esta condición es la que se añade. Se crea una lista a partir de la cadena de 'Días de Pago' # y se ordena. Trás aplicar los días de plazo par el efecto se recorre la lista y se calcula # la fecha de vencimiento. Se ha añadido un día extra "en el mes siguiente" para vencimientos # posteriores a la última fecha. Dicho día es el primero de la lista del mes siguiente. Ejemplo: día 35 de # noviembre = 5 de Diciembre if line.condition == 'payment days' and paydays: payment_days_list = map(int, paydays.split('-')) # logger.notifyChannel('Dias de pago',netsvc.LOG_INFO, payment_days_list) payment_days_list.sort() # logger.notifyChannel('Dias de pago,2',netsvc.LOG_INFO, payment_days_list) payment_days_list.append(next_date.days_in_month + payment_days_list[0]) # logger.notifyChannel('Dias de pago 3',netsvc.LOG_INFO, payment_days_list) for pay_day in payment_days_list: if next_date <= next_date + RelativeDateTime( day=pay_day): # logger.notifyChannel('next_date1',netsvc.LOG_INFO, next_date) # logger.notifyChannel('next_date1',netsvc.LOG_INFO, pay_day) next_date = next_date + RelativeDateTime( day=pay_day) # logger.notifyChannel('next_date1',netsvc.LOG_INFO, next_date) # Se debe establecer un criterio de como actuar en el caso # de que en un mes no exista el día de pago. ¿Qué se hace # si el día de pago es el 30 y estamos en febrero?. Las # tres siguiente líneas hacen que en este caso # se tome como día de pago el último día del mes. # Si se comentan estas líneas el día de pago será el # día 1 o 2 del mes siguiente. previous_month = next_date - RelativeDateTime( months=1) while next_date.day not in payment_days_list + [ previous_month.days_in_month ]: next_date = next_date - RelativeDateTime( days=1) break result.append((next_date.strftime('%Y-%m-%d'), amt)) amount -= amt return result
def main(inargs=None): parser = argparse.ArgumentParser( description="Generate an html formatted report of accounts with" " active quarantines") parser.add_argument( '-o', '--output', metavar='FILE', type=argparse.FileType('w'), default='-', help='Output file for report, defaults to stdout') parser.add_argument( '-e', '--encoding', dest='codec', default=DEFAULT_ENCODING, type=codec_type, help="Output file encoding, defaults to %(default)s") age_arg = parser.add_mutually_exclusive_group(required=True) age_arg.add_argument( '-s', '--start_date', metavar='DATE', dest='start_date', type=ISO.ParseDate, help='Report quarantines set by date (YYYY-MM-DD)') age_arg.add_argument( '-a', '--age', metavar='DAYS', dest='start_date', type=lambda x: now() + RelativeDateTime(days=-abs(int(x))), help='Report quarantines set by age (in days)') Cerebrum.logutils.options.install_subparser(parser) args = parser.parse_args(inargs) Cerebrum.logutils.autoconf('cronjob', args) db = Factory.get('Database')() logger.info('Start of script %s', parser.prog) logger.debug("args: %r", args) quarantines = list(get_quarantine_data(db, args.start_date)) write_html_report(args.output, args.codec, quarantines, args.start_date) args.output.flush() if args.output is not sys.stdout: args.output.close() logger.info('Report written to %s', args.output.name) logger.info('Done with script %s', parser.prog)
def _get_end_date_from_start_date(self, cr, uid, start_date, sub_fleet): year = start_date.year anniversary_time = DateTime.strptime(sub_fleet.anniversary_time, '%Y-%m-%d') month = anniversary_time.month day = anniversary_time.days_in_month - fixed_days_before_month_end end = DateTime.DateTime(year, month, day, 0, 0, 0.0) delta = DateTime.RelativeDateDiff( end + RelativeDateTime(days=fixed_days_before_month_end + 1), start_date) maintenance_month_qty = delta.months + delta.years * 12 if maintenance_month_qty < min_maintenance_months: end = DateTime.DateTime(year + 1, month, day, 0, 0, 0.0) return end
def calc_bin_span(self, days): """ Given a desired bin span in days, calculate number of bins that comes closest. """ assert self.span if (days % 7) == 0: # If user asked for a bin width that is a multiple of 7 days, shift # bins to align with weeks. self.first += RelativeDateTime(weekday=(Monday,0)) self.span = self.last - self.first self.bin_span = DateTimeDelta(days) self.n_bins = int(math.ceil(self.span / self.bin_span)) if self.n_bins > self.max_bins: raise Error('Too many bins (%d, maximum is %d) - make bins bigger, or limit date range' % (self.n_bins, self.max_bins))
def check_token(self, uname, token, browser_token): """Check if token and other data from user is correct.""" try: account = self.get_account(uname) except Errors.CerebrumRPCException: # shouldn't tell what went wrong return False # Check browser_token. The given browser_token may be "" but if so # the stored browser_token must be "" as well for the test to pass. bt = account.get_trait(self.co.trait_browser_token) if not bt or bt['strval'] != self.hash_token(browser_token, uname): log.info("Incorrect browser_token %s for user %s" % (browser_token, uname)) return False # Check password token. Keep track of how many times a token is # checked to protect against brute force attack (defaults to 20). pt = account.get_trait(self.co.trait_password_token) no_checks = int(pt['numval']) if no_checks > getattr(cereconf, 'INDIVIDUATION_TOKEN_ATTEMPTS', 20): log.info("No. of token checks exceeded for user %s" % uname) raise Errors.CerebrumRPCException('toomanyattempts_check') # Check if we're within time limit time_limit = now() - RelativeDateTime( minutes=cereconf.INDIVIDUATION_TOKEN_LIFETIME) if pt['date'] < time_limit: log.debug("Password token's timelimit for user %s exceeded" % uname) raise Errors.CerebrumRPCException('timeout_check') if pt and pt['strval'] == self.hash_token(token, uname): # All is fine return True log.debug("Token %s incorrect for user %s" % (token, uname)) account.populate_trait(self.co.trait_password_token, strval=pt['strval'], date=pt['date'], numval=no_checks + 1) account.write_db() account._db.commit() return False
def get_delay(self, system, type): """Return a DateTime set to the correct delay time for numbers of the given type and from the given source system. Numbers must be older than this DateTime to be accepted. If no delay is set for the number, it returns now(), which will be true unless you change your number in the exact same time. """ delay = 0 try: types = cereconf.INDIVIDUATION_PHONE_TYPES[system]['types'] except KeyError: log.error('get_delay: Unknown system defined: %s' % system) delay = 0 else: for t in types: if int(getattr(self.co, t, 0)) == int(type): delay = int(types[t].get('delay', 0)) break return now() - RelativeDateTime(days=delay)
def get_discounts(self, cr, uid, id, base_date, context={}): """ return the list of (date,percentage) ordered by date for the payment term with the corresponding id. return [] if no cash discount are defined. base_date is the date from where the discounts are computed. """ pt = self.browse(cr, uid, id, context) if not pt.cash_discount_ids: return [] res = [] for d in pt.cash_discount_ids: res.append( ((mx.DateTime.strptime(base_date,'%Y-%m-%d') +\ RelativeDateTime(days=d.delay+1)).strftime("%Y-%m-%d"), d.discount) ) res.sort(cmp=lambda x, y: cmp(x[0], y[0])) return res
def _get_maintenance_month_qty_from_start_end(self, cr, uid, start, end): delta = DateTime.RelativeDateDiff( end + RelativeDateTime(days=fixed_days_before_month_end + 1), start) return delta.months + delta.years * 12
"dtd", "documentation", defaultFunction=date_types.DateTimeDelta) tod = common.TimeOfDayProperty("tod", "documentation", defaultFunction=date_types.TimeOfDay) from mx.DateTime import RelativeDateTime t1 = time.mktime((2003, 2, 23, 0, 0, 0, 0, 0, 0)) DATATABLE = [ # attribute, testTable, badValues ( 'tod', [ ( RelativeDateTime(hour=2, minute=3, second=0.5), [ RelativeDateTime(hour=2, minute=3, second=0.5), RelativeDateTime(months=3, days=30, hour=2, minute=3, second=0.5), u"2:3:.5", u"02:03:0.5", u"2:3:.5am", (2, 3, 0, 500), [2, 3, 0, 500], ], ), (
# this program; if not, write to the Free Software Foundation, Inc., # 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. """date manipulation helper functions""" import math try: from mx.DateTime import RelativeDateTime, strptime, Date STEP = 1 except ImportError: from warnings import warn warn("mxDateTime not found, holiday management won't be available") from datetime import timedelta STEP = timedelta(days=1) else: endOfMonth = RelativeDateTime(months=1, day=-1) FRENCH_FIXED_HOLIDAYS = { 'jour_an': '%s-01-01', 'fete_travail': '%s-05-01', 'armistice1945': '%s-05-08', 'fete_nat': '%s-07-14', 'assomption': '%s-08-15', 'toussaint': '%s-11-01', 'armistice1918': '%s-11-11', 'noel': '%s-12-25', } FRENCH_MOBILE_HOLIDAYS = { 'paques2004': '2004-04-12', 'ascension2004': '2004-05-20',
import time import locale from mx.DateTime import RelativeDateTime from mx.DateTime import now try: from mx.DateTime import strptime except ImportError: # strptime does not exist on windows. we emulate it from mx.DateTime import mktime def strptime(s, f): return mktime(time.strptime(s, f)) date_operation = { '^=w(\d+)$': lambda dt,r: dt+RelativeDateTime(day=0, month=0, weeks = int(r.group(1))), '^=d(\d+)$': lambda dt,r: dt+RelativeDateTime(day=int(r.group(1))), '^=m(\d+)$': lambda dt,r: dt+RelativeDateTime(month = int(r.group(1))), '^=y(2\d\d\d)$': lambda dt,r: dt+RelativeDateTime(year = int(r.group(1))), '^=h(\d+)$': lambda dt,r: dt+RelativeDateTime(hour = int(r.group(1))), '^=(\d+)w$': lambda dt,r: dt+RelativeDateTime(day=0, month=0, weeks = int(r.group(1))), '^=(\d+)d$': lambda dt,r: dt+RelativeDateTime(day=int(r.group(1))), '^=(\d+)m$': lambda dt,r: dt+RelativeDateTime(month = int(r.group(1))), '^=(2\d\d\d)y$': lambda dt,r: dt+RelativeDateTime(year = int(r.group(1))), '^=(\d+)h$': lambda dt,r: dt+RelativeDateTime(hour = int(r.group(1))), '^([\\+-]\d+)h$': lambda dt,r: dt+RelativeDateTime(hours = int(r.group(1))), '^([\\+-]\d+)w$': lambda dt,r: dt+RelativeDateTime(days = 7*int(r.group(1))), '^([\\+-]\d+)d$': lambda dt,r: dt+RelativeDateTime(days = int(r.group(1))), '^([\\+-]\d+)m$': lambda dt,r: dt+RelativeDateTime(months = int(r.group(1))), '^([\\+-]\d+)y$': lambda dt,r: dt+RelativeDateTime(years = int(r.group(1))), '^=$': lambda dt,r: now(),
# USA/Mexico Central # # The "default" Mexico timezone. _make_timezone(TimezoneDST, ('CT', 'Central', 'US/Central', 'USA Central', 'EEUU Central', 'EUA Central', 'us.tx', 'us.il', 'Mexico', 'M\351xico', 'Mexico Central', 'M\351xico Central', 'mx'), offset='-0600', offset_delta=DateTimeDelta(0, 0, -360), dst_offset='-0500', dst_delta=DateTimeDelta(0, 0, -300), dst_forward=RelativeDateTime(hour=2, minute=0, month=4, second=0, weekday=(6, 1)), dst_back=RelativeDateTime(hour=2, minute=0, month=10, second=0, weekday=(6, -1))) # USA Eastern _make_timezone(TimezoneDST, ('ET', 'Eastern', 'US/Eastern', 'USA Eastern', 'EEUU Este', 'EUA Leste', 'us.fl', 'us.ny'), offset='-0500', offset_delta=DateTimeDelta(0, 0, -300), dst_offset='-0400',
def beforeMonth(v): from mx.DateTime import RelativeDateTime, now etime = todayend() btime = now() - RelativeDateTime(months=v) btime = FromMxDateTime(btime) return (btime, etime)
def running_expired_dates3(self, cr, uid, *args): print "DANS RUNNING date d expiration" ref_case = pooler.get_pool(cr.dbname).get('crm.case') txt_mail="Please check your reagents:" print "DS RUNNIN",("select distinct(t.name),l.check_in,l.planified_date,i.check_in,i.intervention_date,i.user_id,l.user_id from labo_intervention i,labo_log l, labo_tool t where t.id=l.log_id and i.intervention_id = t.id ") cr.execute("select distinct(t.name),l.check_in,l.planified_date,i.check_in,i.intervention_date,i.user_id,l.user_id from labo_intervention i,labo_log l, labo_tool t where t.id=l.log_id and i.intervention_id = t.id ") #cr.execute("select distinct(t.name) from labo_intervention i,labo_log l, labo_tool t where t.id=l.log_id and i.intervention_id = t.id and (l.max_date = current_date or i.next_date = current_date) ") res=cr.fetchall() max_date= now()+ RelativeDateTime(years=+1) next_date= now()+ RelativeDateTime(years=+1) for r in res: if r[1] == 'year'or r[3] == 'year': if r[3]=='year': next_date = mx.DateTime.strptime(r[4], '%Y-%m-%d') + RelativeDateTime(years=+1) + RelativeDateTime(months=-1) else: max_date = mx.DateTime.strptime(r[2], '%Y-%m-%d') + RelativeDateTime(years=+1) + RelativeDateTime(months=-1) elif r[1]=='month_6' or r[3] == 'month_6': if r[3]=='month_6': next_date = mx.DateTime.strptime(r[4], '%Y-%m-%d') + RelativeDateTime(months=+6) + RelativeDateTime(months=-1) if r[3]=='month_6': max_date = mx.DateTime.strptime(r[2], '%Y-%m-%d') + RelativeDateTime(months=+6) + RelativeDateTime(months=-1) elif r[1]=='month_3' or r[3]=='month_3': if r[3]=='month_3': next_date = mx.DateTime.strptime(r[4], '%Y-%m-%d') + RelativeDateTime(months=+3) + RelativeDateTime(days=-14) if r[1]=='month_3': max_date = mx.DateTime.strptime(r[2], '%Y-%m-%d') + RelativeDateTime(months=+3) + RelativeDateTime(days=-14) elif r[1]=='month_2' or r[3]=='month_2': if r[3]=='month_2': next_date = mx.DateTime.strptime(r[4], '%Y-%m-%d') + RelativeDateTime(months=+2) + RelativeDateTime(days=-14) if r[1]=='month_2': max_date = mx.DateTime.strptime(r[2], '%Y-%m-%d') + RelativeDateTime(months=+2) + RelativeDateTime(days=-14) elif r[1]=='month_1' or r[3]=='month_1': if r[3]=='month_1': next_date = mx.DateTime.strptime(r[4], '%Y-%m-%d') + RelativeDateTime(months=+1) + RelativeDateTime(days=-7) if r[1]=='month_1': max_date = mx.DateTime.strptime(r[2], '%Y-%m-%d') + RelativeDateTime(months=+1) + RelativeDateTime(days=-7) elif r[1]=='weekly' or r[3]=='weekly' : if r[3]== 'weekly': next_date = mx.DateTime.strptime(r[4], '%Y-%m-%d') + RelativeDateTime(days=+7) + RelativeDateTime(days=-1) if r[1]== 'weekly': max_date = mx.DateTime.strptime(r[2], '%Y-%m-%d') + RelativeDateTime(days=+7) + RelativeDateTime(days=-1) if ( next_date.strftime('%Y-%m-%d') == now().strftime('%Y-%m-%d') or max_date.strftime('%Y-%m-%d') == now().strftime('%Y-%m-%d')): cr.execute('select distinct(current_date) from labo_intervention i,labo_tool t where t.name = %s ', (r[0],)) next_d=([x[0] for x in cr.fetchall() if x]) cr.execute('select distinct(current_date) from labo_log l,labo_tool t where t.id=l.log_id and t.name = %s ', (r[0],)) max_d=([x[0] for x in cr.fetchall() if x]) txt2="for the next intervention or calibrating"+ ",".join(([str(i) for i in next_d if i] )) section_id=pooler.get_pool(cr.dbname).get('crm.case.section').search(cr, uid,[('code', '=', 'equip'),]) # user_id=pooler.get_pool(cr.dbname).get('labo.log').search(cr,uid,[('lod' '=', '')]) user_list=[] user_list.append(r[5]) if (r[5] != r[6]): user_list.append(r[6]) user_obj=pooler.get_pool(cr.dbname).get('res.users') mail_admin='[email protected] ' if r: for i in user_list: print "iii",i partner_id= pooler.get_pool(cr.dbname).get('res.users').browse(cr, uid, [i]) new_id=ref_case.create(cr,uid,{ 'name': "Equipment to review", 'section_id':section_id[0], 'state': 'open', 'active':True, 'partner_id':partner_id[0].company_id.partner_id.id, 'description': txt_mail+ " "+ r[0] + txt2, 'user_id':i, }) cr.execute("select r.email from res_users l, res_partner_address r where r.id=l.address_id and l.id=%d "%( i)) res=cr.fetchone()[0] or "" print res address_mail=res if address_mail: tools.email_send('*****@*****.**',mail_admin ,'Checking equipments', txt2, '*****@*****.**', address_mail, tinycrm=new_id) # else: # raise osv.except_osv('Not Valid Email !', "Please set an email address to '%s' !" % (address_mail,)) txt2="" else: return False return True
output.write(""" <p class="meta">Generert: %s</p>\n</body> \n</html>\n""" % now().strftime('%Y-%m-%d kl %H:%M')) def main(): try: opts, args = getopt.getopt(sys.argv[1:], 'ho:', ['from=', 'to=', 'source_systems=', 'output=']) except getopt.GetoptError, e: print e usage(1) end_date = now() start_date = now() + RelativeDateTime(days=-7) source_systems = 'SAP,FS' output = sys.stdout for opt, val in opts: if opt in ('-h', '--help'): usage() elif opt in ('--from', ): start_date = ISO.ParseDate(val) elif opt in ('--to', ): end_date = ISO.ParseDate(val) elif opt in ('--source_systems', ): source_systems = val elif opt in ('-o', '--output'): output = open(val, 'w')
def main(inargs=None): parser = argparse.ArgumentParser(description=__doc__) dryrun_arg = parser.add_argument('-d', '--dryrun', dest='dryrun', action='store_true', default=False, help='Dry-run (do not send report email)') parser.add_argument('-s', '--start-date', dest='start_date', type=ISO.ParseDate, default=now() + RelativeDateTime(days=-1), help='Start date (YYYY-MM-DD) for events,' ' defaults to %(default)s (1 day ago)') parser.add_argument('-c', '--change-program', dest='change_program', help='Only get events for %(metavar)s') mail_to_arg = parser.add_argument( '-t', '--mail-to', dest='mail_to', metavar='ADDR', help="Send an email report to %(metavar)s") mail_from_arg = parser.add_argument('-f', '--mail-from', dest='mail_from', metavar='ADDR', help="Send reports from %(metavar)s") Cerebrum.logutils.options.install_subparser(parser) args = parser.parse_args(inargs) # Require mail_to and mail_from, or neither if bool(args.mail_from) ^ bool(args.mail_to): apply_to = mail_to_arg if args.mail_to else mail_from_arg missing = mail_from_arg if args.mail_to else mail_to_arg parser.error( argparse.ArgumentError( apply_to, "Must set {0} as well".format('/'.join( missing.option_strings)))) # Require mail_to or dryrun to be set if not any((args.mail_to, args.dryrun)): parser.error( argparse.ArgumentError( mail_to_arg, "Must set {0} if not sending mail".format( '/'.join(dryrun_arg.option_strings)))) Cerebrum.logutils.autoconf('cronjob', args) logger.info('Start of script %s', parser.prog) logger.debug("args: %r", args) db = Factory.get('Database')() new_persons = list( get_new_persons(db, args.start_date, change_program=args.change_program)) if args.change_program: subject = u'New persons from %s since %s' % (args.change_program, args.start_date.date) else: subject = u'New persons since %s' % (args.start_date.date, ) message = u'\n'.join(report_new_persons(new_persons)) if new_persons: if args.mail_to and not args.dryrun: sendmail(args.mail_to, args.mail_from, subject, message) logger.info("Sent report to %s", args.mail_to) else: print("To: {0}".format(args.mail_to)) print("From: {0}".format(args.mail_from)) print("Subject: {0}".format(subject)) print("") print(message) else: logger.info("Nothing to report") logger.info('Done with script %s', parser.prog)