def button_dummy(self, cr, uid, ids, context): for sheet in self.browse(cr, uid, ids, context): if DateTime.strptime(sheet.date_current, "%Y-%m-%d") <= DateTime.strptime(sheet.date_from, "%Y-%m-%d"): self.write(cr, uid, [sheet.id], {"date_current": sheet.date_from}) elif DateTime.strptime(sheet.date_current, "%Y-%m-%d") >= DateTime.strptime(sheet.date_to, "%Y-%m-%d"): self.write(cr, uid, [sheet.id], {"date_current": sheet.date_to}) return True
def _dateConvertFromDB(d): if d==None: return None for format in ('%Y-%m-%d', # Y/M/D '%H:%M:%S', # hh:mm:ss '%H:%M', # hh:mm '%Y-%m'): # Y-M try: return DateTime.strptime(d, format) except: pass dashind = max(d.rfind('-'), d.rfind('+')) tz = d[dashind:] d = d[:dashind] #maybe it has a miliseconds ? dotind = string.rfind(d, '.') if dotind > 0: d = d[:dotind] try: return DateTime.strptime(d, '%H:%M:%S'), tz # timetz except: pass if 1:#try: # why is tz returned above and not here? return DateTime.strptime(d, '%Y-%m-%d %H:%M:%S') # full date
def get_internal_seniority(self,cr,uid,ids,*args): start_date = datetime.date.today() end_date = datetime.date.today() # if the last contract has no en date, en date = today internal_seniority = 0.0 internal_year_seniority = 0.0 internal_month_seniority = 0.0 # Get contracts for employee contract_pool = self.pool.get('hr.contract') contract_ids = contract_pool.search(cr,uid,[('employee_id','=',ids[0])],order='date_start desc') # contracts from today to first based on start date contracts = contract_pool.browse(cr, uid, contract_ids) # Get seniority for each contract for contract in contracts: seniority_rate = 1 # default seniority start_date = DateTime.strptime(contract.date_start,'%Y-%m-%d') if contract.seniority_rate: seniority_rate = contract.seniority_rate if contract.date_end: end_date = DateTime.strptime(contract.date_end,'%Y-%m-%d') internal_year_seniority += (end_date.year - start_date.year)*seniority_rate*1.0 # *1.0 to get a float internal_month_seniority += (end_date.month - start_date.month + 1)*seniority_rate*1.0 # +1 : a started month is counted as a full month end_date = start_date # if previous contract (in time scale) has no end date, its supposed end date is the current contract start date # set seniority in years internal_seniority = internal_year_seniority + internal_month_seniority/12 + internal_month_seniority//12 # Update internal seniority field self.write(cr,uid,ids,{'internal_seniority':internal_seniority}) return True
def get_sales_lines(self,cr,uid,ids,contaxt=None): product_obj=self.pool.get('product.product') invoice_line=self.pool.get('account.invoice.line') invoice_obj=self.pool.get('account.invoice') for sl in self.browse(cr, uid, ids): prods = [] date_fin=DateTime.strptime(sl.date_fin, '%Y-%m-%d') date_debut=DateTime.strptime(sl.date_debut, '%Y-%m-%d') for p in sl.product_id: prods.append(p.id) prods=tuple(prods) invoice_ids=invoice_obj.search(cr,uid,[('date_invoice','>=',date_debut),('date_invoice','<=',date_fin),('type','in',['out_invoice','out_refund'])]) invoice_lines=invoice_line.search(cr,uid,[('invoice_id','in',invoice_ids),('product_id','in',prods)]) invoice_lines=invoice_line.browse(cr,uid,invoice_lines) stock_line_obj=self.pool.get('product.line') for line in invoice_lines: prod=product_obj.browse(cr, uid, line.product_id.id) val = { 'date':line.invoice_id.date_invoice, 'quantite':line.quantity, 'name' : line.product_id.id, 'sale_price':line.price_unit, 'amount':line.price_subtotal, 'cost':line.product_id.standard_price*line.quantity, 'cost_unit':line.product_id.standard_price, 'virtual_quantity':prod.virtual_available, 'pub_id':sl.id } # print self stock_line_obj.create(cr,uid,val) return True
def _get_records(self, cr, uid, data, context={}): inv_obj = pooler.get_pool(cr.dbname).get('account.invoice') shop_obj = pooler.get_pool(cr.dbname).get('sale.shop') ids = [] if data['form']['draft']==True: states = ['draft','open','paid'] else: states = ['open','paid'] title = _("Statistiques Article - ") if data['form']['period'] == 'm': if int(data['form']['month']) < 10: title += "0" title += data['form']['month'] + "/" + data['form']['year'] day_min = datetime.date(int(data['form']['year']), int(data['form']['month']), 1) nextmonth = int(data['form']['month']) + 1 year = int(data['form']['year']) if nextmonth == 13: nextmonth = 1 year += 1 day_max = datetime.date(year, nextmonth, 1) - datetime.timedelta(days=1) elif data['form']['period'] == 's': day_min = DateTime.strptime(data['form']['date_from'], '%Y-%m-%d') day_max = DateTime.strptime(data['form']['date_to'], '%Y-%m-%d') title += _("De ") + day_min.strftime('%d/%m/%Y') + _(" A ") + day_max.strftime('%d/%m/%Y') else: day_min = datetime.date(int(data['form']['year']), 1, 1) day_max = datetime.date(int(data['form']['year']), 12, 31) title += data['form']['year'] inv_ids = inv_obj.search(cr,uid,[ ('date_invoice','>=',day_min.strftime('%Y-%m-%d')), ('date_invoice','<=',day_max.strftime('%Y-%m-%d')), ('type','in',['out_invoice','out_refund','sale_refund']), ('state','in',states), ]) ids = [] # print inv_ids shop_id=data['form']['shop_id'] if shop_id: title += _(" - Souche ") + shop_obj.browse(cr,uid,shop_id).name if inv_ids: lines=inv_obj.browse(cr,uid,inv_ids) for x in lines: for inv_line in x.invoice_line: # print inv_line.product_id.name # put other tests here if you want to filter lines if (inv_line.price_subtotal <> 0.0): if shop_id: if inv_line.invoice_id.user_id.shop.id==shop_id: # if inv_line.price_subtotal==119675000: # print inv_line.id,inv_line.price_subtotal ids.append(inv_line.id) else: ids.append(inv_line.id) return {'ids' : ids , 'title' : title, 'period' : data['form']['period'], 'detail' : not data['form']['hideproducts'], 'year':data['form']['year']}
def _get_records(self, cr, uid, data, context={}): inv_obj = pooler.get_pool(cr.dbname).get('account.invoice') partner_id = data['form']['partner_id'] ids = [] if data['form']['draft'] == True: states = ['draft', 'open', 'paid'] else: states = ['open', 'paid'] title = _("Statistique Clients - ") if data['form']['period'] == 'm': if int(data['form']['month']) < 10: title += "0" title += data['form']['month'] + "/" + data['form']['year'] day_min = datetime.date(int(data['form']['year']), int(data['form']['month']), 1) nextmonth = int(data['form']['month']) + 1 year = int(data['form']['year']) if nextmonth == 13: nextmonth = 1 year += 1 day_max = datetime.date(year, nextmonth, 1) - datetime.timedelta(days=1) elif data['form']['period'] == 's': day_min = DateTime.strptime(data['form']['date_from'], '%Y-%m-%d') day_max = DateTime.strptime(data['form']['date_to'], '%Y-%m-%d') title += _("De ") + day_min.strftime('%d/%m/%Y') + _( " A ") + day_max.strftime('%d/%m/%Y') else: day_min = datetime.date(int(data['form']['year']), 1, 1) day_max = datetime.date(int(data['form']['year']), 12, 31) title += data['form']['year'] print states inv_ids = inv_obj.search(cr, uid, [ ('date_invoice', '>=', day_min.strftime('%Y-%m-%d')), ('date_invoice', '<=', day_max.strftime('%Y-%m-%d')), ('type', 'in', ['out_invoice', 'out_refund', 'sale_refund']), ('state', 'in', states), ]) ids = [] if inv_ids: lines = inv_obj.browse(cr, uid, inv_ids) for x in lines: for inv_line in x.invoice_line: if (inv_line.price_subtotal <> 0.0): if partner_id: if inv_line.partner_id.id == partner_id: ids.append(inv_line.id) else: ids.append(inv_line.id) return { 'ids': ids, 'title': title, 'period': data['form']['period'], 'year': data['form']['year'] }
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 _get_records(self, cr, uid, data, context={}): inv_obj = pooler.get_pool(cr.dbname).get('account.invoice.line') ids = [] states = ['posted','valid'] title = _("Impayes clients - ") ids = [] # print inv_ids partner_id=data['form']['partner_id'] moveline_obj = pooler.get_pool(cr.dbname).get('account.invoice.line') #conditions de date if data['form']['invoice_date']=='': invoice_date= DateTime.strptime(data['form']['invoice_date'], '%Y-%m-%d') else: invoice_date=date.today().strftime('%Y-%m-%d') print 'invoice_date',invoice_date if data['form']['maturity_date']=='': maturity_date= DateTime.strptime(data['form']['maturity_date'], '%Y-%m-%d') else: maturity_date=date.today().strftime('%Y-%m-%d') print 'maturity date',maturity_date # print partners if data['form']['partner_id']: movelines = moveline_obj.search(cr, uid, [('partner_id', '=', partner_id), ]) elif data['form']['code']: partners=pooler.get_pool(cr.dbname).get('res.partner').search(cr,uid,[('ref','like','%'+data['form']['code']+'%')]) movelines = moveline_obj.search(cr, uid, [('partner_id', 'in', partners), ]) else: movelines = moveline_obj.search(cr, uid, [#('partner_id', '=', partner.id), ]) movelines = moveline_obj.browse(cr, uid, movelines) if movelines: lines=movelines for x in lines: # for inv_line in x.move_line_id: # print inv_line.product_id.name # put other tests here if you want to filter lines ids.append(x.id) # print ids title+=_(" ") if data['form']['detail']==0: detail=False else: detail=True return {'ids' : ids , 'title' : title, 'period' : data['form']['period'], 'detail' : detail, 'year':data['form']['year']}
def calcular_edad(date_start, format=1, date_end="now"): try: if date_end == "now": date_end = DateTime.now() else: date_end = DateTime.strptime(date_end, '%Y-%m-%d') dob = DateTime.strptime(date_start, '%Y-%m-%d') delta = DateTime.Age (date_end, dob) if format == 1: return str(delta.years) elif format == 2: return str(delta.years) + " A/" + str(delta.months) + " M" elif format == 3: return str(delta.years) + " A/" + str(delta.months) + " M/" + str(delta.days) + " D " elif format == 4: str_year = "" if delta.years < 1: str_year = u"" elif delta.years == 1: str_year = u"%s %s" % (str(delta.years), u'año') if delta.months > 0: str_year = str_year + ',' else: str_year = u"%s %s" % (str(delta.years), u'años') if delta.months > 0: str_year = str_year + ',' str_month = "" if delta.months < 1: str_month = "" else: if delta.months == 1: str_month = u"%s %s" % (str(delta.months), u'mes') else: str_month = u"%s %s" % (str(delta.months), u'meses') str_day = "" if (delta.days < 1 and delta.months > 0) or (delta.days < 1 and delta.years > 0): str_day = "" else: if delta.days == 1: str_day = u"%s %s" % (str(delta.days), u'día') else: str_day = u"%s %s" % (str(delta.days), u'días') if delta.months > 0 or delta.years > 0: str_day = 'y ' + str_day res = "%s %s %s" % (str_year, str_month, str_day) return res.strip() except: return "0"
def _get_records(self, cr, uid, data, context={}): inv_obj = pooler.get_pool(cr.dbname).get('account.invoice') partner_id=data['form']['partner_id'] ids = [] if data['form']['draft']==True: states = ['draft','open','paid'] else: states = ['open','paid'] title = _("Statistique Clients - ") if data['form']['period'] == 'm': if int(data['form']['month']) < 10: title += "0" title += data['form']['month'] + "/" + data['form']['year'] day_min = datetime.date(int(data['form']['year']), int(data['form']['month']), 1) nextmonth = int(data['form']['month']) + 1 year = int(data['form']['year']) if nextmonth == 13: nextmonth = 1 year += 1 day_max = datetime.date(year, nextmonth, 1) - datetime.timedelta(days=1) elif data['form']['period'] == 's': day_min = DateTime.strptime(data['form']['date_from'], '%Y-%m-%d') day_max = DateTime.strptime(data['form']['date_to'], '%Y-%m-%d') title += _("De ") + day_min.strftime('%d/%m/%Y') + _(" A ") + day_max.strftime('%d/%m/%Y') else: day_min = datetime.date(int(data['form']['year']), 1, 1) day_max = datetime.date(int(data['form']['year']), 12, 31) title += data['form']['year'] print states inv_ids = inv_obj.search(cr,uid,[ ('date_invoice','>=',day_min.strftime('%Y-%m-%d')), ('date_invoice','<=',day_max.strftime('%Y-%m-%d')), ('type','in',['out_invoice','out_refund','sale_refund']), ('state','in',states), ]) ids = [] if inv_ids: lines=inv_obj.browse(cr,uid,inv_ids) for x in lines: for inv_line in x.invoice_line: if (inv_line.price_subtotal <> 0.0): if partner_id: if inv_line.partner_id.id==partner_id: ids.append(inv_line.id) else: ids.append(inv_line.id) return {'ids' : ids , 'title' : title, 'period' : data['form']['period'], 'year':data['form']['year']}
def date_next(self, cr, uid, ids, context): for sheet in self.browse(cr, uid, ids, context): if DateTime.strptime(sheet.date_current, "%Y-%m-%d") >= 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": ( DateTime.strptime(sheet.date_current, "%Y-%m-%d") + DateTime.RelativeDateTime(days=1) ).strftime("%Y-%m-%d") }, ) return True
def __xform_8433(self, result_data): self.__request['sampled_when'] = mxDT.strptime( result_data['8433'][0], '%H%M', self.__request['sampled_when'] ) self.__request.save_payload()
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 burndown_chart(cr, uid, tasks_id, date_start, date_stop): latest = False cr.execute('select id,date_start,state,planned_hours from project_task where id in %s order by date_start', (tuple(tasks_id),)) tasks = cr.fetchall() cr.execute('select id,date_close,state,planned_hours*progress/100 from project_task where id in %s and state in (%s,%s) order by date_close', (tuple(tasks_id), 'progress','done')) tasks2 = cr.fetchall() current_date = date_start total = 0 done = 0 result = [] while current_date<=date_stop: while len(tasks) and tasks[0][1] and tasks[0][1][:10]<=current_date: total += tasks.pop(0)[3] while len(tasks2) and tasks2[0][1] and tasks2[0][1][:10]<=current_date: t2 = tasks2.pop(0) if t2[2]<>'cancel': done += t2[3] else: total -= t2[3] result.append( (int(time.mktime(time.strptime(current_date,'%Y-%m-%d'))), total-done) ) current_date = (DateTime.strptime(current_date, '%Y-%m-%d') + DateTime.RelativeDateTime(days=1)).strftime('%Y-%m-%d') if not len(tasks) and not len(tasks2): break result.append( (int(time.mktime(time.strptime(date_stop,'%Y-%m-%d'))), 0) ) return result
def Ymd(date=None): if date is None: return DateTime.today() elif type(date) in (str, unicode): return DateTime.strptime(date, '%Y-%m-%d') elif type(date) in (type(DateTime.today()), datetime.datetime): return date.strftime('%Y-%m-%d')
def create_chained_picking(self, cr, uid, moves, context): new_moves = [] for picking, todo in self._chain_compute(cr, uid, moves, context).items(): ptype = self.pool.get('stock.location').picking_type_get(cr, uid, todo[0][0].location_dest_id, todo[0][1][0]) pickid = self.pool.get('stock.picking').create(cr, uid, { 'name': picking.name, 'origin': str(picking.origin or ''), 'type': ptype, 'note': picking.note, 'move_type': picking.move_type, 'auto_picking': todo[0][1][1] == 'auto', 'address_id': picking.address_id.id, 'invoice_state': 'none' }) for move, (loc, auto, delay) in todo: # Is it smart to copy ? May be it's better to recreate ? new_id = self.pool.get('stock.move').copy(cr, uid, move.id, { 'location_id': move.location_dest_id.id, 'location_dest_id': loc.id, 'date_moved': time.strftime('%Y-%m-%d'), 'picking_id': pickid, 'state': 'waiting', 'move_history_ids': [], 'date_planned': (DateTime.strptime(move.date_planned, '%Y-%m-%d %H:%M:%S') + DateTime.RelativeDateTime(days=delay or 0)).strftime('%Y-%m-%d'), 'move_history_ids2': []} ) self.pool.get('stock.move').write(cr, uid, [move.id], { 'move_dest_id': new_id, 'move_history_ids': [(4, new_id)] }) new_moves.append(self.browse(cr, uid, [new_id])[0]) wf_service = netsvc.LocalService("workflow") wf_service.trg_validate(uid, 'stock.picking', pickid, 'button_confirm', cr) if new_moves: create_chained_picking(self, cr, uid, new_moves, context)
def process_data(field, value, fields_def): if not value or field not in fields_def: return if '.' not in field: # type datetime, date, bool, int, float if fields_def[field]['type'] == 'boolean': value = value.lower() not in ('0', 'false', 'off','-', 'no', 'n') elif fields_def[field]['type'] == 'selection': if impobj == 'product.product' and self._cache[dbname].get('product.product.%s.%s' % (field, value), False): value = self._cache[dbname]['product.product.%s.%s' % (field, value)] else: for key, val in fields_def[field]['selection']: if value.lower() in [tools.ustr(key).lower(), tools.ustr(val).lower()]: value = key if impobj == 'product.product': self._cache[dbname].setdefault('product.product.%s' % field, {}) self._cache[dbname]['product.product.%s.%s' % (field, value)] = key break elif fields_def[field]['type'] == 'date': dt = DateTime.strptime(value,"%d/%m/%Y") value = dt.strftime("%Y-%m-%d") elif fields_def[field]['type'] == 'float': # remove space and unbreakable space value = re.sub('[ ]+', '', value) value = float(value.replace(',', '.')) return value else: if fields_def[field.split('.')[0]]['type'] in 'many2one': return _get_obj(field, value, fields_def) raise osv.except_osv(_('Warning !'), _('%s does not exist')%(value,))
def action_produce_assign_product(self, cr, uid, ids, context={}): produce_id = False company = self.pool.get('res.users').browse(cr, uid, uid, context).company_id for procurement in self.browse(cr, uid, ids): res_id = procurement.move_id.id loc_id = procurement.location_id.id newdate = DateTime.strptime(procurement.date_planned, '%Y-%m-%d %H:%M:%S') - DateTime.RelativeDateTime(days=procurement.product_id.product_tmpl_id.produce_delay or 0.0) newdate = newdate - DateTime.RelativeDateTime(days=company.manufacturing_lead) produce_id = self.pool.get('mrp.production').create(cr, uid, { 'origin': procurement.origin, 'product_id': procurement.product_id.id, 'product_qty': procurement.product_qty, 'product_uom': procurement.product_uom.id, 'product_uos_qty': procurement.product_uos and procurement.product_uos_qty or False, 'product_uos': procurement.product_uos and procurement.product_uos.id or False, 'location_src_id': procurement.location_id.id, 'location_dest_id': procurement.location_id.id, 'bom_id': procurement.bom_id and procurement.bom_id.id or False, 'date_planned': newdate.strftime('%Y-%m-%d %H:%M:%S'), 'move_prod_id': res_id, 'product_line_origin' : procurement.product_line_origin and procurement.product_line_origin.id or False, }) self.write(cr, uid, [procurement.id], {'state':'running'}) bom_result = self.pool.get('mrp.production').action_compute(cr, uid, [produce_id], properties=[x.id for x in procurement.property_ids]) # wf_service = netsvc.LocalService("workflow") # wf_service.trg_validate(uid, 'mrp.production', produce_id, 'button_confirm', cr) self.pool.get('stock.move').write(cr, uid, [res_id], {'location_id':procurement.location_id.id}) return produce_id
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 get_date(self, payment, line): """Return the right OPAE Line date""" if not line : return unicode(DateTime.today().strftime("%y%m%d")) to_return = DateTime.today() if payment.date_prefered == 'due' and line.ml_maturity_date : to_return = DateTime.strptime(line.ml_maturity_date, '%Y-%m-%d') if payment.date_prefered == 'fixed' and payment.date_planned : to_return = DateTime.strptime(payment.date_planned, '%Y-%M-%d') if to_return < DateTime.today(): raise wizard.except_wizard( _('Error'), _('Payment date must be at least today\n \ Today used instead.') ) return unicode(to_return.strftime("%y%m%d"))
def __xform_8302(self, request_data): """8302: Berichtsdatum""" if self.__request['results_reported_when'] is None: self.__request['results_reported_when'] = mxDT.now() self.__request['results_reported_when'] = mxDT.strptime( request_data['8302'][0].strip(), '%d%m%Y', self.__request['results_reported_when']) return None
def check_date(option, opt, value): """check a file value return the filepath """ try: return DateTime.strptime(value, "%Y/%m/%d") except DateTime.Error: raise OptionValueError("expected format of %s is yyyy/mm/dd" % opt)
def _project_compute(cr, uid, project_id): project = pooler.get_pool(cr.dbname).get('project.project').browse(cr, uid, project_id) if project.date_start: date_begin = DateTime.strptime(project.date_start, '%Y-%m-%d') else: date_begin = DateTime.now() tasks, last_date = _compute_project(cr, uid, project, date_begin) return tasks, last_date
def _get_qty(self, item): product = item.product_id.id start = DateTime.strptime(item.price_version_id.date_start, "%Y-%m-%d") end = DateTime.strptime(item.price_version_id.date_end, "%Y-%m-%d") qty = self.pool.get("sale.report").search( self.cr, self.uid, [("product_id", "=", product), ("date", ">=", start.date), ("date", "<=", end.date)] ) if qty == []: return {"quantity": 0, "value": 0} else: quantity = 0 value = 0 datas = self.pool.get("sale.report").read(self.cr, self.uid, qty, ["product_uom_qty", "price_total"]) for data in datas: quantity += data["product_uom_qty"] value += data["price_total"] * data["product_uom_qty"] return {"quantity": quantity, "value": value}
def __xform_8303(self, request_data): """8303: Berichtszeit""" if self.__request['results_reported_when'] is None: self.__request['results_reported_when'] = mxDT.now() self.__request['results_reported_when'] = mxDT.strptime( request_data['8303'][0].strip(), '%H%M', self.__request['results_reported_when']) return None
def _current_employee_age(self,cr,uid,ids,field_name,arg,context): res = {} today = datetime.date.today() dob = today for employee in self.browse(cr, uid, ids): if employee.birthday: dob = DateTime.strptime(employee.birthday,'%Y-%m-%d') res[employee.id] = today.year - dob.year return res
def intrinsic_anniversary_time_change(self, cr, uid, ids, anniversary_time=False): result = {} if anniversary_time: anniversary_time = DateTime.strptime(anniversary_time, '%Y-%m-%d') if anniversary_time.day != fixed_month_init_day: anniversary_time = DateTime.DateTime(anniversary_time.year, anniversary_time.month, fixed_month_init_day) result['value'] = {'intrinsic_anniversary_time': anniversary_time.strftime('%Y-%m-%d')} result['warning'] = {'title':'Incorrect Anniversary Time', 'message':"- Anniversary date should should ideally start at day %s of the month; corrected to day %s\n" % (fixed_month_init_day, fixed_month_init_day)} return result
def _get_records(self, cr, uid, data, context={}): inv_obj = pooler.get_pool(cr.dbname).get('account.invoice') ids = [] if data['form']['draft'] == True: states = ['draft', 'open', 'paid'] else: states = ['open', 'paid'] title = _("Revenue per customer - ") if data['form']['period'] == 'm': if int(data['form']['month']) < 10: title += "0" title += data['form']['month'] + "/" + data['form']['year'] day_min = datetime.date(int(data['form']['year']), int(data['form']['month']), 1) nextmonth = int(data['form']['month']) + 1 year = int(data['form']['year']) if nextmonth == 13: nextmonth = 1 year += 1 day_max = datetime.date(year, nextmonth, 1) - datetime.timedelta(days=1) elif data['form']['period'] == 's': day_min = DateTime.strptime(data['form']['date_from'], '%Y-%m-%d') day_max = DateTime.strptime(data['form']['date_to'], '%Y-%m-%d') title += _("From ") + day_min.strftime('%d/%m/%Y') + _( " to ") + day_max.strftime('%d/%m/%Y') else: day_min = datetime.date(int(data['form']['year']), 1, 1) day_max = datetime.date(int(data['form']['year']), 12, 31) title += data['form']['year'] inv_ids = inv_obj.search(cr, uid, [ ('date_invoice', '>=', day_min.strftime('%Y-%m-%d')), ('date_invoice', '<=', day_max.strftime('%Y-%m-%d')), ('type', 'in', ['out_invoice', 'out_refund']), ('state', 'in', states), ]) return { 'ids': inv_ids, 'title': title, 'period': data['form']['period'], 'year': data['form']['year'] }
def _get_records(self, cr, uid, data, context={}): inv_obj = pooler.get_pool(cr.dbname).get('account.voucher') ids = [] states = ['posted'] title = _("Journal de Caisse - ") if data['form']['period'] == 'm': if int(data['form']['month']) < 10: title += "0" title += data['form']['month'] + "/" + data['form']['year'] day_min = datetime.date(int(data['form']['year']), int(data['form']['month']), 1) nextmonth = int(data['form']['month']) + 1 year = int(data['form']['year']) if nextmonth == 13: nextmonth = 1 year += 1 day_max = datetime.date(year, nextmonth, 1) - datetime.timedelta(days=1) elif data['form']['period'] == 's': day_min = DateTime.strptime(data['form']['date_from'], '%Y-%m-%d') day_max = DateTime.strptime(data['form']['date_to'], '%Y-%m-%d') title += _("De ") + day_min.strftime('%d/%m/%Y') + _(" A ") + day_max.strftime('%d/%m/%Y') else: day_min = datetime.date(int(data['form']['year']), 1, 1) day_max = datetime.date(int(data['form']['year']), 12, 31) title += data['form']['year'] print inv_obj inv_ids = inv_obj.search(cr,uid,[ ('date','=','2012-03-30'), ('state','=','posted'), ]) ids = [] print inv_ids # print inv_ids if inv_ids: lines=inv_obj.browse(cr,uid,inv_ids) for x in lines: # for inv_line in x.invoice_line: # print inv_line.product_id.name # put other tests here if you want to filter lines ids.append(x.id) title+=_(" ") print title return {'ids' : ids , 'title' : title, 'period' : data['form']['period'],'detail':True, 'year':data['form']['year']}
def create_xml(self, cr, uid, ids, datas, context): service = netsvc.LocalService('object_proxy') month = DateTime.DateTime(datas['form']['year'], datas['form']['month'], 1) user_xml = ['<month>%s</month>' % month2name[month.month], '<year>%s</year>' % month.year] for employee_id in ids: emp = service.execute(cr.dbname, uid, 'hr.employee', 'read', [employee_id])[0] stop, days_xml = False, [] user_repr = ''' <user> <name>%s</name> %%s </user> ''' % (toxml(emp['name'])) today, tomor = month, month + one_day while today.month == month.month: #### Work hour calculation sql = ''' select action, att.name from hr_employee as emp inner join hr_attendance as att on emp.id = att.employee_id where att.name between %s and %s and emp.id = %s order by att.name ''' cr.execute(sql, (today.strftime('%Y-%m-%d %H:%M:%S'), tomor.strftime('%Y-%m-%d %H:%M:%S'), employee_id)) attendences = cr.dictfetchall() wh = 0 # Fake sign ins/outs at week ends, to take attendances across week ends into account if attendences and attendences[0]['action'] == 'sign_out': attendences.insert(0, {'name': today.strftime('%Y-%m-%d %H:%M:%S'), 'action':'sign_in'}) if attendences and attendences[-1]['action'] == 'sign_in': attendences.append({'name' : tomor.strftime('%Y-%m-%d %H:%M:%S'), 'action':'sign_out'}) # sum up the attendances' durations for att in attendences: dt = DateTime.strptime(att['name'], '%Y-%m-%d %H:%M:%S') if att['action'] == 'sign_out': wh += (dt - ldt).hours ldt = dt # Week xml representation wh = hour2str(wh) today_xml = '<day num="%s"><wh>%s</wh></day>' % ((today - month).days+1, wh) days_xml.append(today_xml) today, tomor = tomor, tomor + one_day user_xml.append(user_repr % '\n'.join(days_xml)) xml = '''<?xml version="1.0" encoding="UTF-8" ?> <report> %s </report> ''' % '\n'.join(user_xml) return xml
def _is_expired(self, cr, uid, ids, field_name, arg, context={}): res = {} now = DateTime.now() date = DateTime.DateTime(now.year, now.month, now.day, 0, 0, 0.0) for fleet in self.browse(cr, uid, ids, context): if fleet.expire_time: res[fleet.id] = date > DateTime.strptime(fleet.expire_time, '%Y-%m-%d') else: res[fleet.id] = True #by default no maintenance expire terms means no coverage return res
def _compute_project(cr, uid, project, date_begin): tasks, last_date = _compute_tasks(cr, uid, project.tasks, date_begin) for proj in project.child_id: d0 = DateTime.strptime(proj.date_start,'%Y-%m-%d') if d0 > last_date: last_date = d0 t2, l2 = _compute_project(cr, uid, proj, last_date) tasks.update(t2) last_date = l2 return tasks, last_date
def compute_age_from_dates (date_birth): now=DateTime.now() if (date_birth): dob=DateTime.strptime(date_birth,'%Y-%m-%d') delta=DateTime.Age (now, dob) deceased='' years_months_days = str(delta.years) +"a "+ str(delta.months) +"m "+ str(delta.days)+"j" + deceased else: years_months_days = "No DoB !" return years_months_days
def _get_qty(self, item): product = item.product_id.id start = DateTime.strptime(item.price_version_id.date_start, '%Y-%m-%d') end = DateTime.strptime(item.price_version_id.date_end, '%Y-%m-%d') qty = self.pool.get('sale.report').search( self.cr, self.uid, [('product_id', '=', product), ('date', '>=', start.date), ('date', '<=', end.date)]) if qty == []: return {'quantity': 0, 'value': 0} else: quantity = 0 value = 0 datas = self.pool.get('sale.report').read( self.cr, self.uid, qty, ['product_uom_qty', 'price_total']) for data in datas: quantity += data['product_uom_qty'] value += data['price_total'] * data['product_uom_qty'] return {'quantity': quantity, 'value': value}
def _timeConvertFromDB(t): if t==None: return None for format in ('%H:%M:%S', '%H:%M'): try: return DateTime.strptime(t, format) except: pass raise DateTime.Error, "could not parse time: %s" % t
def __xform_8303(self, request_data): """8303: Berichtszeit""" if self.__request['results_reported_when'] is None: self.__request['results_reported_when'] = mxDT.now() self.__request['results_reported_when'] = mxDT.strptime( request_data['8303'][0].strip(), '%H%M', self.__request['results_reported_when'] ) return None
def _get_records(self, cr, uid, data, context={}): inv_obj = pooler.get_pool(cr.dbname).get('account.voucher') ids = [] states = ['posted'] title = _("Journal de Caisse - ") if data['form']['period'] == 'm': if int(data['form']['month']) < 10: title += "0" title += data['form']['month'] + "/" + data['form']['year'] day_min = datetime.date(int(data['form']['year']), int(data['form']['month']), 1) nextmonth = int(data['form']['month']) + 1 year = int(data['form']['year']) if nextmonth == 13: nextmonth = 1 year += 1 day_max = datetime.date(year, nextmonth, 1) - datetime.timedelta(days=1) elif data['form']['period'] == 's': day_min = DateTime.strptime(data['form']['date_from'], '%Y-%m-%d') day_max = DateTime.strptime(data['form']['date_to'], '%Y-%m-%d') title += _("De ") + day_min.strftime('%d/%m/%Y') + _(" A ") + day_max.strftime('%d/%m/%Y') else: day_min = datetime.date(int(data['form']['year']), 1, 1) day_max = datetime.date(int(data['form']['year']), 12, 31) title += data['form']['year'] inv_ids = inv_obj.search(cr,uid,[ ('date','<=',day_max.strftime('%Y-%m-%d')), ('state','in',states), ]) ids = [] # print inv_ids if inv_ids: lines=inv_obj.browse(cr,uid,inv_ids) for x in lines: for inv_line in x.invoice_line: # print inv_line.product_id.name # put other tests here if you want to filter lines ids.append(inv_line.id) title+=_(" ") print title return {'ids' : ids , 'title' : title, 'period' : data['form']['period'], 'detail' : not data['form']['hideproducts'], 'year':data['form']['year']}
def compute_age_from_dates(patient_dob): now = DateTime.now() if (patient_dob): dob = DateTime.strptime(patient_dob, '%Y-%m-%d') delta = DateTime.Age(now, dob) years_months_days = str(delta.years) + "y " + str( delta.months) + "m " + str(delta.days) + "d" else: years_months_days = "No DoB !" return years_months_days
def _dateConvertFromDB(d): if d==None: return None for format in ('%Y-%m-%d %H:%M:%S', '%Y-%m-%d', # Y/M/D '%H:%M:%S', # hh:mm:ss '%H:%M', # hh:mm '%Y-%m'): # Y-M try: return DateTime.strptime(d, format) except: pass #maybe it has a miliseconds ? dotind = string.rfind(d, '.') if dotind > 0: dotless=d[:dotind] try: return DateTime.strptime(dotless, '%Y-%m-%d %H:%M:%S') # full date except: pass else: dotless=None candidates=dotless is None and (d,) or (d, dotless) for dt in candidates: dashind = max(dt.rfind('-'), dt.rfind('+')) tz = dt[dashind:] dt = dt[:dashind] try: return DateTime.strptime(dt, '%H:%M:%S'), tz # timetz except: pass try: return DateTime.strptime(dt, '%Y-%m-%d %H:%M:%S'), tz except: pass raise DateTime.Error, "could not parse datetime: %s" % d
def get_sales_lines(self, cr, uid, ids, contaxt=None): product_obj = self.pool.get('product.product') invoice_line = self.pool.get('account.invoice.line') invoice_obj = self.pool.get('account.invoice') for sl in self.browse(cr, uid, ids): prods = [] date_fin = DateTime.strptime(sl.date_fin, '%Y-%m-%d') date_debut = DateTime.strptime(sl.date_debut, '%Y-%m-%d') for p in sl.product_id: prods.append(p.id) prods = tuple(prods) invoice_ids = invoice_obj.search( cr, uid, [('date_invoice', '>=', date_debut), ('date_invoice', '<=', date_fin), ('type', 'in', ['out_invoice', 'out_refund'])]) invoice_lines = invoice_line.search( cr, uid, [('invoice_id', 'in', invoice_ids), ('product_id', 'in', prods)]) invoice_lines = invoice_line.browse(cr, uid, invoice_lines) stock_line_obj = self.pool.get('product.line') for line in invoice_lines: prod = product_obj.browse(cr, uid, line.product_id.id) val = { 'date': line.invoice_id.date_invoice, 'quantite': line.quantity, 'name': line.product_id.id, 'sale_price': line.price_unit, 'amount': line.price_subtotal, 'cost': line.product_id.standard_price * line.quantity, 'cost_unit': line.product_id.standard_price, 'virtual_quantity': prod.virtual_available, 'pub_id': sl.id } # print self stock_line_obj.create(cr, uid, val) return True
def _get_age(self, cr, uid, ids, field_name, arg, context={}): # print 'JE PASSE PAR _GET_AGE et CONTEXT is:', context _logger.info('in _get_age ...') res = {} records = self.browse(cr, uid, ids, context) date = DateTime.today() for record in records: age = '' res[record.id] = { 'age': '', } birthdate = False if record.dob: birthdate = DateTime.strptime(record.dob, '%Y-%m-%d') year, month, day = birthdate.year, birthdate.month, birthdate.day if birthdate: day = int(day) month = int(month) year = int(year) if (date.month > month) or (date.month == month and date.day >= day): if (date.year - year) >= 2: age = str(date.year - year) + _(' YO') else: if date.year == year: age = str(date.month - month) + _(' month') else: age = str(12 + date.month - month) + _(' month') else: if (date.year - year - 1) >= 2: age = str(date.year - year - 1) + _(' YO') else: months = date.month - month if date.month == month: months = -1 if date.year == year: age = str(months) + _(' month') elif date.year == year + 1: age = str(12 + months) + _(' month') elif date.year == year + 2: age = str(24 + months) + _(' month') res[record.id]['age'] += age return res
def handle_match(self, match): """Handles cases where the log_regex is matched.""" message = match.group('message') if not self.status_regex.match(message): return date_time = match.group('date_time') date_time, ms = date_time.split(',') date_time = DateTime.strptime(date_time, self.date_time_fmt) ms = DateTimeDelta(0, 0, 0, int(ms) / 1000.0) date_time = date_time + ms if message.startswith('LOADING_IMAGE'): name = message[message.find(':') + 2:] self.last_import = Import(date_time, name) self.imports.append(self.last_import) elif not hasattr(self, 'last_import') or self.last_import is None: return elif message.startswith('LOADED_IMAGE'): self.last_import.setid_end = date_time elif message.startswith('BEGIN_POST_PROCESS'): self.last_import.post_process_start = date_time elif message.startswith('END_POST_PROCESS'): self.last_import.post_process_end = date_time elif message.startswith('BEGIN_SAVE_TO_DB'): self.last_import.save_to_db_start = date_time elif message.startswith('END_SAVE_TO_DB'): self.last_import.save_to_db_end = date_time elif message.startswith('IMPORT_OVERLAYS'): self.last_import.overlays_start = date_time elif message.startswith('IMPORT_THUMBNAILING'): self.last_import.thumbnailing_start = date_time elif message.startswith('IMPORT_DONE'): self.last_import.end = date_time self.last_import = None elif message.startswith('DATASET_STORED'): self.last_series = Series(date_time) self.last_import.series.append(self.last_series) elif message.startswith('DATA_STORED'): self.last_import.series[-1].end = date_time elif message.startswith('IMPORT_STEP'): self.last_series.planes.append(Plane(date_time))
def _get_records(self, cr, uid, data, context={}): inv_obj = pooler.get_pool(cr.dbname).get('account.invoice') shop_obj = pooler.get_pool(cr.dbname).get('sale.shop') ids = [] if data['form']['draft'] == True: states = ['draft', 'open', 'paid'] else: states = ['open', 'paid'] title = _("Statistiques Article - ") if data['form']['period'] == 'm': if int(data['form']['month']) < 10: title += "0" title += data['form']['month'] + "/" + data['form']['year'] day_min = datetime.date(int(data['form']['year']), int(data['form']['month']), 1) nextmonth = int(data['form']['month']) + 1 year = int(data['form']['year']) if nextmonth == 13: nextmonth = 1 year += 1 day_max = datetime.date(year, nextmonth, 1) - datetime.timedelta(days=1) elif data['form']['period'] == 's': day_min = DateTime.strptime(data['form']['date_from'], '%Y-%m-%d') day_max = DateTime.strptime(data['form']['date_to'], '%Y-%m-%d') title += _("De ") + day_min.strftime('%d/%m/%Y') + _( " A ") + day_max.strftime('%d/%m/%Y') else: day_min = datetime.date(int(data['form']['year']), 1, 1) day_max = datetime.date(int(data['form']['year']), 12, 31) title += data['form']['year'] inv_ids = inv_obj.search(cr, uid, [ ('date_invoice', '>=', day_min.strftime('%Y-%m-%d')), ('date_invoice', '<=', day_max.strftime('%Y-%m-%d')), ('type', 'in', ['out_invoice', 'out_refund', 'sale_refund']), ('state', 'in', states), ]) ids = [] # print inv_ids shop_id = data['form']['shop_id'] if shop_id: title += _(" - Souche ") + shop_obj.browse(cr, uid, shop_id).name if inv_ids: lines = inv_obj.browse(cr, uid, inv_ids) for x in lines: for inv_line in x.invoice_line: # print inv_line.product_id.name # put other tests here if you want to filter lines if (inv_line.price_subtotal <> 0.0): if shop_id: if inv_line.invoice_id.user_id.shop.id == shop_id: # if inv_line.price_subtotal==119675000: # print inv_line.id,inv_line.price_subtotal ids.append(inv_line.id) else: ids.append(inv_line.id) return { 'ids': ids, 'title': title, 'period': data['form']['period'], 'detail': not data['form']['hideproducts'], 'year': data['form']['year'] }
def _get_records(self, cr, uid, data, context={}): inv_obj = pooler.get_pool(cr.dbname).get('account.invoice') ids = [] if data['form']['draft'] == True: states = ['draft', 'open', 'paid'] else: states = ['open', 'paid'] if data['form']['paid'] == True: states = ['paid'] title = _("Commissions - ") if data['form']['period'] == 'm': if int(data['form']['month']) < 10: title += "0" title += data['form']['month'] + "/" + data['form']['year'] day_min = datetime.date(int(data['form']['year']), int(data['form']['month']), 1) nextmonth = int(data['form']['month']) + 1 year = int(data['form']['year']) if nextmonth == 13: nextmonth = 1 year += 1 day_max = datetime.date(year, nextmonth, 1) - datetime.timedelta(days=1) elif data['form']['period'] == 's': day_min = DateTime.strptime(data['form']['date_from'], '%Y-%m-%d') day_max = DateTime.strptime(data['form']['date_to'], '%Y-%m-%d') title += _("De ") + day_min.strftime('%d/%m/%Y') + _( " A ") + day_max.strftime('%d/%m/%Y') else: day_min = datetime.date(int(data['form']['year']), 1, 1) day_max = datetime.date(int(data['form']['year']), 12, 31) title += data['form']['year'] if data['form']['user_id'] == False: user = '******' else: user = '******' + data['form']['user_id'] + '%' if data['form']['excluded_partner_id'] == False: excl = [] else: excl = data['form']['excluded_partner_id'].split(',') partner_obj = pooler.get_pool(cr.dbname).get('res.partner') partner_ids = partner_obj.search(cr, uid, [('ref', 'in', excl)]) if data['form']['paid'] == True: inv_ids = inv_obj.search(cr, uid, [ ('date_invoice', '>=', '2012-05-31'), ('type', 'in', ['out_invoice', 'out_refund']), ('state', 'in', states), ('user_id', 'like', user), ('partner_id', 'not in', partner_ids), ]) else: inv_ids = inv_obj.search(cr, uid, [ ('date_invoice', '>=', day_min.strftime('%Y-%m-%d')), ('date_invoice', '<=', day_max.strftime('%Y-%m-%d')), ('type', 'in', ['out_invoice', 'out_refund']), ('state', 'in', states), ('user_id', 'like', user), ('partner_id', 'not in', partner_ids), ]) ids = [] # print inv_ids if inv_ids: lines = inv_obj.browse(cr, uid, inv_ids) for x in lines: if data['form']['paid'] == True: if x.payment_ids: if x.payment_ids[0].date >= day_min.strftime( '%Y-%m-%d'): if x.payment_ids[0].date <= day_max.strftime( '%Y-%m-%d'): for inv_line in x.invoice_line: if (inv_line.price_subtotal <> 0.0): ids.append(inv_line.id) else: for inv_line in x.invoice_line: if (inv_line.price_subtotal <> 0.0): ids.append(inv_line.id) title += _(" ") if data['form']['paid'] == True: title += _("Factures Payes : ") return { 'ids': ids, 'title': title, 'period': data['form']['period'], 'detail': not data['form']['hideproducts'], 'year': data['form']['year'], 'comm_rate': data['form']['comm_rate'], 'paid': data['form']['paid'] }
def action_create_analytic_lines(self, cr, uid, ids, context=None): res = False values = {} obj_sale_order_line = self.pool.get('sale.order.line') obj_account_analytic_line = self.pool.get('account.analytic.line') obj_factor = self.pool.get('hr_timesheet_invoice.factor') obj_agreement = self.pool.get('inv.agreement') if context is None: context = {} for order in self.browse(cr, uid, ids, context=context): analytic_account = order.project_id.id factor = obj_factor.search(cr, uid, [('factor', '=', 0)])[0] for line in order.order_line: if not line.analytic_created: if line.product_id.property_account_income: general_account = line.product_id.property_account_income.id else: general_account = line.product_id.categ_id.property_account_income_categ.id if not line.invoice_date: raise osv.except_osv(_('User error'), _('Invoice Date not found for: %s') %(line.product_id.name)) values = { 'date': line.invoice_date, 'account_id': analytic_account, 'unit_amount': line.product_uom_qty, 'name': line.name, 'sale_amount':line.price_subtotal, 'general_account_id': general_account, 'product_id': line.product_id.id, 'product_uom_id': line.product_id.uom_id.id, 'ref': order.name, 'to_invoice': factor, 'journal_id': 1, 'sale_id': order.id, } if line.invoice_mode == 'once': values.update({ 'sale_amount': line.price_subtotal, }) obj_account_analytic_line.create(cr,uid,values) elif line.invoice_mode == 'installments': amount = line.price_subtotal / line.installments values.update({ 'sale_amount': amount, }) if line.installment_unit == 'days': increment_size = DateTime.RelativeDateTime(days=1) elif line.installment_unit == 'weeks': increment_size = DateTime.RelativeDateTime(days=7) elif line.installment_unit == 'months': increment_size = DateTime.RelativeDateTime(months=1) elif line.installment_unit == 'years': increment_size = DateTime.RelativeDateTime(months=12) cont = line.installments while cont > 0: obj_account_analytic_line.create(cr,uid,values) next_date = DateTime.strptime(values['date'], '%Y-%m-%d') + increment_size values.update({ 'date': next_date.strftime('%Y-%m-%d'), }) cont-=1 elif line.invoice_mode == 'recur': values = { 'partner_id': order.partner_id.id, 'service': line.product_id.recur_service.id, 'signed_date': line.invoice_date, 'cur_effect_date': line.expire_date, 'partner_signed_date': line.partner_signed_date or line.invoice_date, 'analytic_account': analytic_account, 'payment': line.payment, 'recurr_unit_number': line.interval, 'recurr_unit': line.interval_unit, 'period_unit_number': line.period, 'period_unit': line.period_unit, #'fixed_price': line.price_subtotal, 'fixed_price': line.price_unit, 'sale_order_line':line.id, } id = obj_agreement.create(cr, uid, values) self.write(cr, uid, [order.id], {'agreement': id}) obj_agreement.get_number(cr, uid, [id]) obj_agreement.set_process(cr, uid, [id]) return res
def action_produce_assign_product(self, cr, uid, ids, context={}): produce_id = False company = self.pool.get('res.users').browse(cr, uid, uid, context).company_id for procurement in self.browse(cr, uid, ids): res_id = procurement.move_id.id loc_id = procurement.location_id.id newdate = DateTime.strptime( procurement.date_planned, '%Y-%m-%d %H:%M:%S') - DateTime.RelativeDateTime( days=procurement.product_id.product_tmpl_id.produce_delay or 0.0) newdate = newdate - DateTime.RelativeDateTime( days=company.manufacturing_lead) ## Smile's changes ## FIXME sale order line could be copied natively to the production order sale_order_line_id = self.pool.get('sale.order.line').search( cr, uid, [('procurement_id', '=', procurement.id)]) if sale_order_line_id: sale_order_line_id = sale_order_line_id[0] else: sale_order_line_id = False produce_id = self.pool.get('mrp.production').create( cr, uid, { 'origin': procurement.origin, 'product_id': procurement.product_id.id, 'product_qty': procurement.product_qty, 'product_uom': procurement.product_uom.id, 'product_uos_qty': procurement.product_uos and procurement.product_uos_qty or False, 'product_uos': procurement.product_uos and procurement.product_uos.id or False, 'location_src_id': procurement.location_id.id, 'location_dest_id': procurement.location_id.id, 'bom_id': procurement.bom_id and procurement.bom_id.id or False, 'date_planned': newdate.strftime('%Y-%m-%d %H:%M:%S'), 'move_prod_id': res_id, 'sale_order_line_id': sale_order_line_id, }) self.pool.get('sale.order.line').write( cr, uid, sale_order_line_id, {'mrp_production_id': produce_id}) ## End Smile's changes self.write(cr, uid, [procurement.id], {'state': 'running'}) bom_result = self.pool.get('mrp.production').action_compute( cr, uid, [produce_id], properties=[x.id for x in procurement.property_ids]) wf_service = netsvc.LocalService("workflow") wf_service.trg_validate(uid, 'mrp.production', produce_id, 'button_confirm', cr) return produce_id
def filter_date(self, date): """Parse a date and return a DateTime object.""" # TODO: What date format should we use? Isn't ISO the best option? return DateTime.strptime(date, '%d.%m.%Y')
def is_valid_date(self, date): """Check that a date is parsable and valid.""" DateTime.strptime(date, '%d.%m.%Y') return True
def _get_records(self, cr, uid, data, context={}): inv_obj = pooler.get_pool(cr.dbname).get('account.invoice') shop_obj = pooler.get_pool(cr.dbname).get('sale.shop') ids = [] if data['form']['draft'] == True: states = ['draft', 'open', 'paid'] else: states = ['open', 'paid'] if data['form']['paid'] == True: states = ['paid'] title = _("Commissions - ") if data['form']['period'] == 'm': if int(data['form']['month']) < 10: title += "0" title += data['form']['month'] + "/" + data['form']['year'] day_min = datetime.date(int(data['form']['year']), int(data['form']['month']), 1) nextmonth = int(data['form']['month']) + 1 year = int(data['form']['year']) if nextmonth == 13: nextmonth = 1 year += 1 day_max = datetime.date(year, nextmonth, 1) - datetime.timedelta(days=1) elif data['form']['period'] == 's': day_min = DateTime.strptime(data['form']['date_from'], '%Y-%m-%d') day_max = DateTime.strptime(data['form']['date_to'], '%Y-%m-%d') title += _("De ") + day_min.strftime('%d/%m/%Y') + _( " A ") + day_max.strftime('%d/%m/%Y') else: day_min = datetime.date(int(data['form']['year']), 1, 1) day_max = datetime.date(int(data['form']['year']), 12, 31) title += data['form']['year'] if data['form']['user_id'] == False: user = '******' else: user = '******' + data['form']['user_id'] + '%' if data['form']['excluded_partner_id'] == False: excl = [] else: excl = data['form']['excluded_partner_id'].split(',') partner_obj = pooler.get_pool(cr.dbname).get('res.partner') partner_ids = partner_obj.search(cr, uid, [('ref', 'in', excl)]) if data['form']['paid'] == True: inv_ids = inv_obj.search(cr, uid, [ ('date_invoice', '>=', '2012-06-30'), ('date_invoice', '<=', day_max.strftime('%Y-%m-%d')), ('x_exempt_comm', '=', False), ('type', 'in', ['out_invoice', 'out_refund']), ('state', 'in', states), ('user_id', 'like', user), ('partner_id', 'not in', partner_ids), ]) else: inv_ids = inv_obj.search(cr, uid, [ ('date_invoice', '>=', day_min.strftime('%Y-%m-%d')), ('date_invoice', '>=', '2012-06-30'), ('date_invoice', '<=', day_max.strftime('%Y-%m-%d')), ('type', 'in', ['out_invoice', 'out_refund']), ('state', 'in', states), ('user_id', 'like', user), ('partner_id', 'not in', partner_ids), ]) ids = [] # print inv_ids shop_id = data['form']['shop_id'] if shop_id: title += _(" - Souche ") + shop_obj.browse(cr, uid, shop_id).name if inv_ids: lines = inv_obj.browse(cr, uid, inv_ids) for x in lines: if data['form']['paid'] == True: if x.payment_ids: for pay in x.payment_ids: pay_date = pay.date if pay_date >= day_min.strftime('%Y-%m-%d'): if pay_date <= day_max.strftime('%Y-%m-%d'): for inv_line in x.invoice_line: if (inv_line.price_subtotal <> 0.0): ids.append(inv_line.id) #print inv_line.partner_id.name #print inv_line.product_id.name # else: # if x.type=='out_refund': # if x.date_invoice>=day_min.strftime('%Y-%m-%d'): # for inv_line in x.invoice_line: # if (inv_line.price_subtotal <> 0.0): # ids.append(inv_line.id) else: for inv_line in x.invoice_line: # print inv_line.product_id.name # put other tests here if you want to filter lines if (inv_line.price_subtotal <> 0.0): if shop_id: if inv_line.invoice_id.user_id.shop.id == shop_id: # if inv_line.price_subtotal==119675000: # print inv_line.id,inv_line.price_subtotal ids.append(inv_line.id) else: ids.append(inv_line.id) title += _(" ") #print title return { 'ids': ids, 'title': title, 'period': data['form']['period'], 'detail': not data['form']['hideproducts'], 'year': data['form']['year'], 'comm_rate': data['form']['comm_rate'], 'paid': data['form']['paid'] }
def generate_task_realisasi_bulanan(self, cr, uid, ids, context=None): if context is None: context = {} task = {} task_pool = self.pool.get('project.task') stage_pool = self.pool.get('project.task.type') for task_generate in self.browse(cr, uid, ids, context=context): #check Duplicate #Init Field target_category = 'bulanan' description = '' lama_kegiatan = task_generate.lama_kegiatan user_id = task_generate.user_id.id target_period_year = task_generate.target_period_year target_period_month = 'xx' date_start = 'xx' date_end = 'xx' company_id = None currency_id = None user_id_bkd = None employee = self.get_employee_from_user_id(cr, uid, task_generate) if user_id != uid: raise osv.except_osv( _('Invalid Action!'), _('Anda Tidak Memiliki Priviledge Untuk Proses Ini.')) if not employee: raise osv.except_osv( _('Invalid Action, Data Pegawai Tidak Lengkap'), _('Proses Tidak Dapat Dilanjutkan Karena Ada Beberapa Informasi Kepegawaian Belum Diisi, Khususnya Data Pejabat Penilai Dan Atasan Banding.' )) else: company = employee.company_id company_id = company.id currency_id = employee.company_id.currency_id #print "company_id : ",company_id,' - ',currency_id if not company_id: raise osv.except_osv( _('Invalid Action, Data Pegawai Tidak Lengkap'), _('Proses Tidak Dapat Dilanjutkan Karena Unit Dinas Pegawai Belum Dilengkapi.' )) #print "employee parent : ",employee.parent_id if not task_generate.user_id_bkd: if not company.user_id_bkd: raise osv.except_osv( _('Invalid Action, Data Dinas Kurang Lengkap'), _('Staff Pemeriksa Dari BKD Tidak Tersedia Untuk Unit Anda, Silahkan hubungi Admin Atau isi Data Pemeriksa.' )) else: user_id_bkd = company.user_id_bkd.id else: user_id_bkd = task_generate.user_id_bkd.id if not employee.user_id_atasan: raise osv.except_osv( _('Invalid Action, Data Pegawai Tidak Lengkap'), _('Proses Tidak Dapat Dilanjutkan Karena Data Pejabat Penilai Belum Terisi.' )) if not employee.user_id_banding: raise osv.except_osv( _('Invalid Action, Data Pegawai Tidak Lengkap'), _('Proses Tidak Dapat Dilanjutkan Karena Data Pejabat Pengajuan Banding.' )) user_id_atasan = task_generate.user_id_atasan.id user_id_banding = task_generate.user_id_banding.id if not task_generate.user_id_atasan.id: user_id_atasan = employee.user_id_atasan.user_id.id if not task_generate.user_id_banding.id: user_id_banding = employee.user_id_banding.user_id.id task.update({ 'project_id': None, 'user_id': user_id, 'company_id': company_id, 'description': description, 'name': task_generate.name, 'code': None, 'target_category': target_category, #'sequence': target_obj.priority, 'target_type_id': task_generate.target_type_id, 'target_period_year': target_period_year, 'user_id_atasan': user_id_atasan or False, 'user_id_banding': user_id_banding or False, 'user_id_bkd': user_id_bkd or False, 'priority': '2', 'currency_id': currency_id, 'target_waktu': 0, 'target_kualitas': 0, 'target_jumlah_kuantitas_output': 0, 'task_category': 'non_skp', }) #Update Task Target Bulanan now = DateTime.today() first_task_id = None if task_generate.date_start: curr_date = DateTime.strptime(task_generate.date_start, '%Y-%m-%d') else: january = DateTime.Date(now.year, 1, 1) curr_date = DateTime.strptime(january.strftime('%Y-%m-%d'), '%Y-%m-%d') first_date = curr_date #print "THIS IS A DATE ",curr_date for i in range(0, lama_kegiatan): next_date = curr_date + DateTime.RelativeDateTime(months=i) target_period_month = next_date.strftime('%m') task.update({ 'target_period_month': target_period_month, 'name': '%s %s' % (task_generate.name, target_period_month), }) #Check Duplicate Do Not Create task_ids = task_pool.search( cr, uid, [('user_id', '=', user_id), ('target_period_month', '=', target_period_month), ('target_period_year', '=', target_period_year), ('target_type_id', '=', task_generate.target_type_id), ('work_state', '!=', 'draft')], context=None) if task_ids: continue else: #Delete Duplicate task_ids = task_pool.search( cr, uid, [('user_id', '=', user_id), ('target_period_month', '=', target_period_month), ('target_period_year', '=', target_period_year), ('target_type_id', '=', task_generate.target_type_id), ('work_state', '=', 'draft')], context=None) task_pool.unlink(cr, uid, task_ids, context=None) date_start = 'xx' date_end = 'xx' stage_ids = stage_pool.search(cr, uid, [('sequence', '=', 0)], context=None) work_state = 'draft' if stage_ids: task.update({ 'stage_id': stage_ids[0], 'work_state': work_state, 'state': 'draft', 'currency_id': currency_id }) #insert task task_id = task_pool.create(cr, uid, task) return { 'type': 'ir.actions.act_window', 'view_type': 'form', 'view_mode': 'form', 'res_model': 'notification.generate.task', 'target': 'new', 'context': context, #['notif_booking'], }
class DiaryInfo: """ This class holds configuration information for the rest of the program, parses command line args, prints the usage message.""" points_mm = 2.8346457 # Do all our work in millimetres sectionSep = "%-----------------\n" # Separator inside the postscript options = [ "address-pages=", "appointments", "appointment-width=", "awk-ref", "calendar-pages=", "colour", "colour-images", "conversions-ref", "cover-image=", "cover-page-image=", "day-title-shading=", "debug-boxes", "debug-version", "debug-whole-page-boxes", "eps-page=", "eps-2page=", "event-images", "expense-pages=", "gridded-logbook", "gridded-notes", "gridded", "help", "image-page=", "image-2page=", "large-planner", "layout=", "line-colour=", "line-spacing=", "logbook-pages=", "man-page=", "margins-multiplier=", "moon", "northern-hemisphere-moon", "no-appointment-times", "no-smiley", "notes-pages=", "output-file=", "page-registration-marks", "page-size=", "page-x-offset=", "page-y-offset=", "paper-size=", "pcal", "pcal-planner", "pdf", "perpetual-calendars", "personal-info-no-work", "planner-years=", "ref=", "sed-ref", "sh-ref", "shading=", "start-date=", "title=", "units-ref", "unix-ref", "vi-ref", "vim-ref", "weeks-before=", "weeks-after=", "version", "year=", ] usageStrings = \ [ "Usage: %s [--year=year | --start-date=yyyy-mm-dd]\n", " [--output-file=file] [--title=TITLE]\n", " [--address-pages=n] [--appointment-width=w] [--appointments]\n", " [--calendar-pages=yes|no]\n", " [--colour | --colour-images] [--line-colour=COLOUR]\n", " [--cover-image=IMAGE] [--cover-page-image=IMAGE]\n", " [--day-title-shading=all|holidays|none] [--shading=yes|no]\n", " [--debug-boxes] [--debug-whole-page-boxes] [--debug-version]\n", " [--eps-page=epsfile[|title]] [--eps-2page=epsfile[|title1[|title2]]]\n", " [--event-images] [--expense-pages=0|2|4] [--gridded-notes]\n", " [--image-page=IMGFILE[,title]] [--image-2page=IMGFILE[,title][,coverage]]\n", " [--large-planner] [--line-spacing=mm] [--margins-multiplier=f] [--moon]\n", " [--layout=LAYOUT] [--logbook-pages=N] [--man-page=MANPAGE]\n", " [--northern-hemisphere-moon] [--no-appointment-times] [--no-smiley]\n", " [--no-shading] [--notes-pages=n]\n", " [--page-registration-marks] [--page-x-offset=Xmm]\n", " [--page-y-offset=Ymm] [--pdf] [--planner-years=n] \n", " [--pcal] [--pcal-planner] [--perpetual-calendars]\n", " [--personal-info-no-work]\n", " [--ref=<refname>] [--awk-ref] [--conversions-ref]\n", " [--sed-ref] [--sh-ref] [--units-ref] [--unix-ref] [--vi[m]-ref]\n", " [--weeks-before=n] [--weeks-after=n]\n", " [--help] [--version]\n", ] sizesString = "|".join(PaperSize.getPaperSizeNames()) usageStrings.append(" [--page-size=%s]\n" % sizesString) usageStrings.append(" [--paper-size=%s]\n" % sizesString) usageStrings.append(" Defaults:\n") usageStrings.append(" year = next year line-spacing = 6.0mm\n") usageStrings.append(" page-size = a5 paper-size = a5\n") usageStrings.append(" weeks-before = 0 weeks-after = 0\n") usageStrings.append(" appointment-width = 35% planner-years = 2\n") usageStrings.append(" address-pages = 6 notes-pages = 6\n") layouts = ("day-to-page", "logbook", "week-to-opening", "week-to-2-openings", "week-to-page", "week-with-notes", "work") defaultLayout = "week-to-2-openings" usageStrings.append(" Layouts: " + ", ".join(layouts) + "\n") usageStrings.append(" Default layout: " + defaultLayout + "\n") def usage(self, f=sys.stderr, code=1): for i in range(len(self.usageStrings)): f.write(self.usageStrings[i]) sys.exit(code) def shortUsage(self, f=sys.stderr): print >> f, "%s --help for usage" % self.myname sys.exit(1) def __init__(self, myname, opts): self.myname = myname self.opts = opts self.usageStrings[0] = self.usageStrings[0] % myname # first init the instance variables. self.pageNumber = 0 # Page number count self.currentJDaysLeft = -1 # Days left in year self.setStartDate(DateTime.DateTime(DateTime.now().year + 1)) # Adjusted time, next year self.paperSize = 'a5' # Page sizes. Default to a5. wh = PaperSize.getPaperSize(self.paperSize) self.pageWidth = wh[0] self.pageHeight = wh[1] self.paperWidth = wh[0] self.paperHeight = wh[1] self.pageXOffset = 0.0 self.pageYOffset = 0.0 self.translatePage = 0 self.translateXOffset = 0.0 self.translateYOffset = 0.0 self.iMargin = 12.0 # Page layout options self.oMargin = 5.0 # self.bMargin = 5.0 # self.tMargin = 5.0 # self.coverTitleFontSize = 20.0 # self.titleFontSize = 7.0 # self.titleFontName = "Times-Bold" # self.titleFontNoBoldName = "Times" # self.subtitleFontSize = 4.0 # self.subtitleFontName = "Helvetica" # self.subtitleFontNoBoldName = "Helvetica" # self.personalinfoFontName = "Times-Bold" # self.personalinfoFixedFontName = "Courier-Bold" # self.titleY = -1 # Distance from bottom to title, calc from page size self.titleLineY = -1 # self.titleGray = 0.8 # Background for titles on some pages self.underlineThick = 0.2 # Thickness of title lines etc self.lineSpacing = 6.0 # Spacing for writing lines self.evenPage = 0 # even and odd pages self.out = None # Output file self.outName = 'diary.ps' # Output file name self.outNameSet = False # True if the output name set by command line opt. self.nAddressPages = 6 # Default self.nNotesPages = 6 # self.nPlannerYears = 2 # self.largePlanner = False # Default: no large planner self.coverImage = None # Pic for the cover page. self.coverPageImage = None # Pic for the whole cover page. self.appointments = False # Different "styles" for different people. self.appointmentTimes = True # Print appointment times or not self.appointmentWidth = 35 # Width of appointments (as percentage) self.colour = False # If true, print images in colour self.moon = False # If true, print moon phases self.northernHemisphereMoon = False # If true, print northern hemisphere moon phases self.layout = self.defaultLayout self.debugBoxes = False # If true, draw faint boxes around things for debugging self.debugVersion = False # If true, print version info on inside cover. self.debugWholePageBoxes = False # If true, draw faint boxes around all pages. self.pageRegistrationMarks = False # Print marks to show where to cut. self.events = {} # Events to draw on each page, from .calendar file. self.drawEventImages = False # If true, draw event images self.nWeeksBefore = 0 # Print this number of weeks before the current year. self.nWeeksAfter = 0 self.smiley = True self.imagePages = [] self.manPages = [] self.epsPages = [] self.title = None self.pdf = False self.pcal = False self.pcalPlanner = False self.perpetualCalendars = False self.calendarPages = True self.nExpensePages = 2 self.griddedLogbookPages = False self.griddedNotesPages = False self.griddedLogbookPages = False self.dayTitleBoxes = True self.dayTitleShading = "all" self.shading = True self.nLogbookPages = 100 self.lineColour = [0, 0, 0] self.personalInfoNoWork = False self.configOptions = ConfigParser() self.configOptions.read( (expanduser("~/.makediaryrc"), ".makediaryrc", "makediaryrc")) self.createMonthCalendars() self.parseOptions() self.readDotCalendar() def createMonthCalendars(self): '''Create all the month calendar names. There are only 14 possible yearly calendars - one for a year beginning on each day of the days of the week, and twice that for leap years. For each day of the week, we generate one set of month calendars that start on that day and finish on that day (ie 1JAN and 31DEC are the same day of the week) and another set where the year is an extra day longer. The idea is when something wants to print a month calendar, it can call in here with the year and month, and we will calculate exactly which calendar is to be printed, and return a name that will print that calendar in PostScript. ''' self.monthCalendarList = {} for i in range(7): for m in range(1, 13): self.monthCalendarList[(m, i, i)] = "M_m%02d_b%d_e%d" % (m, i, i) i2 = (i + 1) % 7 self.monthCalendarList[(m, i, i2)] = "M_m%02d_b%d_e%d" % (m, i, i2) def getMonthCalendarPsFnCall(self, year, month, addyear=True): '''Return the code to call a PostScript function that will print the appropriate calendar for a given year and month. If addYear==False, we return '() M_mMM_bB_eE', where MM is the month number, B is the day of week of the beginning of the year, and E is the day of week of the end of the year. If addYear is true, we return '(YYYY) M_mMM_bB_eE', where YYYY is the four digit year. ''' dow_begin = DateTime.DateTime(year, 1, 1).day_of_week dow_end = DateTime.DateTime(year, 12, 31).day_of_week k = (month, dow_begin, dow_end) if not self.monthCalendarList.has_key(k): print >> sys.stderr, "makediary: internal error:" print >> sys.stderr, "-- No month calendar for year=%s month=%s" % ( str(year), str(month)) sys.exit(1) procname = self.monthCalendarList[k] if addyear: return (" (%d) " % year) + procname else: return " () " + procname def parseOptions(self): args = self.opts # The first week day should be settable by command line option. #calendar.setfirstweekday(MONDAY) # Save the command line opts in here, and process them all at the end. c = {} try: optlist, args = getopt.getopt(args, '', self.options) except getopt.error, reason: sys.stderr.write("Error parsing options: " + str(reason) + "\n") self.shortUsage() if len(args) != 0: sys.stderr.write("Unknown arg: %s\n" % args[0]) self.shortUsage() # Gather all the command line options into a list so we can process them later. for opt in optlist: assert len(opt) == 2 if 0: pass elif opt[0] == "--help": # The help option bypasses all the others. self.usage(sys.stdout, 0) elif opt[0] == "--man-page": # --man-page can be specified multiple times. self.manPageOption(opt[1]) elif opt[0] == "--ref": # --ref can be specified multiple times. name_and_titles = opt[1].split('|') self.standardEPSRef(name_and_titles[0], name_and_titles[1:]) # Now all the standard args. elif len(opt[1]) == 0: # No argument, so just save the setting. c[opt[0]] = True else: # Save the setting and the argument. c[opt[0]] = opt[1] # Now process all the gathered options. Look at the layout option first, so we can set # things needed by the layout, and potentially change them later. if c.has_key("--layout"): l = c["--layout"] if l in self.layouts: self.layout = l if self.layout == "logbook": self.calendarPages = False self.nPlannerYears = 0 elif self.layout == "week-to-page" or self.layout == "week-with-notes": self.dayTitleBoxes = False self.dayTitleShading = "none" else: print >> sys.stderr, "%s: Unknown layout %s" % (self.myname, l) self.shortUsage() if c.has_key("--address-pages"): self.nAddressPages = self.integerOption("address-pages", c["--address-pages"]) if c.has_key("--appointment-width"): self.appointments = True aw = c["--appointment-width"] if aw[-1] == '%': optstr = aw[0:-1] # Strip an optional trailing '%' else: optstr = aw self.appointmentWidth = self.floatOption("appointment-width", optstr) if self.appointmentWidth < 0 or self.appointmentWidth > 100: sys.stderr.write( "%s: appointment width must be >=0 and <=100\n" % self.myname) sys.exit(1) if c.has_key("--appointments"): self.appointments = True if c.has_key("--awk-ref"): self.standardEPSRef('awk', ['Awk reference']) if c.has_key("--calendar-pages"): self.calendarPages = self.boolOption("calendar-pages", c["--calendar-pages"]) if c.has_key("--colour") or c.has_key("--colour-images"): self.colour = True if c.has_key("--line-colour"): self.setLineColour(c["--line-colour"]) self.dayTitleShading = "none" self.shading = False if c.has_key("--shading"): self.shading = self.boolOption("shading", c["--shading"]) if c.has_key("--conversions-ref"): self.standardEPSRef('conversions', ['Double conversion tables']) if c.has_key("--cover-image"): self.coverImage = c["--cover-image"] if c.has_key("--cover-page-image"): self.coverPageImage = c["--cover-page-image"] if c.has_key("--day-title-shading"): dts = c["--day-title-shading"] if dts in ("all", "holidays", "none"): self.dayTitleShading = dts else: print >>sys.stderr, "day-title-shading must be all or holidays or none" \ + " (not \"%s\")" % dts self.shortUsage() if c.has_key("--debug-boxes"): self.debugBoxes = 1 if c.has_key("--debug-whole-page-boxes"): self.debugWholePageBoxes = 1 if c.has_key("--debug-version"): self.debugVersion = True if c.has_key("--eps-page"): self.epsFilePageOption(c["--eps-page"], 1) if c.has_key("--eps-2page"): self.epsFilePageOption(c["--eps-2page"], 2) if c.has_key("--expense-pages"): ep = c["--expense-pages"] if ep == '0' or ep == '2' or ep == '4': self.nExpensePages = int(ep) else: print >>sys.stderr, \ "%s: number of expense pages must be 0, 2, or 4 (not \"%s\")." % \ (sys.argv[0], ep) self.shortUsage() if c.has_key("--perpetual-calendars"): self.perpetualCalendars = True if c.has_key("--event-images"): self.drawEventImages = True if c.has_key("--gridded"): self.griddedLogbookPages = True self.griddedNotesPages = True if c.has_key("--gridded-logbook"): self.griddedLogbookPages = True if c.has_key("--gridded-notes"): self.griddedNotesPages = True if c.has_key("--image-page"): self.imagePageOption(c["--image-page"], 1) if c.has_key("--image-2page"): self.imagePageOption(c["--image-2page"], 2) if c.has_key("--large-planner"): self.largePlanner = True if c.has_key("--line-spacing"): self.lineSpacing = self.floatOption("line-spacing", c["--line-spacing"]) if c.has_key("--logbook-pages"): self.nLogbookPages = self.integerOption("logbook-pages", c["--logbook-pages"]) if c.has_key("--margins-multiplier"): multiplier = self.floatOption("margins-multiplier", c["--margine-multiplier"]) self.tMargin = self.tMargin * multiplier self.bMargin = self.bMargin * multiplier self.iMargin = self.iMargin * multiplier self.oMargin = self.oMargin * multiplier if c.has_key("--moon"): self.moon = True if c.has_key("--northern-hemisphere-moon"): self.moon = True self.northernHemisphereMoon = True if c.has_key("--no-appointment-times"): self.appointmentTimes = False if c.has_key("--no-smiley"): self.smiley = False if c.has_key("--notes-pages"): self.nNotesPages = self.integerOption("notes-pages", c["--notes-pages"]) if c.has_key("--output-file"): self.outName = c["--output-file"] self.outNameSet = True if c.has_key("--page-registration-marks"): self.pageRegistrationMarks = True if c.has_key("--page-size"): self.pageSize = c["--page-size"] self.setPageSize(self.pageSize) if c.has_key("--page-x-offset"): self.pageXOffset = self.floatOption("page-x-offset", c["--page-x-offset"]) if c.has_key("--page-y-offset"): self.pageYOffset = self.floatOption("page-y-offset", c["--page-y-offset"]) if c.has_key("--pdf"): self.pdf = True if c.has_key("--paper-size"): self.paperSize = c["--paper-size"] self.setPaperSize(self.paperSize) if c.has_key("--pcal"): self.pcal = True if c.has_key("--pcal-planner"): self.pcal = True self.pcalPlanner = True if c.has_key("--personal-info-no-work"): self.personalInfoNoWork = True if c.has_key("--planner-years"): self.nPlannerYears = self.integerOption("planner-years", c["--planner-years"]) if c.has_key("--version"): print "makediary, version " + versionNumber sys.exit(0) if c.has_key("--sed-ref"): self.standardEPSRef('sed', ['sed reference']) if c.has_key("--sh-ref"): self.standardEPSRef('sh', ['Shell and utility reference']) if c.has_key("--start-date"): self.setStartDate(DateTime.strptime(c["--start-date"], '%Y-%m-%d')) if c.has_key("--title"): self.title = c["--title"] if c.has_key("--units-ref"): self.standardEPSRef('units', ['Units']) if c.has_key("--unix-ref"): self.standardEPSRef('unix', [ 'Unix reference', ]) if c.has_key("--vim-ref") or c.has_key("--vi-ref"): self.standardEPSRef('vi', ['Vi reference', 'Vim extensions']) if c.has_key("--weeks-after"): self.nWeeksAfter = self.integerOption("weeks-after", c["--weeks-after"]) if c.has_key("--weeks-before"): self.nWeeksBefore = self.integerOption("weeks-before", c["--weeks-before"]) if c.has_key("--year"): self.setStartDate( DateTime.DateTime(self.integerOption("year", c["--year"]))) if self.pdf: # If the name is still diary.ps and it was not set by command line option, change # it to diary.pdf. if (not self.outNameSet) and self.outName == 'diary.ps': self.outName = 'diary.pdf' # If we are doing PDF output, let ps2pdf open the output file. pdfArgs = ( 'ps2pdf', '-dAutoRotatePages=/None', # pdf2ps rotates some pages without this '-sPAPERSIZE=' + self.paperSize, '-', self.outName) #print >>sys.stderr, "Running "+str(pdfArgs) self.pdfProcess = subprocess.Popen(pdfArgs, stdin=subprocess.PIPE) self.out = self.pdfProcess.stdin else: if self.outName == '-': self.out = sys.stdout else: try: self.out = open(self.outName, 'w') except IOError, reason: sys.stderr.write(("Error opening '%s': " % self.outName) \ + str(reason) + "\n") #self.usage() sys.exit(1)