示例#1
0
 def button_lunch(self, cr, uid, ids, context=None):
     att_obj = self.pool.get('hr.attendance')
     comp_obj = self.pool.get('res.company')
     company_id = comp_obj._company_default_get(cr, uid, 'hr.attendance', context=context)
     company = comp_obj.browse(cr, uid, company_id, context=context)
     
     if not company.lunch_duration:
         raise osv.except_osv(_('Error'), _("Please specify a 'Lunch Duration' in the company configuration!")) 
     
     # time of sign_out is always 12:00
     lunch_time = DateTime.now() + DateTime.RelativeDateTime(hour=10, minute=0, second=0)
     
     for sheet in self.browse(cr, uid, ids):      
         vals = {
             'name': lunch_time.strftime('%Y-%m-%d %H:%M:%S'),
             'sheet_id': sheet.id,
             'action': 'sign_out',
             'flag': 'B',
             'employee_id': sheet.employee_id.id,
         }         
         att_obj.create(cr, uid, vals, context=context)
         vals['name'] = (lunch_time + DateTime.RelativeDateTime(minutes= company.lunch_duration)).strftime('%Y-%m-%d %H:%M:%S')
         vals['action'] = 'sign_in'
         att_obj.create(cr, uid, vals, context=context)
     
     return True
示例#2
0
 def run_employee_evaluation(self,
                             cr,
                             uid,
                             automatic=False,
                             use_new_cursor=False,
                             context=None):
     for id in self.browse(cr,
                           uid,
                           self.search(cr, uid, [], context=context),
                           context=context):
         if id.evaluation_plan_id and id.evaluation_date:
             if (dt.ISO.ParseAny(id.evaluation_date) + dt.RelativeDateTime(
                     months=int(id.evaluation_plan_id.month_next))
                 ).strftime('%Y-%m-%d') <= time.strftime("%Y-%m-%d"):
                 self.write(
                     cr,
                     uid,
                     id.id, {
                         'evaluation_date':
                         (dt.ISO.ParseAny(id.evaluation_date) +
                          dt.RelativeDateTime(
                              months=+int(id.evaluation_plan_id.month_next))
                          ).strftime('%Y-%m-%d')
                     },
                     context=context)
                 self.pool.get("hr_evaluation.evaluation").create(
                     cr, uid, {
                         'employee_id': id.id,
                         'plan_id': id.evaluation_plan_id
                     }, context)
     return True
示例#3
0
    def init_report(self, lab=None):
        self.report_id = None
        self.notes = ''
        self.completed = None

        self.lab_options = list(labs)
        self.lab_options.insert(0, choose)
        if lab:
            for name, label in labs:
                if name.lower() == lab.lower():
                    lab = name
                    break
            else:
                lab = None
        if lab:
            self.lab = lab
            self.lab_readonly = True
        else:
            self.lab = self.lab_options[0][0]
            self.lab_readonly = False

        prev_week = DateTime.RelativeDateTime(weeks=-1)
        self.week_options = []
        d = DateTime.now() + \
            DateTime.RelativeDateTime(days=-4, weekday=(DateTime.Friday, 0),
                                      hour=0, minute=0, second=0)
        for n in range(8):
            self.week_options.append(d.strftime('%Y-%m-%d'))
            d += prev_week
        self.week_options.reverse()
        self.week = self.week_options[-1]
        self.__monitor = Monitor(self, *self.report_cols)
示例#4
0
 def _back_forward(self, widget, type, *args, **argv):
     if self.mode=='day':
         self.date = self.date + DateTime.RelativeDateTime(days=type)
     if self.mode=='week':
         self.date = self.date + DateTime.RelativeDateTime(weeks=type)
     if self.mode=='month':
         self.date = self.date + DateTime.RelativeDateTime(months=type)
     self.display(None)
示例#5
0
    def compute(self, cr, uid, ids, order, context={}):
        pricelist = self.pool.get('res.partner').browse(
            cr, uid, order['partner_id']).property_product_pricelist.id
        subtotal = 0
        taxes = 0
        for product in order['products']:
            product_id = int(product['product_id'])
            price = self.pool.get('product.pricelist').price_get(
                cr, uid, [pricelist], product_id,
                int(product['product_qty']))[pricelist]
            product['price'] = price

            prod_info = self.pool.get('product.product').read(
                cr, uid, [product_id],
                ['sale_delay', 'qty_available', 'code', 'name'])[0]
            dt = (DateTime.now() + DateTime.RelativeDateTime(
                days=prod_info['sale_delay'] or 0.0)).strftime('%Y-%m-%d')
            product['date_available'] = dt
            product['qty_available'] = prod_info['qty_available']
            product['code'] = prod_info['code']
            product['name'] = prod_info['name']
            product['subtotal'] = price * int(product['product_qty'])
            subtotal += (price * int(product['product_qty']))
            taxes += 0
        order['price_subtotal'] = subtotal
        order['price_tax'] = taxes
        order['price_total'] = taxes + subtotal
        return order
示例#6
0
 def timesForRange(self, start=None, end=None, grain=1):
     """
     returns a list of times where the spec matches within the
     range from start to end, stepped through by grain.
     """
     if start is None:
         start=M.now() + _second_zero
     elif isinstance(start, int):
         start=M.DateTimeFromTicks(start)
     if end is None:
         end=start+M.oneDay
     elif isinstance(end, int):
         end=M.DateTimeFromTicks(end)
     if start > end:
         raise ValueError, "start time %s greater than end time %s" % \
               (start.asctime(), end.asctime())
     if grain<1:
         raise ValueError, "grain must be at least one minute"
     incr=M.RelativeDateTime(minutes=grain)
     times=[]
     while start<=end:
         if self.matchTime(start):
             times.append(start)
         start=start+incr
     return times
示例#7
0
 def ISO_date_time( self, info, buffer):
     """Interpret the loose ISO date + time format"""
     (tag, left, right, sublist) = info
     set = singleMap( sublist, self, buffer )
     base, time, offset = (
         set.get(self.dateName),
         set.get(self.timeName) or DateTime.RelativeDateTime(hour=0,minute=0,second=0),
         set.get( "offset" ),
     )
     base = base + time
     offset = set.get( "offset" )
     if offset is not None:
         # an explicit timezone was entered, convert to gmt and return as appropriate...
         gmt = base - offset
         if self.returnLocal:
             return gmt.localtime()
         else:
             return gmt
     # was in the default input locale (either gmt or local)
     if self.inputLocal and self.returnLocal:
         return base
     elif not self.inputLocal and not self.returnLocal:
         return base
     elif self.inputLocal and not self.returnLocal:
         # return gmt from local...
         return base.gmtime()
     else:
         return base.localtime()
示例#8
0
    def running_nexteval_dates(self, cr, uid, *args):
        evaluation_obj = pooler.get_pool(cr.dbname).get('hr.evaluation')
        eval_hist_obj = pooler.get_pool(cr.dbname).get('hr.evaluation.history')
        employee_obj = pooler.get_pool(cr.dbname).get('hr.employee')
        employee_ids = employee_obj.search(cr, uid, [])
        for emp in employee_obj.browse(cr, uid, employee_ids):
            if not len(emp.history_ids):
                #USE date on contract instead of date defined on the employee
                cr.execute("""select date_start from hr_contract where employee_id = %s and
                              (date_end >= %s or date_end is NULL) order by date_start desc""", [emp.id, time.strftime('%Y-%m-%d')])
                last_date = cr.fetchone()
                last_date = last_date and last_date[0] or None
              #  last_date=emp.date_entry or None
              #  salary_market=emp.grid_id and emp.grid_id.salary_market or 0.0
                old_grid_id = emp.grid_id.id or None
                old_salary = emp.current_salary or 0.0
            else:
                cr.execute("""select max(date_eval),old_grid_id,old_salary from hr_evaluation_history
                              where employee_id=%s group by old_grid_id,old_salary""", [emp.id])
                res = cr.fetchone()
                last_date = res and res[0] or None
                old_grid_id = res and res[1] or None
                old_salary = res and res[2] or 0.0

            if last_date and (dt.ISO.ParseAny(last_date)+dt.RelativeDateTime(months=+6, days=-15)).strftime('%Y-%m-%d') == dt.now().strftime('%Y-%m-%d'):
                eval_hist_obj.create(cr, uid, {'employee_id': emp.id,
                                            'date_eval': (dt.ISO.ParseAny(last_date)+ dt.RelativeDateTime(months=+6)).strftime('%Y-%m-%d'),
                                            'old_grid_id': old_grid_id,
#                                            'salary_market':salary_market,
                                            'old_salary': old_salary
                })
                evaluation_obj.create(cr, uid, {'employee_id': emp.id,
                                            'next_eval': (dt.ISO.ParseAny(last_date)+ dt.RelativeDateTime(months=+6)).strftime('%Y-%m-%d'),
                })
        return True
示例#9
0
 def reldate(**kwargs):
     if not kwargs.has_key('hours'):
         kwargs['hour'] = 0
     if not kwargs.has_key('minutes'):
         kwargs['minute'] = 0
     kwargs['second'] = 0
     return DateTime.RelativeDateTime(**kwargs)
 def _carnet_before(self):
     import mx.DateTime as dt
     res = {}
     res_list = []
     today = dt.now()
     before_date = dt.now() + dt.RelativeDateTime(months=1)
     before_date = before_date.strftime("%Y-%m-%d")
     today = today.strftime("%Y-%m-%d")
     carnet_obj = self.pool.get('cci_missions.ata_carnet')
     carnet_ids = carnet_obj.search(self.cr, self.uid,
                                    [('validity_date', '<=', before_date),
                                     ('validity_date', '>=', today),
                                     ('state', '>=', 'created')])
     carnet_data = carnet_obj.browse(self.cr, self.uid, carnet_ids)
     for carnet in carnet_data:
         flag = False
         address = ''
         for letter in carnet.letter_ids:
             if letter.letter_type == 'Rappel avant echeance':
                 flag = True
         if not flag:
             if carnet.partner_id.address:
                 for add in carnet.partner_id.address:
                     if add.type == 'default':
                         address = (add.street or '') + ' ' + (
                             add.street2 or '') + '\n' + (
                                 add.zip_id and add.zip_id.name
                                 or '') + ' ' + (add.city or '') + '\n' + (
                                     add.state_id and add.state_id.name
                                     or '') + ' ' + (add.country_id
                                                     and add.country_id.name
                                                     or '')
                         continue
                     else:
                         address = (add.street or '') + ' ' + (
                             add.street2 or '') + '\n' + (
                                 add.zip_id and add.zip_id.name
                                 or '') + ' ' + (add.city or '') + '\n' + (
                                     add.state_id and add.state_id.name
                                     or '') + ' ' + (add.country_id
                                                     and add.country_id.name
                                                     or '')
             res = {
                 'partner_name': carnet.partner_id.name,
                 'partner_address': address,
                 'type': carnet.type_id.name,
                 'name': carnet.name,
                 'creation_date': carnet.creation_date,
                 'validity_date': carnet.validity_date
             }
             res_letter = {
                 'letter_type': 'Rappel avant echeance',
                 'date': time.strftime('%Y-%m-%d'),
                 'ata_carnet_id': carnet.id,
             }
             id = self.pool.get('cci_missions.letters_log').create(
                 self.cr, self.uid, res_letter)
             res_list.append(res)
     return res_list
示例#11
0
    def button_plan_in_progress(self, cr, uid, ids, context={}):
        apprai_id = []
        for evaluation in self.browse(cr, uid, ids, context):
            wait = False
            for phase in evaluation.plan_id.phase_ids:
                childs = []
                if phase.action == "bottom-up":
                    childs = evaluation.employee_id.child_ids
                elif phase.action in ("top-down", "final"):
                    if evaluation.employee_id.parent_id:
                        childs = [evaluation.employee_id.parent_id]
                elif phase.action == "self":
                    childs = [evaluation.employee_id]
                for child in childs:
                    if not child.user_id:
                        continue

                    hr_eval_inter_obj = self.pool.get(
                        'hr.evaluation.interview')
                    int_id = hr_eval_inter_obj.create(
                        cr,
                        uid, {
                            'evaluation_id':
                            evaluation.id,
                            'survey_id':
                            phase.survey_id.id,
                            'date_deadline':
                            (dt.ISO.ParseAny(dt.now().strftime('%Y-%m-%d')) +
                             dt.RelativeDateTime(months=+1)
                             ).strftime('%Y-%m-%d'),
                            'user_id':
                            child.user_id.id,
                            'user_to_review_id':
                            evaluation.employee_id.id
                        },
                        context=context)
                    if phase.wait:
                        wait = True
                    if not wait:
                        hr_eval_inter_obj.survey_req_waiting_answer(
                            cr, uid, [int_id], context=context)

                    if (not wait) and phase.mail_feature:
                        body = phase.mail_body % {
                            'employee_name': child.name,
                            'user_signature': user.signature,
                            'eval_name': phase.survey_id.title,
                            'date': time.strftime('%Y-%m-%d'),
                            'time': time
                        }
                        sub = phase.email_subject
                        dest = [child.work_email]
                        if dest:
                            tools.email_send(src, dest, sub, body)

        self.write(cr, uid, ids, {'state': 'wait'}, context=context)
        return True
示例#12
0
 def set_start(self, cr, uid, ids, context={}):
     self.write(cr, uid, ids, {'state': 'ready'})
     cron_id = self.browse(cr, uid, ids[0], {}).cron_id.id
     nextcall = (now() + DateTime.RelativeDateTime(seconds=30)
                 ).strftime('%Y-%m-%d %H:%M:%S')
     self.pool.get('ir.cron').write(cr, uid, cron_id, {
         'numbercall': 1,
         'active': True,
         'nextcall': nextcall
     })
     return True
示例#13
0
 def ISO_time( self, info, buffer):
     """Interpret the ISO time format"""
     (tag, left, right, sublist) = info
     set = {}
     for item in sublist:
         set[ item[0] ] = dispatch( self, item, buffer)
     return DateTime.RelativeDateTime(
         hour = set.get("hour") or 0,
         minute = set.get("minute") or 0,
         second = set.get("second") or 0,
     )
示例#14
0
 def from_interval(buf):
     microseconds, days, months = unpack_interval(buf)
     seconds = round(microseconds / pgtype.usec_mul, 2)
     # Unfortunately, we can't use divmod here...
     hours = int(seconds / 3600.0)
     seconds = math.fmod(seconds, 3600.0)
     minutes = int(seconds / 60.0)
     seconds = math.fmod(seconds, 60.0)
     years = int(months / 12.0)
     months = int(math.fmod(months, 12))
     return DateTime.RelativeDateTime(years, months, days, hours, minutes,
                                      seconds)
示例#15
0
 def to_dobprec(self, now=None):
     """
     Given an integer age and unit code, return a DOB & precision
     """
     if self.units == 'y':
         age = DateTime.RelativeDateTime(years=self.age)
         prec = PREC_YEAR
     elif self.units == 'm':
         age = DateTime.RelativeDateTime(months=self.age)
         prec = PREC_MONTH
     elif self.units == 'w':
         age = DateTime.RelativeDateTime(weeks=self.age)
         prec = PREC_WEEK
     elif self.units == 'd':
         age = DateTime.RelativeDateTime(days=self.age)
         prec = PREC_DAY
     else:
         raise AssertionError('Bad age units: %s' % self.units)
     if now is None:
         now = datetime.now()
     return now - age, prec
示例#16
0
def _until_timespec_mx(curticks, hr, min, sec):
    """
    >>> t=time.strptime('200212312359', '%Y%m%d%H%M')
    >>> u=_until_timespec_mx(time.mktime(t), 4, 20, 32)
    >>> time.ctime(u)
    'Wed Jan  1 04:20:32 2003'
    """
    reldate = DateTime.RelativeDateTime(hour=hr, minute=min, second=sec)
    curdate = DateTime.DateTimeFromTicks(curticks)
    huh = curdate + reldate
    if huh <= curdate:
        huh = huh + 1
    return huh.ticks()
示例#17
0
 def onchange_evaluation_plan_id(self,
                                 cr,
                                 uid,
                                 ids,
                                 evaluation_plan_id,
                                 evaluation_date,
                                 context={}):
     evaluation_date = evaluation_date or False
     evaluation_plan_obj = self.pool.get('hr_evaluation.plan')
     if evaluation_plan_id:
         flag = False
         evaluation_plan = evaluation_plan_obj.browse(cr,
                                                      uid,
                                                      [evaluation_plan_id],
                                                      context=context)[0]
         if not evaluation_date:
             evaluation_date = (
                 dt.ISO.ParseAny(dt.now().strftime('%Y-%m-%d')) +
                 dt.RelativeDateTime(months=+evaluation_plan.month_first)
             ).strftime('%Y-%m-%d')
             flag = True
         else:
             if (dt.ISO.ParseAny(evaluation_date) + dt.RelativeDateTime(
                     months=int(evaluation_plan.month_next))
                 ).strftime('%Y-%m-%d') <= time.strftime("%Y-%m-%d"):
                 evaluation_date = (
                     dt.ISO.ParseAny(evaluation_date) +
                     dt.RelativeDateTime(months=+evaluation_plan.month_next)
                 ).strftime('%Y-%m-%d')
                 flag = True
         if ids and flag:
             self.pool.get("hr_evaluation.evaluation").create(
                 cr,
                 uid, {
                     'employee_id': ids[0],
                     'plan_id': evaluation_plan_id
                 },
                 context=context)
     return {'value': {'evaluation_date': evaluation_date}}
示例#18
0
    def compute_periods(self, company, date, periods_number=5):
        """ return the timeranges to display. This is the 5 last timesheets (depending on the timerange defined for the company) """

        periods = []

        (last_start_date,
         last_end_date) = self.get_last_period_dates(company, date)

        for cpt in range(periods_number):
            #find the delta between last_XXX_date to XXX_date
            if company.timesheet_range == 'month':
                delta = DateTime.RelativeDateTime(months=-cpt)
            elif company.timesheet_range == 'week':
                delta = DateTime.RelativeDateTime(weeks=-cpt)
            elif company.timesheet_range == 'year':
                delta = DateTime.RelativeDateTime(years=-cpt)

            start_date = last_start_date + delta
            end_date = last_end_date + delta
            periods.append((start_date, end_date))

        return periods
示例#19
0
    def get_last_period_dates(self, company, date):
        """ return the start date and end date of the last period to display """

        # return the first day and last day of the month
        if company.timesheet_range == 'month':
            start_date = DateTime.Date(date.tm_year, date.tm_mon, 1)
            end_date = start_date + DateTime.RelativeDateTime(months=+1)
        #return the first and last days of the week
        elif company.timesheet_range == 'week':
            start_date = DateTime.Date(
                date.tm_year, date.tm_mon,
                date.tm_mday) + DateTime.RelativeDateTime(
                    weekday=(DateTime.Monday, 0))
            end_date = DateTime.Date(date.tm_year, date.tm_mon,
                                     date.tm_mday) + DateTime.RelativeDateTime(
                                         weekday=(DateTime.Sunday, 0))
        # return the first and last days of the year
        elif company.timesheet_range == 'year':
            start_date = DateTime.Date(date.tm_year, 1, 1)
            end_date = DateTime.Date(date.tm_year, 12, 31)

        return (start_date, end_date)
示例#20
0
def _old_test():
    print "testing old functions..."
    print timeConv('1h20m3s')
    print time.asctime(time.gmtime(datestrToSeconds('10:20:03')))
    print time.asctime(time.gmtime(datestrToSeconds('2/11/1999 10:20:03')))
    print currentDate()
    print "testing new functions..."
    cur = DateTime.now()
    print cur.ticks(), cur
    for test in [
            ':15',
        (':15', ':30', ':45', ':00', '06:00'),
            '00:15',
            '23:59',
            '23:59:59',
            '2007-05-06',
            '2007-05-06 23:59',
            '2007-05-06 23:59:59',
            cur + 0.5,
            DateTime.RelativeDateTime(minute=15),
            DateTime.RelativeDateTime(minute=00),
    ]:
        scs = None
        try:
            scs = convertUntil(test)
            status = 'good'
        except PastTimeException:
            status = 'time is past'
        except TimeException:
            status = 'bad argument'
        print test
        print '-->', scs,
        if scs is not None:
            print DateTime.DateTimeFrom(scs),
        else:
            print "None",
        print status
    def _do_process(self, cr, uid, data, context):
        pool = pooler.get_pool(cr.dbname)

        res = {}
        res['name'] = 'Scheduled Migration, ' + time.strftime(
            '%Y-%m-%d %H:%M:%S')
        res['nextcall'] = (
            now() +
            DateTime.RelativeDateTime(minutes=1)).strftime('%Y-%m-%d %H:%M:%S')
        res['priority'] = 5
        res['numbercall'] = 1
        res['interval_type'] = 'minutes'
        res['interval_number'] = 1
        res['model'] = 'migration.schedule'
        #res['args'] = data['form'][0][2]
        res['function'] = '_import_data'

        action_ids = []
        name_list = []
        for act in pool.get("migration.import_models").read(
                cr, uid, data['form']['import_model_ids'][0][2],
            ['name', 'actions']):
            name_list.append(act['name'][1])
            action_ids += act['actions']
        name = ', '.join(name_list)
        if len(name) > 64:
            name = name[:61] + '...'

        cron_id = pool.get('ir.cron').create(cr, uid, res)
        id = pool.get('migration.schedule').create(
            cr, uid, {
                'name': name,
                'import_model_ids': data['form']['import_model_ids'],
                'actions_ids': [(6, 0, action_ids)],
                'cron_id': cron_id,
                'print_log': data['form']['print_log']
            })
        pool.get('ir.cron').write(
            cr, uid, cron_id,
            {'args': [id, data['form']['import_model_ids'][0][2]]})
        return {
            'domain': "[('id','=', " + str(id) + ")]",
            'name': 'Scheduled Migrations',
            'view_type': 'form',
            'view_mode': 'tree,form',
            'res_model': 'migration.schedule',
            'view_id': False,
            'type': 'ir.actions.act_window'
        }
示例#22
0
    class MxInterpreter(DispatchProcessor):
        """Interpret a parsed ISO_date_time_loose in GMT/UTC time or localtime
		"""
        int = numbers.IntInterpreter()
        offset_minute = offset_hour = year = month = day = hour = minute = int

        float = numbers.FloatInterpreter()
        second = float

        def __init__(
            self,
            inputLocal=1,
            returnLocal=1,
        ):
            self.inputLocal = inputLocal
            self.returnLocal = returnLocal

        dateName = 'ISO_date_loose'
        timeName = 'ISO_time_loose'

        def ISO_date_time_loose(self, (tag, left, right, sublist), buffer):
            """Interpret the loose ISO date + time format"""
            set = singleMap(sublist, self, buffer)
            base, time, offset = (
                set.get(self.dateName),
                set.get(self.timeName)
                or DateTime.RelativeDateTime(hour=0, minute=0, second=0),
                set.get("offset"),
            )
            base = base + time
            offset = set.get("offset")
            if offset is not None:
                # an explicit timezone was entered, convert to gmt and return as appropriate...
                gmt = base - offset
                if self.returnLocal:
                    return gmt.localtime()
                else:
                    return gmt
            # was in the default input locale (either gmt or local)
            if self.inputLocal and self.returnLocal:
                return base
            elif not self.inputLocal and not self.returnLocal:
                return base
            elif self.inputLocal and not self.returnLocal:
                # return gmt from local...
                return base.gmtime()
            else:
                return base.localtime()
示例#23
0
class huissier_partenaire(osv.osv):
    _inherit = 'res.partner'
    _columns = {
        'image': fields.binary('Image'),
        'date_creation': fields.date(u'Création badge'),
        'date_expiration': fields.date('Expiration badge')
    }
    _defaults = {
        'date_creation':
        lambda *args: time.strftime('%Y-%m-%d'),
        'date_expiration':
        lambda *args: (DateTime.now() + DateTime.RelativeDateTime(years=+1)).
        strftime('%Y-%m-%d'),
        'ref':
        lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(
            cr, uid, 'res.partner'),
    }
示例#24
0
    def user_request_guest(self, operator, nr, date, groupname, comment):
        """ Request a number of guest users for a certain time. """
        # date checking
        start_date, end_date = self._parse_date_from_to(date)
        today = DateTime.today()
        if start_date < today:
            raise CerebrumError("Start date shouldn't be in the past")
        # end_date in allowed interval?
        if end_date < start_date:
            raise CerebrumError("End date can't be earlier than start_date")
        max_date = start_date + DateTime.RelativeDateTime(
            days=cereconf.GUESTS_MAX_PERIOD)
        if end_date > max_date:
            raise CerebrumError("End date can't be later than %s" %
                                max_date.date)
        if not nr.isdigit():
            raise CerebrumError(
                "'Number of accounts' requested must be a number;"
                " %r isn't." % nr)

        try:
            self.ba.can_request_guests(operator.get_entity_id(), groupname)
        except Errors.NotFoundError:
            raise CerebrumError("Group %r not found" % groupname)
        owner = self.util.get_target(groupname, default_lookup="group")
        try:
            user_list = self.bgu.request_guest_users(
                int(nr),
                end_date,
                comment,
                owner.entity_id,
                operator.get_entity_id())
            for uname, comment, e_id, passwd in user_list:
                operator.store_state("new_account_passwd",
                                     {'account_id': e_id,
                                      'password': passwd})

            ret = "OK, reserved guest users:\n%s\n" % \
                  self._pretty_print([x[0] for x in user_list])
            ret += "Please use misc list_passwords to view the passwords\n"
            ret += "or use misc print_passwords to print the passwords."
            return ret
        except GuestAccountException as e:
            raise CerebrumError(e)
示例#25
0
 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
示例#26
0
    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'],
        }
示例#27
0
			set = {}
			for item in sublist:
				set[ item[0] ] = dispatch( self, item, buffer)
			return DateTime.DateTime(
				set.get("year") or now().year,
				set.get("month") or 1,
				set.get("day") or 1,
			)
		def ISO_time( self, (tag, left, right, sublist), buffer):
			"""Interpret the ISO time format"""
			set = {}
			for item in sublist:
				set[ item[0] ] = dispatch( self, item, buffer)
			return DateTime.RelativeDateTime(
				hour = set.get("hour") or 0,
				minute = set.get("minute") or 0,
				second = set.get("second") or 0,
			)

		integer = numbers.IntInterpreter()
		second =  offset_minute = offset_hour = year = month = day = hour =minute =integer
		
		def offset( self, (tag, left, right, sublist), buffer):
			"""Calculate the time zone offset as a date-time delta"""
			set = singleMap( sublist, self, buffer )
			direction = set.get('offset_sign',1)
			hour = set.get( "hour", 0)
			minute = set.get( "minute", 0)
			delta = DateTime.DateTimeDelta( 0, hour*direction, minute*direction)
			return delta
			
示例#28
0
 def rdt(**kwargs):
     return now + DateTime.RelativeDateTime(hour=12, **kwargs)
示例#29
0
 def setStartDate(self, date):
     self.dtbegin = DateTime.DateTime(date.year, date.month, date.day)
     self.dt = DateTime.DateTime(date.year, date.month, date.day)
     self.dtend = self.dt + DateTime.RelativeDateTime(years=1)
示例#30
0
 </source>
 <fixed field="locality" value="NSW" />
 <ignore field="street_address" />
 <form name="sars_exposure" version="1">
  <source field="Contact_duration" src="Duration" />
  <source field="Close_contact" src="Contact" />
  <source field="Contact_date_first" src="Date" />
  <multivalue field="Contact_favourite_food" src="Likes" delimiter="/" />
 </form>
</importrules>
'''

# Need to reproduce the effects of casemgr.person DOB processing, as well as
# cocklebur.datetime, cocklebur.dbobj.column_describer and a round-trip through
# postgres - urgh.
truncate_tod = DateTime.RelativeDateTime(hour=0, minute=0, second=0)
three_years = DateTime.RelativeDateTime(years=3)
age3y = DateTime.now() - three_years - truncate_tod
four_months = DateTime.RelativeDateTime(months=4)
age4m = DateTime.now() - four_months - truncate_tod

class DataImpTest(testcommon.AppTestCase):

    create_tables = testcommon.AppTestCase.create_tables + (
        'nicknames',
        'person_phonetics',
        'syndrome_case_status',
        'syndrome_demog_fields',
        'import_defs',
    )