Exemple #1
0
class MrpWordkorderShiftsTimeHistory(models.Model):

	_name="mrp.workorder.rm.shifts.date.history"
	
	shift_id = fields.Many2one('mrp.workorder.rm.shifts','Shift No.')
	start_time = fields.Datetime('Start Time')
	new_start_time = fields.Datetime('New Date')
	end_time = fields.Datetime('End Time')
	date = fields.Datetime('Previous Time')
    	
    	@api.multi
    	def Process(self):
    		for res in self:
    		     if res.shift_id:
    			
    			second=res.shift_id.hours*3600
    			ntime=datetime.strptime(res.new_start_time,'%Y-%m-%d %H:%M:%S')+timedelta(seconds=second)
    			res.shift_id.start_time=res.new_start_time
			res.shift_id.end_time=ntime
			
			rawseconds=0
			rawtime=False
			workorder=False
			self_process_ids=self.env['mrp.production.workcenter.line'].search([
						('production_id','=',res.shift_id.workorder_id.production_id.id),
						('workcenter_id','=',res.shift_id.workorder_id.workcenter_id.id)])
			for self_process in self_process_ids:
				workorder=self.env['mrp.production.workcenter.line'].search([('workcenter_id.process_id.process_type','=','raw'),('next_order_id','=',self_process.id)])
				if workorder:
					break
			if workorder:
				rawseconds=workorder.hour*3600
				rawtime=datetime.strptime(res.new_start_time,'%Y-%m-%d %H:%M:%S')-timedelta(hours=6)
				res.shift_id.raw_end_time=rawtime
				res.shift_id.raw_start_time=rawtime-timedelta(seconds=rawseconds)
					
			if res.shift_id.status in ('draft','request'):
				rtime=datetime.strptime(res.new_start_time,'%Y-%m-%d %H:%M:%S')-timedelta(hours=2)
    				res.shift_id.date=rtime
			
			next_shift_id=res.shift_id.next_shift_id if res.shift_id else False
			while next_shift_id:
				next_shift_id.start_time=ntime
				ntime = ntime + timedelta(seconds=second)
				next_shift_id.end_time=ntime
				print "EEEEEEEEee",next_shift_id.start_time,next_shift_id.end_time
				if workorder:
					print "11111111",rawtime,rawseconds
					next_shift_id.raw_start_time=rawtime
					rawtime = rawtime + timedelta(seconds=rawseconds)
					next_shift_id.raw_end_time=rawtime
				next_shift_id = next_shift_id.next_shift_id
    		     
		return True
			
class GolValidatorRetention(osv.Model):
    _name = 'gol.validator.retention'
    _description = u'descripcion modulo'
    #Decalaracion de campos
    initialCorrelative = fields.Char('Correlativo inicial',
                                     size=50,
                                     required=True)
    correlativeEnd = fields.Char('Correlativo Final', size=50, required=True)
    broadcastDate = fields.Datetime('Fecha de Emisión')
    expirationDate = fields.Datetime('Fecha de Caducidad')
    authorizationNumber = fields.Char('Número de Autorización')
    idRulesRetention = fields.Many2one('res.partner', 'Reglas Retención')
class achievements(models.Model):
    _name = 'achievements'
    _rec_name = 'achieve'

    achieve = fields.Text('Achievements : ')
    choose_student = fields.Many2one('student', 'Choose Student :')
    s_date = fields.Datetime('Start Date:')
    e_date = fields.Datetime('End Date:')
    time = fields.Char('Time Difference:')
    state = fields.Selection([('start', 'Start'), ('resume', 'Resume'),
                              ('stop', 'Stop')])

    #achieve = fields.Many2many('subject','subject_teacher_rel','subject_id','teacher_id')

    @api.multi
    def start_state(self):
        st = datetime.now()

        self.write({
            'state': 'start',
            's_date': st,
        })

    @api.multi
    def resume_state(self):
        self.write({
            'state': 'resume',
        })

    @api.one
    def stop_state(self):

        st = datetime.strptime(str(self.s_date), "%Y-%m-%d %H:%M:%S")
        print "dt=================", st
        # dt1 = str(dt)
        # print "dt1=================",dt1
        et = datetime.now()
        print "et_et ==========================", et
        # et = datetime.strptime(str(et_et),"%Y-%m-%d %H:%M:%S")

        diff = et - st
        print "diff===================", diff

        self.write({
            'state': 'stop',
            'e_date': et,
            'time': diff,
        })
Exemple #4
0
class MixedModel(models.Model):
    _name = 'test_new_api.mixed'

    number = fields.Float(digits=(10, 2), default=3.14)
    date = fields.Date()
    now = fields.Datetime(compute='_compute_now')
    lang = fields.Selection(string='Language', selection='_get_lang')
    reference = fields.Reference(string='Related Document',
        selection='_reference_models')
    comment1 = fields.Html(sanitize=False)
    comment2 = fields.Html(sanitize=True, strip_classes=False)
    comment3 = fields.Html(sanitize=True, strip_classes=True)
    comment4 = fields.Html(sanitize=True, strip_style=True)

    currency_id = fields.Many2one('res.currency', default=lambda self: self.env.ref('base.EUR'))
    amount = fields.Monetary()

    @api.one
    def _compute_now(self):
        # this is a non-stored computed field without dependencies
        self.now = fields.Datetime.now()

    @api.model
    def _get_lang(self):
        return self.env['res.lang'].get_installed()

    @api.model
    def _reference_models(self):
        models = self.env['ir.model'].search([('state', '!=', 'manual')])
        return [(model.model, model.name)
                for model in models
                if not model.model.startswith('ir.')]
Exemple #5
0
class MixedModel(models.Model):
    _name = 'test_new_api.mixed'

    number = fields.Float(digits=(10, 2), default=3.14)
    date = fields.Date()
    now = fields.Datetime(compute='_compute_now')
    lang = fields.Selection(string='Language', selection='_get_lang')
    reference = fields.Reference(string='Related Document',
                                 selection='_reference_models')

    @api.one
    def _compute_now(self):
        # this is a non-stored computed field without dependencies
        self.now = fields.Datetime.now()

    @api.model
    def _get_lang(self):
        langs = self.env['res.lang'].search([])
        return [(lang.code, lang.name) for lang in langs]

    @api.model
    def _reference_models(self):
        models = self.env['ir.model'].search([('state', '!=', 'manual')])
        return [(model.model, model.name) for model in models
                if not model.model.startswith('ir.')]
Exemple #6
0
class poi_report_kardex(models.Model):
    _name = 'poi.stock.kardex.analysis'
    _description = "Kardex Analysis"
    _auto = False

    price_unit = fields.Float(string='Costo del movimiento (Bs)')
    date = fields.Datetime(string='Fecha',readonly=True)
    string_date = fields.Char('Fecha', readonly=True)
    product_id= fields.Many2one('product.product',string='Producto', readonly=True)
    location_id= fields.Many2one('stock.location',string='Location')
    stock_to_date= fields.Float(string='Stock a la Fecha')

    def _select(self, select=False):
        if select:
            select_str= select
        else:
            select_str = """
SELECT
	product_id,
	location_id,
	precio as price_unit,
	date,
	'['||coalesce(origin,'')||']'||cast(cast(date as timestamp) + c_interval as varchar) as string_date,
	cantidad_en_fecha as stock_to_date
FROM poi_report_kardex_inv prk
LEFT JOIN
	(
		SELECT id, cast(substring(tz_offset from 1 for 3)||':'||substring(tz_offset from 4 for 2) as interval) as c_interval FROM res_company
	) as company_tz
	ON company_tz.id = prk.company_id

ORDER BY date
        """
        return select_str

    def init(self, cr, select=False, mlc=False, mlr=False):
        table = "poi_stock_kardex_analysis"
        cr.execute("""
            SELECT table_type
            FROM information_schema.tables
            WHERE table_name = '%s';
            """ % table)
        vista = cr.fetchall()
        for v in vista:
            if v[0] == 'VIEW':
                cr.execute("""
                    DROP VIEW IF EXISTS %s;
                    """ % table);
        cr.execute("""

            DROP MATERIALIZED VIEW IF EXISTS %s;
            CREATE MATERIALIZED VIEW %s as ((
            SELECT row_number() over() as id, *
                FROM ((
                    %s
                )) as asd
            ))""" % (table, table, self._select(select)))
Exemple #7
0
class GolDocumentHeader(osv.Model):
    _name = 'gol.document.header'
    _description = u'descripcion modulo'
    #Decalaracion de campos
    documentType=fields.Many2one('gol.document.type','Tipo de Documento')
    correlative=fields.Char('Correlativo',required=False)
    date=fields.Datetime('Fecha',default=datetime.now())    
    state = fields.Selection([('active','Activo'),
                                        ('annulled','Anulado')],'Estado del Comprobante',
                                        default ='active', required=True)

    gloss=fields.Text('Glosa')
Exemple #8
0
class student(models.Model):
    _name = 'teacher'

    name = fields.Char('Name', required=1)
    address = fields.Text('Address')
    pincode = fields.Char('Pincode')
    telephone = fields.Char('Telephone')
    birthdate = fields.Date('Birthdate')
    joindate = fields.Datetime('Join Date')
    active = fields.Boolean('Active', default=1)

    def active_action(self):
        print self
Exemple #9
0
class student(models.Model):
    _name = 'student'

    name = fields.Char('Name', required=1)
    address = fields.Text('Address')
    pincode = fields.Char('Pincode')
    telephone = fields.Char('Telephone')
    birthdate = fields.Date('Birthdate')
    joindate = fields.Datetime('Join Date')
    roll_no = fields.Integer('Roll Number')
    fees_amt = fields.Float('Fees')
    active = fields.Boolean('Active', default=1)
    stand = fields.Selection([('one', 'One'), ('two', 'Two'),
                              ('three', 'Three'), ('four', 'Four')], 'Stand.')
class employee_information(models.Model):
    _name = 'employee.information'

    emp_id = fields.Integer('Employee_ID', required=True)
    emp_name = fields.Char('Employee Name', required=True)
    city = fields.Char('City')
    pincode = fields.Integer('Pincode')
    #active = fields.Boolean('Active',  default=1)
    working_address = fields.Text('Working Address')
    work_email =  fields.Char('Work Email')
    work_phone = fields.Char('Work Phone')
    work_mobile = fields.Integer('Work Mobile')
    office_location = fields.Char('Office Location')
    company_code = fields.Char('Company Code')
    nationality = fields.Char('Nationality')
    education_level = fields.Char('Education Level')
    college_name = fields.Char('College Name')
    birth = fields.Date('Birth')
    date_of_birth = fields.Datetime('Date Of Birth' , required=True)
class born_sale_order(models.Model):
    _inherit = 'sale.order'

    sale_category = fields.Selection([
        ('weixin', u'微信商城'),
        ('online', u'在线销售'),
        ('normal', u'普通销售'),
    ],
                                     default='normal',
                                     string=u'状态',
                                     help=u'销售类型')
    is_weixin_unlick = fields.Boolean(u'微信删除订单', help=u"微信删除订单", default=False)
    openid = fields.Char('OPENID', size=255, help="OPENID")
    weixin_user_id = fields.Many2one('born.weixin.users', u'关注者', help=u"关注者")
    out_trade_no = fields.Char(u'微信对应订单号', size=255, help=u"微信对应订单号")
    transaction_id = fields.Char(u'微信支付流水号', size=255, help=u"微信支付流水号")
    is_lottery = fields.Boolean(u'是否已经抽奖', help=u'是否已经抽奖', default=False)
    spread_id = fields.Many2one('born.spread', u'活动编号')
    payment_date = fields.Datetime(u'付款日期')
Exemple #12
0
class sale_order_line(models.Model):
    _inherit = 'sale.order.line'

    
    line_ship_dt = fields.Date(string='Ship Date',default=fields.date.today())
    line_planned_date = fields.Datetime(string='Planned date')
    line_sc_date = fields.Date(string='Schedule Date')
    
    @api.onchange('line_sc_date')
    @api.multi
    def onchange_line_sc_date(self):
        if self.line_sc_date :
            time=datetime.now().time()
            current_time=(time.strftime("%H:%M:%S"))
            self.line_planned_date=self.line_sc_date +' '+ current_time
        elif not self.line_sc_date:
            self.line_planned_date = False

    @api.onchange('line_ship_dt')
    @api.multi
    def onchange_line_ship_dt(self):
        if self.line_ship_dt:
            new_date = self.order_id.date_order
            updated_date = datetime.strptime(new_date, DEFAULT_SERVER_DATETIME_FORMAT).date()
            update_date = datetime.strptime(self.line_ship_dt, DEFAULT_SERVER_DATE_FORMAT).date()
            delay = abs(updated_date-update_date).days
            self.delay=delay
    
    @api.onchange('delay')
    @api.multi
    def onchange_line_delay(self):
        date_order = self.order_id.date_order
        updated_date = datetime.strptime(date_order, DEFAULT_SERVER_DATETIME_FORMAT).date()
        line_ship_date = updated_date + timedelta(days=self.delay)
        self.line_ship_dt = line_ship_date
               
    def default_get(self, cr, uid, fields, context=None):
        if context is None: context = {}
        res = super(sale_order_line, self).default_get(cr, uid, fields, context=context)
        if context.get('line_ship_dt'):
            res.update({'line_ship_dt': context.get('line_ship_dt')})
        return res
Exemple #13
0
class teacher(models.Model):
    _name = 'teacher'

    name = fields.Char('Name', required=1)
    address = fields.Text('Address')
    pincode = fields.Char('Pincode')
    telephone = fields.Char('Telephone')
    birthdate = fields.Date('Birthdate')
    joindate = fields.Datetime('Join Date')
    subject_ids = fields.Many2many('subject','teacher_subject_rel','teacher_id','subject_id','Subjects')
    active = fields.Boolean('Active', default=1)

    @api.multi
    def active_action(self):
        if self.active:
            self.write({'active': False})
        elif not self.active:
            self.write({'active': True})
        else:
            self.write({'active': True})
        print "Is Active", self.active
Exemple #14
0
class teacher(models.Model):
    _name = 'teacher'

    name = fields.Char('Name', required=1)
    user_id = fields.Many2one('res.users', 'Select User:'******'Address')
    pincode = fields.Char('Pincode')
    telephone = fields.Char('Telephone')
    birthdate = fields.Date('Birthdate')
    joindate = fields.Datetime('Join Date')
    ID_NO = fields.Integer('ID_NO')
    #fees_amt = fields.Float('Fees')
    active = fields.Boolean('Active', default=1)
    Experience = fields.Selection([('one', 'One'), ('two', 'Two'),
                                   ('three', 'Three'), ('four', 'Four')],
                                  'Stand.')

    student_id = fields.Many2one('student', 'Student ID :')
    # subject = fields.Many2many('subject','subject_teacher_rel','sub_id','teacher_id')
    # Choose_subject = fields.One2many('subject','choose_teacher','Choose Teacher :')
    teacher_stud = fields.One2many('student', 'choose_teacher',
                                   'Teacher Student Relation:')
Exemple #15
0
class maintenance_timeofuse_report(osv.osv):
    _name = "maintenance.timeofuse.report"
    _description = "Maintenance Time of Use Analysis"
    _auto = False

    #name = fields.Char('Year', required=False,readonly=True)
    #brand = fields.Many2one('maintenance.element.brand','Brand', readonly=True)
    installation_id = fields.Many2one('maintenance.installation',
                                      'Installation',
                                      readonly=True)
    nbr = fields.Integer('# of Counters', readonly=True)
    #date_start = fields.Datetime('Start Date', readonly=True)
    #date_end = fields.Datetime('End Date', readonly=True)
    use = fields.Integer('Use')
    #failure_type_id = fields.Many2one('maintenance.failure.type','Failure Type', readonly=True)
    element_id = fields.Many2one('maintenance.element',
                                 'Element concerned',
                                 readonly=True)
    partner_id = fields.Many2one('res.partner', 'Partner', readonly=True)
    date = fields.Datetime('Date', readonly=True)
    time_of_use = fields.Integer('Time of Use', readonly=True)
    previous_date = fields.Datetime('Previous Date', readonly=True)
    previous_time_of_use = fields.Integer('Previous Time of Use',
                                          readonly=True)

    #time_planned = fields.Float('Time Planned',readonly=True)

    def init(self, cr):
        tools.sql.drop_view_if_exists(cr, 'maintenance_timeofuse_report')
        cr.execute("""
            DROP VIEW IF EXISTS maintenance_timeofuse_report;
            CREATE view maintenance_timeofuse_report as
                            SELECT min(req1.maintenance_element_id) AS id,
                        ( SELECT 1) AS nbr,
                        rp.id AS partner_id,
                        mi.id AS installation_id,
                        req1.maintenance_element_id AS element_id,
                        req1.time_of_use,
                        req1.date,
                        req1.previous_time_of_use,
                        req1.previous_date,
                        (req1.time_of_use - req1.previous_time_of_use)::integer AS use
                       FROM ( SELECT mit.maintenance_element_id,
                                mit.time_of_use,
                                mit.date,
                                ( SELECT mit1.time_of_use
                                       FROM maintenance_intervention_timeofuse mit1
                                      WHERE mit1.date < mit.date AND mit1.maintenance_element_id = mit.maintenance_element_id AND mit1.time_of_use IS NOT NULL
                                      ORDER BY mit1.date DESC
                                     LIMIT 1) AS previous_time_of_use,
                                ( SELECT mit1.date
                                       FROM maintenance_intervention_timeofuse mit1
                                      WHERE mit1.date < mit.date AND mit1.maintenance_element_id = mit.maintenance_element_id AND mit1.time_of_use IS NOT NULL
                                      ORDER BY mit1.date DESC
                                     LIMIT 1) AS previous_date
                               FROM maintenance_intervention_timeofuse mit
                              WHERE mit.time_of_use IS NOT NULL
                              GROUP BY mit.maintenance_element_id, mit.date, mit.time_of_use
                              ORDER BY mit.maintenance_element_id, mit.date) req1
                         JOIN maintenance_element me ON me.id = req1.maintenance_element_id
                         JOIN maintenance_installation mi ON me.installation_id = mi.id
                         JOIN res_partner rp ON rp.id = mi.partner_id
                      GROUP BY element_id, mi.id, rp.id, me.id, req1.time_of_use, req1.date, req1.previous_time_of_use, req1.previous_date
                    ORDER BY element_id
                      ;

        """)
class dym_journal_memorial_consol(models.Model):
    _name = 'dym.journal.memorial.consol'
    _description = 'Journal Memorial Consolidation'

    STATE_SELECTION = [('draft', 'Draft'),
                       ('waiting_for_approval', 'Waiting For Approval'),
                       ('confirm', 'Confirmed'), ('cancel', 'Cancelled')]

    @api.one
    @api.depends('journal_memorial_line.amount')
    def _compute_debit(self):
        total_debit = 0.0
        for x in self.journal_memorial_line:
            if x.type == 'Dr':
                total_debit += x.amount
        self.total_debit = total_debit

    @api.one
    @api.depends('journal_memorial_line.amount')
    def _compute_credit(self):
        total_credit = 0.0
        for x in self.journal_memorial_line:
            if x.type == 'Cr':
                total_credit += x.amount
        self.total_credit = total_credit

    @api.cr_uid_ids_context
    def _get_default_branch(self, cr, uid, ids, context=None):
        user_obj = self.pool.get('res.users')
        user_browse = user_obj.browse(cr, uid, uid)
        branch_ids = False
        branch_ids = user_browse.branch_ids and len(
            user_browse.branch_ids
        ) == 1 and user_browse.branch_ids[0].id or False
        return branch_ids

    @api.cr_uid_ids_context
    def get_group_company(self, cr, uid, ids, context=None):
        user_obj = self.pool.get('res.users').browse(cr, SUPERUSER_ID, uid)
        company = user_obj.company_id
        while company.parent_id:
            company = company.parent_id
        return company

    @api.cr_uid_ids_context
    def _get_default_periode(self, cr, uid, ids, context=None):
        periode_obj = self.pool.get('account.period')
        company = self.get_group_company(cr, uid, [])
        periode_now = periode_obj.search(cr, uid, [
            ('date_start', '<=', datetime.today()),
            ('date_stop', '>=', datetime.today()),
            ('company_id', '=', company.id),
        ])
        periode_id = False
        if periode_now:
            periode_id = periode_obj.browse(cr, uid, periode_now).id
        return periode_id

    name = fields.Char(string='No')
    branch_id = fields.Many2one('dym.branch',
                                string='Branch',
                                required=True,
                                default=_get_default_branch)
    date = fields.Date(string="Date",
                       required=True,
                       readonly=True,
                       default=fields.Date.context_today)
    periode_id = fields.Many2one('account.period', string='Periode')
    division = fields.Selection([('Unit', 'Showroom'),
                                 ('Sparepart', 'Workshop'),
                                 ('Umum', 'General'), ('Finance', 'Finance')],
                                string='Division',
                                default='Unit',
                                required=True,
                                change_default=True,
                                select=True)
    auto_reverse = fields.Boolean(string="Auto Reverse ?")
    journal_memorial_line = fields.One2many('dym.journal.memorial.consol.line',
                                            'journal_memorial_id')
    state = fields.Selection(STATE_SELECTION,
                             string='State',
                             readonly=True,
                             default='draft')
    total_debit = fields.Float(string='Total Debit',
                               digits=dp.get_precision('Account'),
                               store=True,
                               compute='_compute_debit')
    total_credit = fields.Float(string='Total Credit',
                                digits=dp.get_precision('Account'),
                                store=True,
                                compute='_compute_credit')
    move_id = fields.Many2one('account.move.consol',
                              string='Account Entry',
                              copy=False)
    move_ids = fields.One2many('account.move.line.consol',
                               related='move_id.line_id',
                               string='Journal Items',
                               readonly=True)
    auto_reverse_move_id = fields.Many2one('account.move.consol',
                                           string='Account Entry',
                                           copy=False)
    auto_reverse_move_ids = fields.One2many(
        'account.move.line.consol',
        related='auto_reverse_move_id.line_id',
        string='Auto Reverse Journal Items',
        readonly=True)
    prev_periode = fields.Boolean(string="Prev Periode")
    current_periode_id = fields.Many2one('account.period',
                                         string='Current Periode',
                                         default=_get_default_periode)
    reverse_periode_id = fields.Many2one('account.period',
                                         string='Reverse Periode')
    description = fields.Char(string='Description')
    confirm_uid = fields.Many2one('res.users', string="Confirmed by")
    confirm_date = fields.Datetime('Confirmed on')
    approval_ids = fields.One2many('dym.approval.line',
                                   'transaction_id',
                                   string="Table Approval",
                                   domain=[('form_id', '=', _name)])
    approval_state = fields.Selection([('b', 'Belum Request'),
                                       ('rf', 'Request For Approval'),
                                       ('a', 'Approved'), ('r', 'Reject')],
                                      'Approval State',
                                      readonly=True,
                                      default='b')
    code = fields.Selection([(' ', ' '), ('cancel', 'Cancel')],
                            string="Code",
                            default=' ')
    state_periode = fields.Selection(related="periode_id.state")
    cancel_refered = fields.Many2one('dym.journal.memorial.consol')
    konsolidasi = fields.Selection([('Umum', 'General'),
                                    ('Konsolidasi', 'Konsolidasi')],
                                   string='Type',
                                   default='Umum',
                                   change_default=True,
                                   select=True)
    partner_id = fields.Many2one('res.partner', string="Partner")

    @api.onchange('periode_id')
    def onchange_periode(self):
        if self.periode_id:
            if self.periode_id.date_stop > self.date:
                self.prev_periode = True
            else:
                self.prev_periode = False
            self.reverse_periode_id = self.env['account.period'].search(
                [('date_start', '>', self.periode_id.date_stop),
                 ('company_id', '=', self.periode_id.company_id.id)],
                order="date_start asc",
                limit=1)

    @api.cr_uid_ids_context
    def fields_view_get(self,
                        cr,
                        uid,
                        view_id=None,
                        view_type='form',
                        context=None,
                        toolbar=False,
                        submenu=False):
        if not context: context = {}
        res = super(dym_journal_memorial_consol,
                    self).fields_view_get(cr,
                                          uid,
                                          view_id=view_id,
                                          view_type=view_type,
                                          context=context,
                                          toolbar=toolbar,
                                          submenu=submenu)
        periode_obj = self.pool.get('account.period')
        kolek_periode = []
        company = self.get_group_company(cr, uid, [])
        user_obj = self.pool.get('res.users').browse(cr, uid, uid)
        periode_now = periode_obj.search(cr, uid, [
            ('date_start', '<=', datetime.today()),
            ('date_stop', '>=', datetime.today()),
            ('company_id', '=', company.id),
        ])
        if periode_now:
            periode_id = periode_obj.browse(cr, uid, periode_now)
            kolek_periode.append(periode_id.id)
            prev_periode = periode_obj.search(cr, uid, [
                ('date_start', '<', datetime.today()),
                ('id', '!=', periode_id.id),
                ('state', '=', 'draft'),
                ('company_id', '=', company.id),
            ])
            if prev_periode:
                perv_periode_id2 = periode_obj.browse(cr, uid, prev_periode)
                for x in perv_periode_id2:
                    kolek_periode.append(x.id)

        doc = etree.XML(res['arch'])
        nodes_branch = doc.xpath("//field[@name='periode_id']")
        for node in nodes_branch:
            node.set('domain', '[("id", "in", ' + str(kolek_periode) + ')]')
        partner_ids = self.pool.get('res.partner').search(
            cr, uid, [
                ('partner_type', '=', 'Konsolidasi'),
            ])
        nodes_branch = doc.xpath("//field[@name='partner_id']")
        for node in nodes_branch:
            node.set('domain', '[("id", "in", ' + str(partner_ids) + ')]')
        res['arch'] = etree.tostring(doc)
        return res

    @api.model
    def create(self, vals, context=None):

        vals['name'] = self.env['ir.sequence'].get_per_branch(
            vals['branch_id'], 'JMC', division=False)
        vals['date'] = datetime.today()
        if not vals.get(
                'journal_memorial_line') and vals.get('code') != 'cancel':
            raise osv.except_osv(('Perhatian !'), ("Harap isi detail!"))

        res = super(dym_journal_memorial_consol, self).create(vals)
        res.cek_balance()
        return res

    @api.multi
    def write(self, values, context=None):
        res = super(dym_journal_memorial_consol, self).write(values)
        self.cek_balance()
        return res

    @api.one
    def cek_balance(self):
        if self.total_debit != self.total_credit:
            raise osv.except_osv(
                ('Perhatian !'),
                ("Total tidak balance, silahkan periksa kembali !"))

    @api.multi
    def cancel_memorial(self):
        self.action_create_memorial()
        self.state = 'cancel'

    @api.multi
    def action_create_memorial(self):
        memorial_vals = {
            'branch_id':
            self.branch_id.id,
            'periode_id':
            self.periode_id.id,
            'description':
            'Cancel Journal Memorial Consolidation No %s' % (self.name),
            'division':
            self.division,
            'date':
            datetime.today(),
            'auto_reverse':
            self.auto_reverse,
            'code':
            'cancel',
            'total_debit':
            self.total_debit,
            'total_credit':
            self.total_credit,
            'transaction_id':
            self.id,
            'model':
            self.__class__.__name__,
        }
        memorial_id = self.sudo().create(memorial_vals)
        for line in self.journal_memorial_line:
            memorial_line_vals = {
                'journal_memorial_id': memorial_id.id,
                'account_id': line.account_id.id,
                'amount': line.amount,
                'type': 'Dr' if line.type == 'Cr' else 'Cr',
                'branch_id': line.branch_id.id,
                'division': self.division,
                'partner_id': line.partner_id.id,
                'analytic_1': line.analytic_1.id,
                'analytic_2': line.analytic_2.id,
                'analytic_3': line.analytic_3.id,
                'analytic_account_id': line.analytic_account_id.id,
            }
            self.env['dym.journal.memorial.consol.line'].sudo().create(
                memorial_line_vals)
        memorial_id.wkf_request_approval()
        self.cancel_refered = memorial_id.id

    @api.cr_uid_ids_context
    def action_create_move_line(self, cr, uid, ids, context=None):
        if context is None:
            context = {}
        move_pool = self.pool.get('account.move.consol')
        move_line_pool = self.pool.get('account.move.line.consol')
        branch_config = self.pool.get('dym.branch.config')
        company = self.get_group_company(cr, uid, [])

        for memorial in self.browse(cr, uid, ids, context=context):

            name = memorial.name
            date = memorial.date
            if not company.journal_memorial_journal_consol_id:
                raise osv.except_osv(
                    ('Perhatian !'),
                    ("Journal Memorial Consolidation belum diisi di %s! !") %
                    (company.name))
            journal_id = company.journal_memorial_journal_consol_id.id
            amount = memorial.total_credit
            period_id = memorial.periode_id.id

            move = {
                'name':
                name,
                'ref':
                name,
                'journal_id':
                journal_id,
                'date':
                date if period_id == memorial.current_periode_id.id else
                memorial.periode_id.date_stop,
                'period_id':
                period_id,
                'reverse_from_id':
                False,
                'transaction_id':
                memorial.id,
                'model':
                memorial.__class__.__name__,
            }
            # for_name = False
            # if memorial.auto_reverse :
            #     for_name = memorial.description + ' (Auto Reverse)'
            # else :
            #     for_name = memorial.description
            move_id = move_pool.create(cr, uid, move, context=None)
            for y in memorial.journal_memorial_line:
                for_name = False
                if memorial.auto_reverse:
                    for_name = y.description + ' (Auto Reverse)'
                else:
                    for_name = y.description
                branch_dest = self.pool.get('dym.branch').browse(
                    cr, uid, [y.branch_id.id])

                move_line_2 = {
                    'name':
                    _('%s') % (for_name),
                    'ref':
                    name,
                    'account_id':
                    y.account_id.id,
                    'move_id':
                    move_id,
                    'journal_id':
                    journal_id,
                    'period_id':
                    period_id,
                    'date':
                    date if period_id == memorial.current_periode_id.id else
                    memorial.periode_id.date_stop,
                    'debit':
                    y.amount if y.type == 'Dr' else 0.0,
                    'credit':
                    y.amount if y.type == 'Cr' else 0.0,
                    'branch_id':
                    branch_dest.id,
                    'division':
                    memorial.division,
                    'partner_id':
                    y.partner_id.id,
                    'analytic_account_id':
                    y.analytic_account_id.id,
                }
                line_id2 = move_line_pool.create(cr, uid, move_line_2, context)
            # self.create_intercompany_lines(cr,uid,ids,move_id,context=None)
            if company.journal_memorial_journal_consol_id.entry_posted:
                posted = move_pool.post(cr, uid, [move_id], context=None)
            auto_reverse_move_id = False
            if memorial.auto_reverse:
                auto_reverse_move = {
                    'name':
                    name,
                    'ref':
                    name,
                    'journal_id':
                    journal_id,
                    'date':
                    date if memorial.reverse_periode_id.id
                    == memorial.current_periode_id.id else
                    memorial.reverse_periode_id.date_stop,
                    'period_id':
                    memorial.reverse_periode_id.id,
                    'reverse_from_id':
                    move_id,
                    'transaction_id':
                    memorial.id,
                    'model':
                    memorial.__class__.__name__,
                }
                # if not memorial.current_periode_id :
                #     raise osv.except_osv(('warning !'), ("Make sure you have active period for today!"))

                auto_reverse_move_id = move_pool.create(
                    cr, uid, auto_reverse_move, context)
                for y in memorial.journal_memorial_line:
                    for_name = False
                    if memorial.auto_reverse:
                        for_name = y.description + ' (Auto Reverse)'
                    else:
                        for_name = y.description
                    branch_destination = self.pool.get('dym.branch').browse(
                        cr, uid, [y.branch_id.id])
                    autoreverse_move_line_2 = {
                        'name':
                        _('%s') % (for_name),
                        'ref':
                        name,
                        'account_id':
                        y.account_id.id,
                        'move_id':
                        auto_reverse_move_id,
                        'journal_id':
                        journal_id,
                        'period_id':
                        memorial.reverse_periode_id.id,
                        'date':
                        date if memorial.reverse_periode_id.id
                        == memorial.current_periode_id.id else
                        memorial.reverse_periode_id.date_stop,
                        'debit':
                        y.amount if y.type == 'Cr' else 0.0,
                        'credit':
                        y.amount if y.type == 'Dr' else 0.0,
                        'branch_id':
                        branch_destination.id,
                        'division':
                        memorial.division,
                        'partner_id':
                        y.partner_id.id,
                        'analytic_account_id':
                        y.analytic_account_id.id,
                    }
                    autoreverse_line_id2 = move_line_pool.create(
                        cr, uid, autoreverse_move_line_2, context)
                # self.create_intercompany_lines(cr,uid,ids,auto_reverse_move_id,context=None)
                if company.journal_memorial_journal_consol_id.entry_posted:
                    posted2 = move_pool.post(cr,
                                             uid, [auto_reverse_move_id],
                                             context=None)

            self.write(
                cr, uid, memorial.id, {
                    'state': 'confirm',
                    'move_id': move_id,
                    'auto_reverse_move_id': auto_reverse_move_id
                })
        return True

    @api.cr_uid_ids_context
    def create_intercompany_lines(self, cr, uid, ids, move_id, context=None):
        ##############################################################
        ################# Add Inter Company Journal ##################
        ##############################################################
        branch_rekap = {}
        branch_pool = self.pool.get('dym.branch')
        vals = self.browse(cr, uid, ids)
        move_line = self.pool.get('account.move.line.consol')
        move_line_srch = move_line.search(cr, uid, [('move_id', '=', move_id)])
        move_line_brw = move_line.browse(cr, uid, move_line_srch)
        branch = branch_pool.search(cr, uid, [('id', '=', vals.branch_id.id)])
        company = self.get_group_company(cr, uid, [])

        if branch:
            branch_browse = branch_pool.browse(cr, uid, branch)
            inter_branch_header_account_id = branch_browse.inter_company_account_id.id
            if not inter_branch_header_account_id:
                raise osv.except_osv(('Perhatian !'), (
                    "Account Inter Company belum diisi dalam Master branch %s !"
                ) % (vals.branch_id.name))
        if not company.journal_memorial_journal_consol_id:
            raise osv.except_osv(
                ('Perhatian !'),
                ("Journal Memorial Consolidation belum diisi di %s! !") %
                (company.name))
        journal_id = company.journal_memorial_journal_consol_id.id

        #Merge Credit and Debit by Branch
        for x in move_line_brw:
            if x.branch_id not in branch_rekap:
                branch_rekap[x.branch_id] = {}
                branch_rekap[x.branch_id]['debit'] = x.debit
                branch_rekap[x.branch_id]['credit'] = x.credit
            else:
                branch_rekap[x.branch_id]['debit'] += x.debit
                branch_rekap[x.branch_id]['credit'] += x.credit
        #Make account move
        for key, value in branch_rekap.items():
            if key != vals.branch_id and value['debit'] != value['credit']:

                inter_branch_detail_account_id = key.inter_company_account_id.id
                if not inter_branch_detail_account_id:
                    raise osv.except_osv(('Perhatian !'), (
                        "Account Intercompany belum diisi dalam Master branch %s - %s!"
                    ) % (key.code, key.name))

                balance = value['debit'] - value['credit']
                debit = abs(balance) if balance < 0 else 0
                credit = balance if balance > 0 else 0

                move_line_create = {
                    'name':
                    _('Interco Journal Memorial Consolidation %s') %
                    (key.name),
                    'ref':
                    _('Interco Journal Memorial Consolidation %s') %
                    (key.name),
                    'account_id':
                    inter_branch_header_account_id,
                    'move_id':
                    move_id,
                    'journal_id':
                    journal_id,
                    'period_id':
                    vals.periode_id.id,
                    'date':
                    vals.date,
                    'debit':
                    debit,
                    'credit':
                    credit,
                    'branch_id':
                    key.id,
                    'division':
                    vals.division
                }
                inter_first_move = move_line.create(cr, uid, move_line_create,
                                                    context)

                move_line2_create = {
                    'name':
                    _('Interco Journal Memorial Consolidation %s') %
                    (vals.branch_id.name),
                    'ref':
                    _('Interco Journal Memorial Consolidation %s') %
                    (vals.branch_id.name),
                    'account_id':
                    inter_branch_detail_account_id,
                    'move_id':
                    move_id,
                    'journal_id':
                    journal_id,
                    'period_id':
                    vals.periode_id.id,
                    'date':
                    vals.date,
                    'debit':
                    credit,
                    'credit':
                    debit,
                    'branch_id':
                    vals.branch_id.id,
                    'division':
                    vals.division
                }
                inter_second_move = move_line.create(cr, uid,
                                                     move_line2_create,
                                                     context)

        return True

    @api.multi
    def wkf_request_approval(self):
        if self.konsolidasi:
            partner_check = self.journal_memorial_line.search([
                ('partner_id', '!=', self.partner_id.id),
                ('journal_memorial_id', '=', self.id)
            ])
            if partner_check:
                raise osv.except_osv(('Perhatian !'), (
                    "Partner di header dan di line harus sama jika tipe konsolidasi, mohon periksa kembali!"
                ))
        obj_matrix = self.env["dym.approval.matrixbiaya"]
        if self.code == 'cancel':
            obj_matrix.request_by_value(self,
                                        self.total_credit,
                                        code=self.code)
        else:
            obj_matrix.request_by_value(self, self.total_credit)

        self.state = 'waiting_for_approval'
        self.approval_state = 'rf'
        company = self.get_group_company()
        if not company.journal_memorial_journal_consol_id:
            raise osv.except_osv(
                ('Perhatian !'),
                ("Journal Memorial Consolidation belum diisi di %s! !") %
                (company.name))

    @api.multi
    def wkf_approval(self):
        if not self.journal_memorial_line:
            raise osv.except_osv(
                ('Perhatian !'),
                ("Detail belum diisi. Data tidak bisa di save."))
        approval_sts = self.env['dym.approval.matrixbiaya'].approve(self)
        if approval_sts == 1:
            self.write({
                'date': datetime.today(),
                'approval_state': 'a',
                'confirm_uid': self._uid,
                'confirm_date': datetime.now()
            })
            self.action_create_move_line()
        elif approval_sts == 0:
            raise osv.except_osv(('Perhatian !'),
                                 ("User tidak termasuk group Approval"))

    @api.multi
    def has_approved(self):

        if self.approval_state == 'a':
            return True

        return False

    @api.multi
    def has_rejected(self):

        if self.approval_state == 'r':
            self.write({'state': 'draft'})
            return True
        return False

    @api.one
    def wkf_set_to_draft(self):
        self.write({'state': 'draft', 'approval_state': 'r'})

    @api.cr_uid_ids_context
    def view_jm(self, cr, uid, ids, context=None):
        val = self.browse(cr, uid, ids, context={})[0]
        return {
            'name': 'Journal Memorial Consolidation',
            'view_type': 'form',
            'view_mode': 'form',
            'res_model': 'dym.journal.memorial.consol',
            'type': 'ir.actions.act_window',
            'nodestroy': True,
            'target': 'current',
            'res_id': val.cancel_refered.id
        }

    @api.cr_uid_ids_context
    def unlink(self, cr, uid, ids, context=None):
        for item in self.browse(cr, uid, ids, context=context):
            if item.state != 'draft':
                raise osv.except_osv(
                    ('Perhatian !'),
                    ("Journal Memorial Consolidation tidak bisa didelete !"))
        return super(dym_journal_memorial_consol, self).unlink(cr,
                                                               uid,
                                                               ids,
                                                               context=context)
Exemple #17
0
class GolTaxLiability(osv.osv):
    _name = 'gol.tax.liability'
    _inherit = 'gol.basic.entity'
    state = fields.Boolean('Estado')
    date = fields.Datetime('Fecha de Ingreso')
    idCompany = fields.Many2one('res.company', 'Empresa')
Exemple #18
0
class sale_order(models.Model):

    _inherit = 'sale.order'

    @api.onchange('ship_dt')
    @api.multi
    def onchange_ship_dt(self):
        new_date = self.date_order
        updated_date = datetime.strptime(new_date, DEFAULT_SERVER_DATETIME_FORMAT).date()
        if self.ship_dt:
            if self.order_line:
                for line in self.order_line:
                    update_date = datetime.strptime(line.line_ship_dt, DEFAULT_SERVER_DATE_FORMAT).date()
                    delay = abs(updated_date-update_date).days
                    line.delay = delay
        elif not self.ship_dt:
            if self.order_line:
                for line in self.order_line:
                    line.delay=False


    @api.onchange('sc_date')
    @api.multi
    def onchange_sc_date(self):
        if self.sc_date:
            time=datetime.now().time()
            current_time=(time.strftime("%H:%M:%S"))
            self.planned_date=self.sc_date +' '+ current_time
            if self.order_line:
                for line in self.order_line:
                    line.line_sc_date = self.sc_date
                    line.line_planned_date = self.planned_date
        elif not self.sc_date:
            if self.order_line:
                for line in self.order_line:
                    line.line_planned_date = False
                    line.line_sc_date = False


    ship_dt = fields.Date('Ship Date', readonly=True, select=True, default=lambda *a: time.strftime('%Y-%m-%d'), states={'draft': [('readonly', False)],'sent': [('readonly', False)]})
    in_hand_date = fields.Date('In Hand Date', select=True, readonly=True, states={'draft': [('readonly', False)]}, help='In hand date should be after Ship Date')
    planned_date = fields.Datetime(string='Planned Date' )
    sc_date = fields.Date(string='Schedule Date', readonly=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]})
    in_hand_date_visible = fields.Boolean(string='In Hand Date Required')

    def _get_date_planned(self, cr, uid, order, line, start_date, context=None):
        res = super(sale_order, self)._get_date_planned(cr, uid, order, line, start_date, context=context)
        if line.line_planned_date:
            routes = line.product_id.route_ids
            if routes.filtered(lambda r: r.name == 'Manufacture'):
                new_date = datetime.strptime(line.line_planned_date,DEFAULT_SERVER_DATETIME_FORMAT)
                procurement_date_planned = new_date + relativedelta(days=order.company_id.manufacturing_lead)
                date_planned = procurement_date_planned + relativedelta(days=line.product_id.produce_delay or 0.0)
                date_planned = (date_planned + timedelta(days=order.company_id.security_lead)).strftime(DEFAULT_SERVER_DATETIME_FORMAT)
                date_planned = datetime.strptime(date_planned, '%Y-%m-%d %H:%M:%S')
                return date_planned
            elif routes.filtered(lambda r: r.name == "Buy"):
                new_date = datetime.strptime(line.line_planned_date,DEFAULT_SERVER_DATETIME_FORMAT)
                procurement_date_planned = new_date + relativedelta(days=order.company_id.po_lead)
                date_planned = (procurement_date_planned + timedelta(days=order.company_id.security_lead)).strftime(DEFAULT_SERVER_DATETIME_FORMAT)
                date_planned = datetime.strptime(date_planned, '%Y-%m-%d %H:%M:%S')
                return date_planned
            else:
                return res
        else:
            return res

    def action_button_confirm(self, cr, uid, ids, context=None):
        res = super(sale_order, self).action_button_confirm(cr, uid, ids, context=context)
        for order in self.browse(cr, uid, ids, context=context):
            if not order.ship_dt:
                raise osv.except_osv(_('Warning'), _('Please enter the Ship Date'))
        return res

    def _get_ship_date(self, cr, uid, order, line, start_date, context=None):
        date_planned = datetime.strptime(start_date, DEFAULT_SERVER_DATETIME_FORMAT) 
        date_planned = (date_planned - timedelta(days=order.company_id.security_lead)).strftime(DEFAULT_SERVER_DATETIME_FORMAT)
        return date_planned

    def create(self, cr, uid, vals, context=None):
        updated_date = False
        if vals.has_key('in_hand_date_visible') and vals['in_hand_date_visible']:
            if vals.get('ship_dt', False):
                if isinstance(vals['ship_dt'], date):
                    ship_date_new = vals['ship_dt'].strftime('%Y-%m-%d')
                else:
                    ship_date_new = vals['ship_dt']
            if vals.get('ship_dt', False) and vals.get('in_hand_date', False) and vals.get('in_hand_date', False) < ship_date_new and vals.get('in_hand_date_visible', False) and vals['in_hand_date_visible']:
                raise osv.except_osv(_('Warning!'), _('In Hand Date should be after or equal to Ship Date'))
        if vals.has_key('ship_dt') and vals['ship_dt']:
            if vals.has_key('date_order') and vals['date_order']:
                date_order = vals['date_order']
                if len(date_order.split(' ')) <2:
                    date_order = vals['date_order'] + " " + str(datetime.now().time()).split('.')[0]
                date_order = datetime.strptime(date_order, DEFAULT_SERVER_DATETIME_FORMAT)
                date_order_new = date_order.date()
                ship_dt = datetime.strptime(str(vals['ship_dt']), DEFAULT_SERVER_DATE_FORMAT)
                ship_dt_new = ship_dt.date()
                if ship_dt_new < date_order_new :
                    raise osv.except_osv(_('Warning!'), _('Ship Date should be after or Equal to Order Date'))                 
        if vals.has_key('order_line') and vals.get('order_line') and vals.get('date_order'):
            new_date = vals.get('date_order')
            updated_date = datetime.strptime(new_date, DEFAULT_SERVER_DATETIME_FORMAT).date()
            for line_rec in vals.get('order_line'):
                if line_rec[2] and line_rec[2].has_key('line_ship_dt') and line_rec[2].get('line_ship_dt'):
                    update_date = datetime.strptime(line_rec[2]['line_ship_dt'], DEFAULT_SERVER_DATE_FORMAT).date()
                    delay = updated_date and abs(updated_date-update_date).days or 0
                    line_rec[2].update({'delay':delay})

        if not vals.get('ship_dt'):
            vals['ship_dt'] = fields.date.today()

        order_id = super(sale_order, self).create(cr, uid, vals, context=context)
        order = self.browse(cr, uid, order_id, context=context)
        ship_date = []
        for line in order.order_line:
            if not line.line_ship_dt:
                line_ship_date = order.ship_dt
                update_date = datetime.strptime(line_ship_date ,'%Y-%m-%d').date()
                delay = updated_date and abs(updated_date-update_date).days or 0
                self.pool.get('sale.order.line').write(cr, uid, line.id, {'line_ship_dt': line_ship_date,'delay':delay}, context=context)

        return order_id

    def write(self, cr, uid, ids, vals, context=None):
        res = super(sale_order, self).write(cr, uid, ids, vals, context=context)
        if not ids:
            return res
        if ids and not isinstance(ids, (list)):
            ids = [ids]    
        current_rec = self.browse(cr, uid, ids[0], context=context)
        


        order_line_obj = self.pool.get('sale.order.line')
        for order in self.browse(cr, uid, ids, context=context):
            delay_list = []
            delay_dict = {}
            date_order = order.date_order or False
            new_ship_date = vals.get('ship_dt', False)

            if not new_ship_date and order:
                new_ship_date = order.ship_dt
            if new_ship_date and isinstance(new_ship_date, str):
                new_ship_date = new_ship_date +" "+ datetime.now().strftime('%H:%M:%S')
                if len(new_ship_date) > 10:
                    new_ship_date = new_ship_date.replace(new_ship_date[11:], datetime.now().strftime('%H:%M:%S'))
                    new_ship_date = datetime.strptime(new_ship_date, DEFAULT_SERVER_DATETIME_FORMAT)
                else:
                    new_ship_date = new_ship_date +" "+ datetime.now().strftime('%H:%M:%S')
                    new_ship_date = datetime.strptime(new_ship_date, DEFAULT_SERVER_DATETIME_FORMAT)

            #Convert date_order to datetime if it is of type 'str'
            if date_order and isinstance(date_order, str):
                if len(order.date_order) > 10:
                    date_order = datetime.strptime(order.date_order, DEFAULT_SERVER_DATETIME_FORMAT)
                else:
                    date_order = datetime.strptime(order.date_order, DEFAULT_SERVER_DATE_FORMAT)

            if vals.get('order_line') and not vals.get('ship_dt'):
                for line in order.order_line:
                    if line.line_ship_dt:
                        linedate_new  = line.line_ship_dt
                        new_date = order.date_order
                        updated_date = datetime.strptime(new_date, DEFAULT_SERVER_DATETIME_FORMAT).date()
                        update_date = datetime.strptime(linedate_new ,'%Y-%m-%d').date()
                        delay = abs(update_date -updated_date).days
                        order_line_obj.write(cr, uid, line.id, {'line_ship_dt': linedate_new,'delay': delay}, context=context)
                    if not line.line_ship_dt:
                        linedate_new  = order.ship_dt
                        new_date = order.date_order
                        updated_date = datetime.strptime(new_date, DEFAULT_SERVER_DATETIME_FORMAT).date()
                        update_date = datetime.strptime(linedate_new ,'%Y-%m-%d').date()
                        delay = abs(update_date -updated_date).days
                        order_line_obj.write(cr, uid, line.id, {'line_ship_dt': linedate_new,'delay': delay}, context=context)
                    if line.id in delay_dict.keys():
                         delay_list.append(delay_dict.get(line.id))
                    else:
                        delay_list.append(line.delay)
                delay = delay_list and min(delay_list)
            if vals.get('ship_dt', False) and not context.get('from_create') and new_ship_date:
                if new_ship_date.date() < date_order.date():
                    raise osv.except_osv(_('Warning!'), _('Ship Date should be after or Equal to Order Date'))
                if current_rec.in_hand_date:
                    in_hand_date = datetime.strptime(current_rec.in_hand_date, DEFAULT_SERVER_DATE_FORMAT)
                    if vals.has_key('in_hand_date_visible') and vals['in_hand_date_visible']:
                        if (new_ship_date.date() > in_hand_date.date()):
                            raise osv.except_osv(_('Warning!'), _('In hand Date should be after or Equal to ship Date'))
            if current_rec.in_hand_date:
                in_hand_date = datetime.strptime(current_rec.in_hand_date, DEFAULT_SERVER_DATE_FORMAT)
                if vals.has_key('in_hand_date_visible') and vals['in_hand_date_visible']:
                    if (new_ship_date.date() > in_hand_date.date()):
                        raise osv.except_osv(_('Warning!'), _('In hand Date should be after or Equal to ship Date'))


                #Convert new_ship_date to datetime if it is of type 'str'
                if order.ship_dt and isinstance(order.ship_dt, str):
                    if len(order.ship_dt) > 10:
                        old_ship_date = datetime.strptime(order.ship_dt, DEFAULT_SERVER_DATETIME_FORMAT)
                    else:
                        old_ship_date = datetime.strptime(order.ship_dt, DEFAULT_SERVER_DATE_FORMAT)

            in_hand_date = vals.get('in_hand_date', False)


        if vals.get('in_hand_date', False):
            if len(vals.get('in_hand_date', False)) > 10:
                in_hand_date = datetime.strptime(vals.get('in_hand_date', False), DEFAULT_SERVER_DATETIME_FORMAT)
            else:
                in_hand_date = datetime.strptime(vals.get('in_hand_date', False), DEFAULT_SERVER_DATE_FORMAT)
            if current_rec.in_hand_date_visible or (vals.get('in_hand_date_visible', False) and vals['in_hand_date_visible']):
                if (new_ship_date and in_hand_date and in_hand_date.date() < new_ship_date.date()) or (current_rec.ship_dt and current_rec.ship_dt and current_rec.in_hand_date and current_rec.in_hand_date < current_rec.ship_dt):
                    raise osv.except_osv(_('Warning!'), _('In Hand Date should be after or equal to Ship Date'))
            #Check Ship date should be after order date
            if not context.get('by_pass', False):
                if new_ship_date and date_order and new_ship_date < date_order:
                    raise osv.except_osv(_('Warning!'), _('Ship Date should be after Order Date'))
        if vals.get('ship_dt', False) and not vals.get('in_hand_date', False):
            vals['in_hand_date'] = vals.get('ship_dt', False)
        if vals.get('ship_dt'):
            for line in order.order_line:
                linedate_new  = line.line_ship_dt
                new_date = order.date_order
                updated_date = datetime.strptime(new_date, DEFAULT_SERVER_DATETIME_FORMAT).date()
                if linedate_new:
                    update_date = datetime.strptime(linedate_new,'%Y-%m-%d').date()
                else:
                    update_date = datetime.strptime(vals.get('ship_dt'),'%Y-%m-%d').date()
                delay = abs(update_date -updated_date).days
                if linedate_new:
                    order_line_obj.write(cr, uid, line.id, {'line_ship_dt': linedate_new,'delay':delay}, context=context)
                else:
                    order_line_obj.write(cr, uid, line.id, {'line_ship_dt': vals.get('ship_dt'), 'delay': delay},
                                         context=context)
        if not order.ship_dt:
            order.ship_dt = order.date_order
        return res
Exemple #19
0
class PrestashopBackend(models.Model):
    _name = 'prestashop.backend'
    _doc = 'Prestashop Backend'
    _inherit = 'connector.backend'

    _backend_type = 'prestashop'

    
    def _select_versions(self):
        """ Available versions

        Can be inherited to add custom versions.
        """
        return [('1.5', '1.5'),]


            
    location = fields.Char("Location", required=True)
    version = fields.Selection(selection=_select_versions, string='Version',
            required=True)
    webservice_key = fields.Char(
            'Webservice key',
            required=True,
            help="You have to put it in 'username' of the PrestaShop "
            "Webservice api path invite"
        )
    warehouse_id = fields.Many2one(
            'stock.warehouse',
            'Warehouse',
            required=True,
            help='Warehouse used to compute the stock quantities.'
        )
        
    taxes_included = fields.Boolean("Use tax included prices" )
    
    import_partners_since = fields.Datetime('Import partners since')
    import_orders_since = fields.Datetime('Import Orders since')
    import_products_since = fields.Datetime('Import Products since')
    import_refunds_since = fields.Datetime('Import Refunds since')
    import_suppliers_since = fields.Datetime('Import Suppliers since')
    language_ids = fields.One2many(comodel_name='prestashop.res.lang', 
                    inverse_name='backend_id',
                    string='Languages'
        )
    company_id = fields.Many2one('res.company', 'Company', select=True,
                                required=True,
                                default=lambda self: self.env.user.company_id)
    discount_product_id = fields.Many2one('product.product',
                                               'Discount Product', select=True,
                                               required=False)
    shipping_product_id = fields.Many2one('product.product',
                                               'Shipping Product', select=True,
                                               required=False)
    journal_id = fields.Many2one('account.journal',
                                'Main Journal for invoices', select=True,
                                 required=False)                                       
    api_debug =  fields.Boolean("Debug the API", default=False)
    api_timeout = fields.Float("Timeout in seconds", default=100)
    image_store_type = fields.Selection(
                                [('db','Database'),('file','File'),('url', 'URL')], string='Stockage type for image',
                                required=True, default='db'
                            )
    use_variant_default_code = fields.Boolean(string='', 
                    help="""Allow to choose wether the default_code or the default variant is used""",
                    default=True)
    quantity_field = fields.Selection(
                            [('qty_available','Available Quantity'),
                            ('virtual_available','Forecast quantity')],
                            string='Field use for quantity update',
                            required=True, 
                            default='virtual_available'
                        )
    
            
#    _columns = {
#        'version': fields.selection(
#            _select_versions,
#            string='Version',
#            required=True),
#        'location': fields.Char('Location', required=True),
#        'webservice_key': fields.Char(
#            'Webservice key',
#            required=True,
#            help="You have to put it in 'username' of the PrestaShop "
#            "Webservice api path invite"
#        ),
#        'warehouse_id': fields.Many2one(
#            'stock.warehouse',
#            'Warehouse',
#            required=True,
#            help='Warehouse used to compute the stock quantities.'
#        ),
#        'taxes_included': fields.Boolean("Use tax included prices",
##                                         readonly=True
#                                         ),
#        'import_partners_since': fields.datetime('Import partners since'),
#        'import_orders_since': fields.datetime('Import Orders since'),
#        'import_products_since': fields.datetime('Import Products since'),
#        'import_refunds_since': fields.datetime('Import Refunds since'),
#        'import_suppliers_since': fields.datetime('Import Suppliers since'),
#        'language_ids': fields.one2many(
#            'prestashop.res.lang',
#            'backend_id',
#            'Languages'
#        ),
#        'company_id': fields.Many2one('res.company', 'Company', select=True,
#                                      required=True),
#        'discount_product_id': fields.Many2one('product.product',
#                                               'Discount Product', select=True,
#                                               required=False),
#        'shipping_product_id': fields.Many2one('product.product',
#                                               'Shipping Product', select=True,
#                                               required=False),
#        'journal_id': fields.Many2one('account.journal',
#                                               'Main Journal for invoices', select=True,
#                                               required=False),                                        
#        'api_debug': fields.Boolean("Debug the API"),
#        'api_timeout': fields.float("Timeout in seconds"),
#        'image_store_type' : fields.selection(
#                                [('db','Database'),('file','File'),('url', 'URL')], string='Stockage type for image',
#                                required=True, default='db'
#                            ),
#        'use_variant_default_code': fields.Boolean(string='', 
#                    help="""Allow to choose wether the default_code or the default variant is used"""),
#        'quantity_field' : fields.selection(
#                            [('qty_available','Available Quantity'),
#                            ('virtual_available','Forecast quantity')],
#                            string='Field use for quantity update',
#                            required=True, 
#                            default='virtual_available'
#                        )
#    }

#    _defaults = {
#        'company_id': lambda s, cr, uid,
#        c: s.pool.get('res.company')._company_default_get(cr, uid,
#                                                          'prestashop.backend',
#                                                          context=c),
#        'api_debug': False,
#        'api_timeout': 100.0,
#        'use_variant_default_code': True,
#    }

    @api.v7
    def synchronize_metadata(self, cr, uid, ids, context=None):
        if not hasattr(ids, '__iter__'):
            ids = [ids]
        session = ConnectorSession(cr, uid, context=context)
        for backend_id in ids:
            for model in ('prestashop.shop.group',
                          'prestashop.shop'):
                # import directly, do not delay because this
                # is a fast operation, a direct return is fine
                # and it is simpler to import them sequentially
                import_batch(session, model, backend_id)
        return True

    @api.v7
    def synchronize_basedata(self, cr, uid, ids, context=None):
        if not hasattr(ids, '__iter__'):
            ids = [ids]
        session = ConnectorSession(cr, uid, context=context)
        for backend_id in ids:
            for model_name in [
                'prestashop.res.lang',
                'prestashop.res.country',
                'prestashop.res.currency',
            ]:
                env = get_environment(session, model_name, backend_id)
                directBinder = env.get_connector_unit(DirectBinder)
                directBinder.run()
            
            
            #TODO : Consider running the prestashop.configuration in asynchronous mode (Example of conf > 1000 items)
            import_batch(session, 'prestashop.configuration', backend_id)
            import_batch(session, 'prestashop.account.tax.group', backend_id)            
            import_batch(session, 'prestashop.account.tax', backend_id)
            
            import_batch(session, 'prestashop.tax.rule', backend_id)
            import_batch(session, 'prestashop.sale.order.state', backend_id)
            
        return True
    
    @api.multi
    def _date_as_user_tz(self, dtstr):
        if not dtstr:
            return None
#        users_obj = self.pool.get('res.users')
#        user = users_obj.browse(cr, uid, uid)
        user = self.env.user
        timezone = pytz.timezone(user.partner_id.tz or 'utc')
        dt = datetime.strptime(dtstr, DEFAULT_SERVER_DATETIME_FORMAT)
        dt = pytz.utc.localize(dt)
        dt = dt.astimezone(timezone)
        return dt
        
    @api.multi
    def import_customers_since(self):
#        if not hasattr(ids, '__iter__'):
#            ids = [ids]
        session = session = ConnectorSession(self.env.cr, self.env.uid,
                                       context=self.env.context)
                                       
#        for backend_record in self.browse(cr, uid, ids, context=context):
        for backend_record in self:
            since_date = self._date_as_user_tz(backend_record.import_partners_since)
            import_customers_since.delay(
                session,
                backend_record.id,
                since_date,
                priority=10,
            )

        return True
    
    @api.cr_uid_context
    def import_products(self, cr, uid, ids, context=None):
        if not hasattr(ids, '__iter__'):
            ids = [ids]
        session = ConnectorSession(cr, uid, context=context)
        for backend_record in self.browse(cr, uid, ids, context=context):
            since_date = self._date_as_user_tz(
                cr, uid, backend_record.import_products_since
            )
            import_products.delay(session, backend_record.id, since_date,
                                  priority=10)
        return True

    @api.cr_uid_context
    def import_carriers(self, cr, uid, ids, context=None):
        if not hasattr(ids, '__iter__'):
            ids = [ids]
        session = ConnectorSession(cr, uid, context=context)
        for backend_id in ids:
            import_carriers.delay(session, backend_id, priority=10)
        return True

    @api.cr_uid_context
    def update_product_stock_qty(self, cr, uid, ids, context=None):
        if not hasattr(ids, '__iter__'):
            ids = [ids]
        session = ConnectorSession(cr, uid, context=context)
        export_product_quantities.delay(session, ids)
        return True
    
    @api.cr_uid_context
    def import_stock_qty(self, cr, uid, ids, context=None):
        if not hasattr(ids, '__iter__'):
            ids = [ids]
        session = ConnectorSession(cr, uid, context=context)
        for backend_id in ids:
            import_inventory.delay(session, backend_id)
    
    @api.cr_uid_context
    def import_sale_orders(self, cr, uid, ids, context=None):
        if not hasattr(ids, '__iter__'):
            ids = [ids]
        session = ConnectorSession(cr, uid, context=context)
        for backend_record in self.browse(cr, uid, ids, context=context):
            since_date = self._date_as_user_tz(
                cr, uid, backend_record.import_orders_since
            )
            import_orders_since.delay(
                session,
                backend_record.id,
                since_date,
                priority=5,
            )
        return True

    @api.cr_uid_context
    def import_payment_methods(self, cr, uid, ids, context=None):
        if not hasattr(ids, '__iter__'):
            ids = [ids]
        session = ConnectorSession(cr, uid, context=context)
        for backend_record in self.browse(cr, uid, ids, context=context):
            import_batch.delay(session, 'account.payment.mode', backend_record.id)
        return True

    @api.cr_uid_context
    def import_refunds(self, cr, uid, ids, context=None):
        if not hasattr(ids, '__iter__'):
            ids = [ids]
        session = ConnectorSession(cr, uid, context=context)
        for backend_record in self.browse(cr, uid, ids, context=context):
            since_date = self._date_as_user_tz(
                cr, uid, backend_record.import_refunds_since
            )
            import_refunds.delay(session, backend_record.id, since_date)
        return True

    @api.cr_uid_context
    def import_suppliers(self, cr, uid, ids, context=None):
        if not hasattr(ids, '__iter__'):
            ids = [ids]
        session = ConnectorSession(cr, uid, context=context)
        for backend_record in self.browse(cr, uid, ids, context=context):
            since_date = self._date_as_user_tz(
                cr, uid, backend_record.import_suppliers_since
            )
            import_suppliers.delay(session, backend_record.id, since_date)
        return True

    @api.cr_uid_context
    def _scheduler_launch(self, cr, uid, callback, domain=None,
                          context=None):
        if domain is None:
            domain = []
        ids = self.search(cr, uid, domain, context=context)
        if ids:
            callback(cr, uid, ids, context=context)

    @api.cr_uid_context
    def _scheduler_confirm_sale_orders(self, cr, uid, domain=None,
                                       context=None):
        sale_obj = self.pool.get('sale.order')
        ids = sale_obj.search(cr, uid,
                              [('state', 'in', ['draft']),
                               ('prestashop_bind_ids', '!=', False)],
                              context=context)
        for id in ids:
            sale_obj.action_button_confirm(cr, uid, id, context=context)

    @api.cr_uid_context
    def _scheduler_update_product_stock_qty(self, cr, uid, domain=None,
                                            context=None):
        self._scheduler_launch(cr, uid, self.update_product_stock_qty,
                               domain=domain, context=context)

    @api.cr_uid_context
    def _scheduler_import_sale_orders(self, cr, uid, domain=None,
                                      context=None):
        self._scheduler_launch(cr, uid, self.import_sale_orders,
                               domain=domain, context=context)
    
    @api.cr_uid_context
    def _scheduler_import_customers(self, cr, uid, domain=None,
                                    context=None):
        self._scheduler_launch(cr, uid, self.import_customers_since,
                               domain=domain, context=context)
    
    @api.cr_uid_context
    def _scheduler_import_products(self, cr, uid, domain=None, context=None):
        self._scheduler_launch(cr, uid, self.import_products, domain=domain,
                               context=context)
    
    @api.cr_uid_context
    def _scheduler_import_carriers(self, cr, uid, domain=None, context=None):
        self._scheduler_launch(cr, uid, self.import_carriers, domain=domain,
                               context=context)
    @api.cr_uid_context
    def _scheduler_import_payment_methods(self, cr, uid, domain=None,
                                          context=None):
        self._scheduler_launch(cr, uid, self.import_payment_methods,
                               domain=domain, context=context)

        self._scheduler_launch(cr, uid, self.import_refunds,
                               domain=domain, context=context)
    
    @api.cr_uid_context
    def _scheduler_import_suppliers(self, cr, uid, domain=None, context=None):
        self._scheduler_launch(cr, uid, self.import_suppliers,
                               domain=domain, context=context)
    
    @api.cr_uid_context
    def _scheduler_create_payments(self, cr, uid, states=None, context=None):
        order_obj = self.pool.get('prestashop.sale.order')
        order_ids =  order_obj.search(cr, uid, [('state', 'not in', states)])
        order_obj.create_payments(cr, uid, order_ids, context=context)
    
    @api.cr_uid_context            
    def import_record(self, cr, uid, backend_id, model_name, ext_id,
                      context=None):
        session = ConnectorSession(cr, uid, context=context)
        import_record(session, model_name, backend_id, ext_id)
        return True
Exemple #20
0
class dym_pettycash(models.Model):
    _name = "dym.pettycash"
    _description ="Petty Cash"
    _order = "create_date desc"
    
    STATE_SELECTION = [
        ('draft', 'Draft'),
        ('waiting_for_approval','Waiting Approval'),
        ('confirmed', 'Confirmed'),
        ('approved', 'Approved'),
        ('posted', 'Posted'),
        ('fully_returned', 'Fully Returned'),
        ('horejected', 'HO Rejected'),
        ('reimbursed', 'Reimbursed'),
        ('cancel', 'Cancelled'),
    ]   
    
    @api.cr_uid_ids_context
    @api.depends('period_id')
    def _get_period(self, cr, uid, ids,context=None):
        if context is None: context = {}
        if context.get('period_id', False):
            return context.get('period_id')
        periods = self.pool.get('account.period').find(cr, uid, context=context)
        return periods and periods[0] or False

    @api.model
    def _get_default_branch(self):
        res = self.env.user.get_default_branch()
        return res

    @api.one
    @api.depends('line_ids.amount_real','line_ids.amount_reimbursed')
    def _compute_amount(self):
        self.amount_real = sum(line.amount_real for line in self.line_ids)
        self.amount_reimbursed = sum(line.amount_reimbursed for line in self.line_ids)
        # self.balance = sum(line.amount_real for line in self.line_ids)
                    
    def terbilang(self,amount):
        hasil = fungsi_terbilang.terbilang(amount, "idr", 'id')
        return hasil

    def ubah_tanggal(self,tanggal):
        if not tanggal:
            return False
        try:
            conv = datetime.strptime(tanggal, '%d-%m-%Y %H:%M')
            return conv.strftime('%d-%m-%Y')
        except Exception as e:
            conv = datetime.strptime(tanggal, '%Y-%m-%d %H:%M:%S')
            return conv.strftime('%d-%m-%Y')

    def ubah_tanggal_2(self,tanggal):
        if not tanggal:
            return False
        try:
            conv = datetime.strptime(tanggal, '%d-%m-%Y')
            return conv.strftime('%d-%m-%Y')
        except Exception as e:
            conv = datetime.strptime(tanggal, '%Y-%m-%d')
            return conv.strftime('%d-%m-%Y')

    @api.model
    def _get_analytic_company(self):
        company = self.pool.get('res.users').browse(self._cr, self._uid, self._uid).company_id
        level_1_ids = self.pool.get('account.analytic.account').search(self._cr, self._uid, [('segmen','=',1),('company_id','=',company.id),('type','=','normal'),('state','not in',('close','cancelled'))])
        if not level_1_ids:
            raise osv.except_osv(('Perhatian !'), ("[dym_pettycash-1] Tidak ditemukan data analytic untuk company %s")%(company.name))
        return level_1_ids[0]

    @api.model
    def _getCompanyBranch(self):
        user = self.env.user
        if user.branch_type!='HO':
            if not user.branch_id:
                raise osv.except_osv(('Perhatian !'), ("User %s tidak memiliki default branch. Hubungi system administrator agar menambahkan default branch di User Setting." % self.env.user.name))
            return [('id','=',user.branch_id.id)]
        company_id = self._context.get('company_id', self.env.user.company_id.id)
        branch_ids = [b.id for b in self.env.user.branch_ids if b.company_id.id==company_id]
        return [('id','in',branch_ids)]

    @api.multi
    @api.depends('journal_id')
    def _get_balance(self):
        aa_obj = self.env['account.analytic.account']
        start_date = fields.Date.context_today(self)
        for rec in self:
            bank_balance = 0
            today_balance = 0
            branch_id = rec.branch_id
            if rec.journal_id:            
                sql_query = ''
                if branch_id:
                    analytic_branch = aa_obj.search([('segmen','=',3),('branch_id','=',branch_id.id),('type','=','normal'),('state','not in',('close','cancelled'))])
                    analytic_cc = aa_obj.search([('segmen','=',4),('type','=','normal'),('state','not in',('close','cancelled')),('parent_id','child_of',analytic_branch.ids)])
                    sql_query = ' and l.period_id in (select id from  account_period where special= FALSE) AND l.analytic_account_id in %s' % str(tuple(analytic_cc.ids)).replace(',)', ')')
                bank_balance = rec.journal_id.default_credit_account_id.with_context(date_from=start_date, date_to=start_date, initial_bal=True,sql_query=sql_query).balance or rec.journal_id.default_debit_account_id.with_context(date_from=start_date, date_to=start_date, initial_bal=True,sql_query=sql_query).balance
                today_balance = rec.journal_id.default_credit_account_id.with_context(date_from=start_date, date_to=start_date, initial_bal=False,sql_query=sql_query).balance or rec.journal_id.default_debit_account_id.with_context(date_from=start_date, date_to=start_date, initial_bal=False,sql_query=sql_query).balance
            rec.balance = bank_balance + today_balance
        return True

    branch_id = fields.Many2one('dym.branch', string='Branch', required=True, default=_get_default_branch, domain=_getCompanyBranch)
    name = fields.Char(string="Name",readonly=True,default='')
    user_id = fields.Many2one('hr.employee', string='Responsible')
    division = fields.Selection(DIVISION_SELECTION, string='Division', change_default=True, select=True, readonly=True)
    amount = fields.Float('Paid Amount')
    branch_destination_id =  fields.Many2one('dym.branch', string='Branch Destination', required=True)
    journal_id = fields.Many2one('account.journal',string="Payment Method",domain="[('branch_id','in',[branch_id,False]),('type','=','pettycash')]")
    line_ids = fields.One2many('dym.pettycash.line','pettycash_id',string="PettyCash Line")
    state= fields.Selection(STATE_SELECTION, string='State', readonly=True,default='draft')
    date = fields.Date(string="Date",required=True,readonly=True,default=fields.Date.context_today)
    move_id = fields.Many2one('account.move', string='Account Entry', copy=False)
    move_ids = fields.One2many('account.move.line',related='move_id.line_id',string='Journal Items', readonly=True)    
    period_id = fields.Many2one('account.period',string="Period",required=True, readonly=True,default=_get_period)
    #company_id = fields.Many2one(related='journal_id.company_id',string='Company',store=True, readonly=True),
    account_id = fields.Many2one('account.account',string="Account")    
    #reimbursed_id = fields.Many2one('dym.reimbursed')  
    confirm_uid = fields.Many2one('res.users',string="Posted by")
    confirm_date = fields.Datetime('Posted on')
    amount_real = fields.Float(string='Amount Biaya',digits=dp.get_precision('Account'), store=True, readonly=True, compute='_compute_amount',) 
    amount_reimbursed = fields.Float(string='Amount Reimbursed',digits=dp.get_precision('Account'), store=True, readonly=True, compute='_compute_amount',) 
    kas_bon = fields.Boolean('Kas Bon')
    pay_supplier_invoice = fields.Boolean('Pay Supplier Invoice')

    date_cancel = fields.Date(string="Date Canceled",readonly=True)
    cancel_uid = fields.Many2one('res.users',string="Cancelled by")
    cancel_date = fields.Datetime('Cancelled on')
    
    balance = fields.Float(compute=_get_balance, string='Balance', readonly=True)
    balance_on_posted = fields.Float(string='Balance On Posted', readonly=True) 
    analytic_1 = fields.Many2one('account.analytic.account', 'Account Analytic Company')
    analytic_2 = fields.Many2one('account.analytic.account', 'Account Analytic Bisnis Unit')
    analytic_3 = fields.Many2one('account.analytic.account', 'Account Analytic Branch')
    analytic_4 = fields.Many2one('account.analytic.account', 'Account Analytic Cost Center')

    analytic_2_readonly = fields.Many2one('account.analytic.account', 'Account Analytic Bisnis Unit', related="analytic_2")
    analytic_3_readonly = fields.Many2one('account.analytic.account', 'Account Analytic Branch', related="analytic_3")
    analytic_4_readonly = fields.Many2one('account.analytic.account', 'Account Analytic Cost Center', related="analytic_4")

    wo_ids = fields.Many2many('dym.work.order','pettycash_out_wo_rel','pettycash_id','wo_id','Work Order Reference')
    so_ids = fields.Many2many('sale.order','pettycash_out_so_rel','pettycash_id','so_id','Sales Memo Reference')
    cash_in_ids = fields.One2many('dym.pettycash.in','pettycash_id',string="Cash In")
    cash_in = fields.Many2one('dym.pettycash.in', string='Pettycash In Reff')

    _defaults = {
        'analytic_1':_get_analytic_company,
    }

    @api.onchange('kas_bon')
    def onchange_kas_bon(self):
        self.line_ids = []

    @api.multi
    def get_equal_amount(self,amount,pettycash):
        total_amount = 0.0
        for x in pettycash :
            total_amount += x['amount']
        return total_amount
            
    @api.model
    def default_get(self, fields):
        res = super(dym_pettycash, self).default_get(fields)
        journal_id = self.env['account.journal'].search([('branch_id','in',[self.branch_id,False]),('type','=','pettycash')])
        res['journal_id'] = journal_id.id
        return res

    @api.multi
    @api.constrains('amount')
    def check_amount(self):
        for rec in self:
            if rec.amount > rec.balance:
                raise osv.except_osv(('Perhatian !'), ("Nilai amount tidak boleh lebih besar dari balance."))

    @api.model
    def create(self,vals,context=None):

        if not vals['line_ids'] :
            raise osv.except_osv(('Perhatian !'), ("Detail belum diisi. Data tidak bisa di save."))
        try:
            pettycash = []
            for x in vals['line_ids']:
                x_pop = x.pop(2)
                pettycash.append(x_pop)        
            vals['date'] = datetime.today()            
            if vals['journal_id'] :
                journal_obj = self.env['account.journal'].search([('id','=',vals['journal_id'])])
                vals['name'] = self.env['ir.sequence'].get_per_branch(vals['branch_id'], 'PCO', division='Umum')  
                     
            del[vals['line_ids']]
            vals['amount'] = self.get_equal_amount(vals['amount'],pettycash)
        except:
            pass
        
        pettycash_id = super(dym_pettycash, self).create(vals)
        if pettycash_id :
            rekap = []
            for x in pettycash :
                if x['account_id'] not in rekap :
                    rekap.append(x['account_id'])
                elif x['account_id'] in rekap :
                    raise osv.except_osv(('Perhatian !'), ("Tidak boleh ada Account yang sama dalam detail transaksi"))
                     
                pettycash_pool = self.env['dym.pettycash.line']
                pettycash_pool.create({
                    'pettycash_id':pettycash_id.id,
                    'name':x['name'],
                    'account_id':x['account_id'],
                    'amount':x['amount'],
                    'analytic_1':x['analytic_1'],
                    'analytic_2':x['analytic_2'],
                    'analytic_3':x['analytic_3'],
                    'analytic_4':x['analytic_4'],
                })
        else :
            return False    
        return pettycash_id
    
    @api.multi
    def write(self,vals,context=None):
        vals.get('line_ids',[]).sort(reverse=True)        
        line = vals.get('line_ids',False)
        if line:
            for x,item in enumerate(line) :
                petty_id = item[1]
                if item[0] == 1 or item[0] == 0:
                    value = item[2]
                    if value.get('account_id') :
                        for y in self.line_ids :
                            if y.account_id.id == value['account_id'] :
                                raise osv.except_osv(('Perhatian !'), ("Tidak boleh ada Account yang sama dalam detail transaksi"))
        res = super(dym_pettycash,self).write(vals)
        return res        

    @api.onchange('division')
    def onchange_division(self):
        value = {}
        value['line_ids'] = []
        return {'value':value}

    @api.onchange('branch_id')
    def onchange_branch(self):
        dom={}
        val={}
        self.branch_destination_id = self.branch_id
        if self.branch_id:
            branch = self.branch_id
            analytic_1_general, analytic_2_general, analytic_3_general, analytic_4_general = self.pool.get('account.analytic.account').get_analytical(self._cr, self._uid, branch, 'Umum', False, 4, 'General')
            self.analytic_1 = analytic_1_general
            self.analytic_2 = analytic_2_general
            self.analytic_3 = analytic_3_general
            self.analytic_4 = analytic_4_general
            dom['user_id'] = [('branch_id','=',self.branch_id.id)]
            self.line_ids = []
            print "self.branch_id.branch_status",self.branch_id.branch_status
            if self.branch_id.branch_status == 'HO':
                self.division = 'Finance'
            if self.branch_id.branch_status == 'H1':
                self.division = 'Unit'
            if self.branch_id.branch_status == 'H23':
                self.division = 'Sparepart'
            if self.branch_id.branch_status == 'H123':
                self.division = 'Unit'
        return {'domain':dom,'value':val}

    @api.multi
    def post_pettycash(self):
        max_amount = self.env['dym.branch.config'].search([('branch_id','=',self.branch_id.id)])
        if max_amount and max_amount.petty_cash_limit and self.amount > max_amount.petty_cash_limit:            
            warning = {
                'title': ('Perhatian !'),
                'message': (("Nilai amount tidak boleh dari limit (%s)" % '{:20,.2f}'.format(max_amount.petty_cash_limit))),
            }                      
            return {'warning':warning}
        self.update({'balance_on_posted': self.balance-float(self.amount)})
        self.action_move_line_create()
        self.set_amount_real()
        return True
    
    @api.multi
    def set_amount_real(self):
        for x in self.line_ids :
            x.amount_reimbursed = 0
            if self.kas_bon:
                x.amount_real = 0
            else:
                x.amount_real = x.amount
                    
    @api.multi
    def reimbursed_pettycash(self):
        self.state = 'reimbursed'
    
    @api.multi
    def cancel_pettycash(self):
        if self.move_id:
            self.move_id.action_reverse_journal()
        self.state = 'cancel'
        self.date_cancel = datetime.today()
        self.cancel_uid = self._uid
        self.cancel_date = datetime.now()
     
    @api.cr_uid_ids_context
    def action_move_line_create(self, cr, uid, ids, context=None):
        if context is None:
            context = {}
        move_pool = self.pool.get('account.move')
        move_line_pool = self.pool.get('account.move.line')
        periods = self.pool.get('account.period').find(cr, uid, context=context)
        for pettycash in self.browse(cr, uid, ids, context=context):
            pettycash.write({'period_id':periods and periods[0]})
            name = pettycash.name
            date = pettycash.date
            journal_id = pettycash.journal_id.id
            account_id = pettycash.journal_id.default_credit_account_id.id or pettycash.journal_id.default_debit_account_id.id
            amount = pettycash.amount          
            period_id = pettycash.period_id.id
            
            move = {
                'name': name,
                'journal_id': journal_id,
                'ref':name,
                'date': datetime.now().strftime('%Y-%m-%d'),
                'period_id':period_id,
                'transaction_id':pettycash.id,
                'model':pettycash.__class__.__name__,
            }
            move_id = move_pool.create(cr, uid, move, context=None)

            names = []
            for y in pettycash.line_ids:
                names.append(y.name)
            names = ', '.join(names)

            move_line1 = {
                'name': _('Petty Cash Out: %s' % names),
                'ref':name,
                'account_id': account_id,
                'move_id': move_id,
                'journal_id': journal_id,
                'period_id': period_id,
                'date': datetime.now().strftime('%Y-%m-%d'),
                'debit': 0.0,
                'credit': pettycash.amount,
                'branch_id' : pettycash.branch_id.id,
                'division' : pettycash.division,
                'analytic_account_id' : pettycash.analytic_4.id                    
            }           
            line_id = move_line_pool.create(cr, uid, move_line1, context)            
            for y in pettycash.line_ids :
                move_line_2 = {
                    'name': y.name,
                    'ref':name,
                    'account_id': y.account_id.id,
                    'move_id': move_id,
                    'journal_id': journal_id,
                    'period_id': period_id,
                    'date': datetime.now().strftime('%Y-%m-%d'),
                    'debit': y.amount,
                    'credit': 0.0,
                    'branch_id' : pettycash.branch_destination_id.id,
                    'division' : pettycash.division,
                    'analytic_1': y.analytic_1.id,
                    'analytic_2': y.analytic_2.id,
                    'analytic_3': y.analytic_3.id,
                    'analytic_4': y.analytic_4.id,
                    'analytic_account_id' : y.analytic_4.id                    
                }           
                line_id2 = move_line_pool.create(cr, uid, move_line_2, context)
                
            # self.create_intercompany_lines(cr,uid,ids,move_id,context=None)      
            if  pettycash.journal_id.entry_posted :    
                posted = move_pool.post(cr, uid, [move_id], context=None)
            self.write(cr, uid, pettycash.id, {'date':datetime.today(),'state': 'posted', 'move_id': move_id,'account_id':account_id,'confirm_uid':uid,'confirm_date':datetime.now()})
        return True 

    @api.cr_uid_ids_context   
    def create_intercompany_lines(self,cr,uid,ids,move_id,context=None):
        branch_rekap = {}       
        branch_pool = self.pool.get('dym.branch')        
        vals = self.browse(cr,uid,ids) 
        move_line = self.pool.get('account.move.line')
        move_line_srch = move_line.search(cr,uid,[('move_id','=',move_id)])
        move_line_brw = move_line.browse(cr,uid,move_line_srch)
        
        branch = branch_pool.search(cr,uid,[('id','=',vals.branch_id.id)])

        if branch :
            branch_browse = branch_pool.browse(cr,uid,branch)
            inter_branch_header_account_id = branch_browse.inter_company_account_id.id
            if not inter_branch_header_account_id :
                raise osv.except_osv(('Perhatian !'), ("Account Inter Company belum diisi dalam Master branch %s !")%(vals.branch_id.name))
        
        #Merge Credit and Debit by Branch                                
        for x in move_line_brw :
            if x.branch_id not in branch_rekap :
                branch_rekap[x.branch_id] = {}
                branch_rekap[x.branch_id]['debit'] = x.debit
                branch_rekap[x.branch_id]['credit'] = x.credit
            else :
                branch_rekap[x.branch_id]['debit'] += x.debit
                branch_rekap[x.branch_id]['credit'] += x.credit  
        
        #Make account move       
        for key,value in branch_rekap.items() :
            if key != vals.branch_id :
                config = branch_pool.search(cr,uid,[('id','=',key.id)])
        
                if config :
                    config_browse = branch_pool.browse(cr,uid,config)
                    inter_branch_detail_account_id = config_browse.inter_company_account_id.id                
                    if not inter_branch_detail_account_id :
                        raise osv.except_osv(('Perhatian !'), ("Account Inter belum diisi dalam Master branch %s - %s!")%(key.code, key.name))

                balance = value['debit']-value['credit']
                debit = abs(balance) if balance < 0 else 0
                credit = balance if balance > 0 else 0
                
                if balance != 0:
                    move_line_create = {
                        'name': _('Interco Petty Cash Out %s')%(key.name),
                        'ref':_('Interco Petty Cash Out %s')%(key.name),
                        'account_id': inter_branch_header_account_id,
                        'move_id': move_id,
                        'journal_id': vals.journal_id.id,
                        'period_id': vals.period_id.id,
                        'date': vals.date,
                        'debit': debit,
                        'credit': credit,
                        'branch_id' : key.id,
                        'division' : vals.division                    
                    }    
                    inter_first_move = move_line.create(cr, uid, move_line_create, context)    
                             
                    move_line2_create = {
                        'name': _('Interco Petty Cash Out %s')%(vals.branch_id.name),
                        'ref':_('Interco Petty Cash Out %s')%(vals.branch_id.name),
                        'account_id': inter_branch_detail_account_id,
                        'move_id': move_id,
                        'journal_id': vals.journal_id.id,
                        'period_id': vals.period_id.id,
                        'date': vals.date,
                        'debit': credit,
                        'credit': debit,
                        'branch_id' : vals.branch_id.id,
                        'division' : vals.division                    
                    }    
                    inter_second_move = move_line.create(cr, uid, move_line2_create, context)       
        return True
        
    @api.cr_uid_ids_context
    def unlink(self, cr, uid, ids, context=None):
        for item in self.browse(cr, uid, ids, context=context):
            if item.state != 'draft':
                raise osv.except_osv(('Perhatian !'), ("Petty Cash sudah diproses, data tidak bisa didelete !"))
        return super(dym_pettycash, self).unlink(cr, uid, ids, context=context) 

    @api.onchange('amount')
    def amount_change(self):    
        self.amount = sum([x.amount for x in self.line_ids])
        warning = {}     
        if self.amount < 0 :
            self.amount = 0 
            warning = {
                'title': ('Perhatian !'),
                'message': (("Nilai amount tidak boleh kurang dari 0")),
            }                      
            return {'warning':warning}

        max_amount = self.env['dym.branch.config'].search([('branch_id','=',self.branch_id.id)])
        if max_amount and max_amount.petty_cash_limit and self.amount > max_amount.petty_cash_limit:            
            warning = {
                'title': ('Perhatian !'),
                'message': (("Nilai amount tidak boleh dari limit (%s)" % '{:20,.2f}'.format(max_amount.petty_cash_limit))),
            }                      
            return {'warning':warning}


    @api.onchange('line_ids')
    def amount_line_ids(self):
        self.amount = sum([x.amount for x in self.line_ids])
class tools_helpdesk_incidencia(models.Model):
    _name = 'tools.helpdesk.incidencia'
    _inherit = ['mail.thread', 'ir.needaction_mixin']
    _rec_name = 'codigo'
    _description = 'Incidencia'

    codigo = fields.Char('Código', size=10, help="Código de la Incidencia")
    solicitante_id = fields.Many2one(
        'res.users',
        string="Solicitante",
        help='Nombre Completo del Solicitante de la Incidencia')
    res_partner_id = fields.Many2one(related='solicitante_id.res_partner_id',
                                     string='Organización')
    contexto_nivel1_id = fields.Many2one('tools.helpdesk.contexto_nivel1',
                                         'Aplicación')
    contexto_nivel2_id = fields.Many2one('tools.helpdesk.contexto_nivel2',
                                         'Módulo')
    contexto_nivel3_id = fields.Many2one('tools.helpdesk.contexto_nivel3',
                                         'Operación')
    categoria_incidencia_id = fields.Many2one(
        'tools.helpdesk.categoria_incidencia',
        string="Categoría de Incidencia")
    tipo_incidencia_id = fields.Many2one('tools.helpdesk.tipo_incidencia',
                                         'Tipo de Incidencia')
    state = fields.Selection([('registrado', 'Registrado'),
                              ('recibido', 'Recibido'),
                              ('asignado', 'Asignado'),
                              ('proceso', 'En Proceso'),
                              ('atendido', 'Atendido'),
                              ('resuelto', 'Resuelto'),
                              ('anulado', 'Anulado')], "Status")
    observacion_ids = fields.One2many('tools.helpdesk.observacion',
                                      'incidencia_id',
                                      string="Observaciones",
                                      help='Observaciones de una incidencia')
    autorizado = fields.Char(
        'Autorizado por:',
        size=30,
        help='Colocar el Nombre y Apellido del autorizante')
    asignacion = fields.Many2one('res.users', 'Asignado a:')
    denominacion = fields.Char('Descripción Corta', size=90)
    prioridad = fields.Selection([('0', 'Ninguna'), ('1', 'Baja'),
                                  ('2', 'Media'), ('3', 'Urgente')],
                                 'Prioridad',
                                 default='0')
    fecha_actual = fields.Date('Fecha de la solicitud',
                               help='Fecha cuando se reporto la incidenciaa',
                               default=datetime.today())
    #memo = fields.Boolean('Memo')
    #correo = fields.Boolean('Correo Electrónico')
    #llamada = fields.Boolean('Llamada Telefonica')
    #presencial = fields.Boolean('Presencial')
    #gestion = fields.Boolean('Gestion Documental')
    #n_memo = fields.Char('Número de Memo')
    #Para adjuntar los documentos a enviar.
    adjunto_ids = fields.One2many(
        'tools.helpdesk.adjuntos',
        'incidencia_id',
        string="Adjuntos",
        help='Documentos adicionales, Respaldos Fisicos')
    #Fin del adjunto
    descripcion = fields.Text('Descripción')
    procedimiento = fields.Text('Procedimiento en la Solución')
    fecha_creacion = fields.Datetime('Fecha de Creación', default=0)
    fecha_recibido = fields.Datetime('Fecha de Recibido')
    fecha_asignado_a = fields.Datetime('Fecha Asignado a')
    fecha_proceso = fields.Datetime('Fecha Proceso')
    fecha_atendido = fields.Datetime('Fecha Resuelto')
    fecha_solucion = fields.Datetime('Fecha Cerrado')
    dia_creacion = fields.Char('Días de Creado')
    dia_recibido = fields.Char('Días Intervalo Creado a Recibido')
    dia_asignado_a = fields.Char('Días Intervalo Recibido a Asignado')
    dia_proceso = fields.Char('Días Intervalo Asignado a Proceso')
    dia_atendido = fields.Char('Días Intervalo Proceso a Resuelto')
    dia_solucion = fields.Char('Días Intervalo Resuelto a Cerrado')
    retraso = fields.Integer(
        'Dias Transcurridos',
        help="Conteo de dias a pertir de la fecha de entrega",
        readonly="True",
        compute="_compute_calculo_dias",
        store="False")

    _defaults = {'solicitante_id': lambda self, cr, uid, ctx=None: uid}

    #@api.onchange('solicitante_id')
    #def actualizar_organizacion_solicitante(self):
    #    self.res_partner_id = self.solicitante_id.res_partner_id.id

    #def onchange_solicitante(self, cr, uid, ids):
    #    return {'value':{'solicitante_id': uid}}

    _order = 'codigo desc'  #PARA ORDENAR POR CODICO DE MAYOR A MENOR

    def create(self, cr, uid, vals, context=None):
        #vals['solicitante_id'] = uid
        vals.update({
            'codigo':
            self.pool.get('ir.sequence').get(cr, uid,
                                             'tools.helpdesk.incidencia')
        })
        vals.update({'fecha_creacion': datetime.today()})
        new_id = super(tools_helpdesk_incidencia, self).create(cr,
                                                               uid,
                                                               vals,
                                                               context=None)
        return new_id

    # Accion para Botones en el proceso Workflow

    def enviar_mensaje_status(self):
        """Método utilizado para definir el mensaje junto al status
        que se enviará en el mensaje dentro de openchatter"""
        message = "El estatus ha sido cambiado a <strong><em>%s</em></strong>" % self.state
        self.message_post(body=message,
                          type='email',
                          subtype='mail.mt_comment')

    @api.one
    def action_registrado(self):
        self.state = 'registrado'
        self.message_subscribe_users(user_ids=[1, self.solicitante_id.id])

    @api.one
    def action_recibido(self):
        self.fecha_recibido = datetime.today()
        diferencia = self.calcular_dias(self.fecha_creacion,
                                        self.fecha_recibido)
        self.dia_recibido = diferencia.days
        self.state = 'recibido'
        self.enviar_mensaje_status()

    @api.one
    def action_asignado(self):
        if not self.asignacion:
            raise osv.except_osv(('Error'),
                                 ('Debes llenar el campo: asignado a'))
        self.fecha_asignado_a = datetime.today()
        diferencia = self.calcular_dias(self.fecha_recibido,
                                        self.fecha_asignado_a)
        self.dia_asignado_a = diferencia.days
        self.state = 'asignado'
        self.enviar_mensaje_status()
        self.message_subscribe_users(user_ids=[self.asignacion.id])

        # PARA ENVIAR E-MAIL
        cuerpo_mensaje = """Se le ha asignado una Ticket en Help Desk:<br>
        Codigo: %s,<br>
        Asunto: %s,<br>
        Descripcion: %s,<br> """ % (self.codigo, self.denominacion,
                                    self.descripcion)
        const_mail = {
            'email_from': self.solicitante_id.email,
            'email_to': self.asignacion.login,
            #'partner_ids' : [(0,0,{'res_partner_id':self.asignacion.partner_id, 'mail_message_id': ids_mail})],
            'subject': "Re: %s" % self.codigo,
            'body_html': cuerpo_mensaje
        }
        ids_mail = self.env['mail.mail'].create(const_mail).send()
        return True

    # FIN DE EMAIL

    @api.one
    def action_proceso(self):
        self.fecha_proceso = datetime.today()
        diferencia = self.calcular_dias(self.fecha_asignado_a,
                                        self.fecha_proceso)
        self.dia_proceso = diferencia.days
        self.state = 'proceso'
        self.enviar_mensaje_status()

    @api.one
    def action_atendido(self):
        self.fecha_atendido = datetime.today()
        diferencia = self.calcular_dias(self.fecha_proceso,
                                        self.fecha_atendido)
        self.dia_atendido = diferencia.days
        self.state = 'atendido'
        self.enviar_mensaje_status()

        # PARA ENVIAR E-MAIL AL SOLICITANTE
        cuerpo_mensaje = """

        Estimado usuario,<br>
        Le informamos que su REQUERIMIENTO DE SOPORTE, bajo el ticket No. <strong>%s</strong>,<br>
        ha sido procesado satisfactoriamente, por el Departamento de HELPDESK.<br>
        Su estatus actual es: <strong>ATENDIDO</strong><br>
        El asunto de su Ticket es: <em>%s</em><br>
        La Descripcion de su Ticket es: <em>%s</em><br>
        <br>
        Por favor, confirme que fue solucionado su requerimiento cambiando el estatus a RESUELTO<br>
        Puede seguir su ticket a traves de la direccion http://ovniticket.ovnicom.com:8069<br>
        """ % (self.codigo, self.denominacion, self.descripcion)

        const_mail = {
            'email_from': self.asignacion.login,
            'email_to': self.solicitante_id.email,
            #'partner_ids' : [(0,0,{'res_partner_id':self.asignacion.partner_id, 'mail_message_id': ids_mail})],
            'subject': "Re: %s" % self.codigo,
            'body_html': cuerpo_mensaje
        }

        ids_mail = self.env['mail.mail'].create(const_mail).send()

    @api.one
    def action_resuelto(self):
        self.fecha_solucion = datetime.today()
        diferencia = self.calcular_dias(self.fecha_atendido,
                                        self.fecha_solucion)
        self.dia_solucion = diferencia.days
        self.state = 'resuelto'
        self.enviar_mensaje_status()

        return True

    @api.one
    def action_anulado(self):
        self.state = 'anulado'
        self.enviar_mensaje_status()

    #Fin de las acciones en los botones

    # PARA CALCULAR LOS DIAS DE UN PROCESO A OTRO
    def calcular_dias(self, fecha_primera, fecha_segunda):
        formato_fecha = "%Y-%m-%d"
        fc = datetime.strptime(fecha_primera, "%Y-%m-%d %H:%M:%S")
        fh = datetime.strptime(fecha_segunda, "%Y-%m-%d %H:%M:%S")
        fecha_hoy = datetime.strftime(fh, formato_fecha)
        fecha_creado = datetime.strftime(fc, formato_fecha)
        diferencia = datetime.strptime(
            fecha_hoy, formato_fecha) - datetime.strptime(
                fecha_creado, formato_fecha)  #fecha_hoy - fecha_creado
        return diferencia

    #FIN DEL CALCULO PARA LOS DIAS DE UN PROCESO A OTRO

    #CALCULA LOS DIAS TRANSCURRIDOS
    @api.depends('fecha_actual')
    def _compute_calculo_dias(self):
        carga = datetime.strptime(self.fecha_actual, '%Y-%m-%d')
        dias = datetime.today() - carga
        self.retraso = dias.days
        return True
Exemple #22
0
class dym_reimbursed_ho(models.Model):
    _name = 'dym.reimbursed.ho'
    _description = "Reimbursed HO"
    _inherit = ['mail.thread']

    STATE_SELECTION = [
        ('draft', 'Draft'),
        ('request', 'Requested'),
        ('approved', 'Approved'),
        ('done', 'Done'),
        ('cancel', 'Cancelled'),
    ]

    @api.one
    @api.depends('line_ids.amount')
    def _compute_amount(self):
        amount = sum(line.total_net for line in self.settle_ids)
        self.amount_total = amount

    @api.cr_uid_ids_context
    def _get_default_branch(self, cr, uid, ids, context=None):
        user_obj = self.pool.get('res.users')
        user_browse = user_obj.browse(cr, uid, uid)
        branch_ids = False
        branch_ids = user_browse.branch_ids and len(
            user_browse.branch_ids
        ) == 1 and user_browse.branch_ids[0].id or False
        return branch_ids

    def terbilang(self, amount):
        hasil = fungsi_terbilang.terbilang(amount, "idr", 'id')
        return hasil

    def ubah_tanggal(self, tanggal):
        try:
            conv = datetime.strptime(tanggal, '%d-%m-%Y %H:%M')
            return conv.strftime('%d/%m/%Y')
        except Exception as e:
            conv = datetime.strptime(tanggal, '%Y-%m-%d %H:%M:%S')
            return conv.strftime('%d/%m/%Y')

    # @api.one
    # @api.depends('line_ids')
    # def _count_detail_payslip(self):
    #     settle_ids = []
    #     count = 0
    #     for line in self.line_ids:
    #         if line.settlement_id.id in settle_ids:
    #             continue
    #         count += 1
    #         settle_ids.append(line.settlement_id.id)
    #     self.settle_count = count

    @api.model
    def _getCompanyBranch(self):
        user = self.env.user
        if user.branch_type != 'HO':
            if not user.branch_id:
                raise osv.except_osv(('Perhatian !'), (
                    "User %s tidak memiliki default branch. Hubungi system administrator agar menambahkan default branch di User Setting."
                    % self.env.user.name))
            return [('id', '=', user.branch_id.id)]
        company_id = self._context.get('company_id',
                                       self.env.user.company_id.id)
        branch_ids = [
            b.id for b in self.env.user.branch_ids
            if b.company_id.id == company_id
        ]
        return [('id', 'in', branch_ids)]

    name = fields.Char(string="Name", readonly=True, default='')
    company_id = fields.Many2one('res.company',
                                 string='Company',
                                 required=True,
                                 index=True,
                                 default=lambda self: self.env.user.company_id,
                                 help="Company related to this journal")
    branch_id = fields.Many2one('dym.branch',
                                string='Branch',
                                required=True,
                                domain=_getCompanyBranch)
    division = fields.Selection([('Unit', 'Showroom'),
                                 ('Sparepart', 'Workshop'),
                                 ('Umum', 'General'), ('Finance', 'Finance')],
                                string='Division',
                                default='Umum',
                                change_default=True,
                                select=True)
    journal_id = fields.Many2one(
        'account.journal',
        string="Payment Method",
        domain=
        "[('branch_id','in',[branch_id,False]),('type','in',['pettycash','cash','bank'])]"
    )
    state = fields.Selection(STATE_SELECTION,
                             string='State',
                             readonly=True,
                             default='draft')
    date_request = fields.Date(string="Date Requested",
                               required=True,
                               readonly=True,
                               default=fields.Date.context_today)
    date_approve = fields.Date(string="Date Approved", readonly=True)
    date_cancel = fields.Date(string="Date Canceled", readonly=True)
    amount_total = fields.Float(
        string='Total Amount',
        digits=dp.get_precision('Account'),
        store=True,
        readonly=True,
        compute='_compute_amount',
    )
    confirm_uid = fields.Many2one('res.users', string="Requested by")
    confirm_date = fields.Datetime('Requested on')
    cancel_uid = fields.Many2one('res.users', string="Cancelled by")
    cancel_date = fields.Datetime('Cancelled on')
    # settle_count = fields.Integer(compute=_count_detail_payslip, string="Items")
    settle_ids = fields.Many2many('dym.settlement',
                                  'reimbursed_settle_avp_rel',
                                  'reimbursed_id',
                                  'settle_avp_id',
                                  string='Settlement')
    line_ids = fields.One2many('dym.reimbursed.ho.line',
                               'reimbursed_id',
                               string='Reimburse Details',
                               compute='_compute_details',
                               store=True)
    notes = fields.Char('Notes')

    @api.depends('settle_ids')
    def _compute_details(self):
        if self.settle_ids:
            vals = []
            for settle in self.settle_ids:
                for line in settle.settlement_line:
                    vals.append((0, 0, {
                        'name': str(settle.description or settle.name),
                        'settlement_id': settle.id,
                        'account_id': line.account_id.id,
                        'amount': line.amount,
                    }))
            self.line_ids = vals

    @api.model
    def default_get(self, fields):
        res = super(dym_reimbursed_ho, self).default_get(fields)
        user = self.env.user
        # if not user.branch_id:
        #     raise osv.except_osv(('Perhatian !'), ("User %s tidak memiliki default branch. Hubungi system administrator agar menambahkan default branch di User Setting." % self.env.user.name))

        res['branch_id'] = user.branch_id.id
        if user.branch_type != 'HO':
            res['division'] = 'Finance'
        else:
            # raise osv.except_osv(('Perhatian !'), ("User %s tidak diijinkan untuk membuat transaksi ini." % self.env.user.name))
            return res

    @api.multi
    def action_validate(self):
        warning = {}
        if not self.line_ids:
            raise osv.except_osv(('Perhatian !'), (
                "Tidak ditemukan baris baris transaksi, silahkan Compute dulu. Tapi jika ternyata memang tidak ada transaksi pada periode yang dipilih, silahkan coba lagi periode berikutnya."
            ))
        else:
            self.name = self.env['ir.sequence'].get_per_branch(
                self.branch_id.id, 'RBK', division=self.division)
            self.action_post()

    @api.model
    def create(self, vals, context=None):
        rekap = []
        vals['name'] = self.env['ir.sequence'].get_per_branch(
            vals['branch_id'], 'RAP', division='Umum')
        vals['date_request'] = datetime.today()

        reimbursed_id = super(dym_reimbursed_ho, self).create(vals)
        return reimbursed_id

    @api.multi
    def cancel(self):
        self.state = 'cancel'
        self.date_cancel = datetime.today()
        self.cancel_uid = self._uid
        self.cancel_date = datetime.now()

    @api.multi
    def request(self):
        cash = ''
        self.message_post(
            body=_("Reimbursed Requested Advance Payment No: <br/>%s") %
            (cash))
        self.state = 'request'
        self.confirm_uid = self._uid
        self.confirm_date = datetime.now()
        self.date_request = datetime.today()

    @api.multi
    def approve(self):
        cash = ''
        self.message_post(body=_(
            "Reimbursed Approved <br/> Advance Payment No : <br/>  %s ") %
                          (cash))
        self.state = 'approved'
        self.date_approve = datetime.today()

    @api.onchange('branch_id', 'division')
    def onchange_settlement(self):
        dom = {}
        val = {}
        if self.branch_id:
            if self._context.get('transaction_type', False) == 'avp':
                # branch = self.env['dym.branch'].browse(self.branch_id.id)
                account_bank_ids = self.env['account.journal'].search([
                    ('company_id', '=', self.branch_id.company_id.id),
                    ('type', '=', 'cash')
                ])
                bank_ids = [x.id for x in account_bank_ids]
                settlement = self.env['dym.settlement'].search([
                    ('branch_id', '=', self.branch_id.id),
                    ('division', '=', self.division), ('state', '=', 'done'),
                    ('amount_total', '>', 0),
                    ('payment_method', 'in', bank_ids)
                ])
                settle = [x.id for x in settlement]
                dom['settle_ids'] = [('id', 'in', settle)]
        return {'domain': dom}

    @api.cr_uid_ids_context
    def button_dummy(self, cr, uid, ids, context=None):
        return True
Exemple #23
0
class dym_journal_elimination(models.Model):
    _name = 'dym.journal.elimination'
    _description = 'Journal Elimination (ALL COMPANY)'

    STATE_SELECTION = [
        ('draft', 'Draft'),
        ('waiting_for_approval','Waiting For Approval'),
        ('confirm','Confirmed'),
        ('cancel','Cancelled')
    ]
                    
    @api.cr_uid_ids_context
    def get_group_company(self,cr,uid, ids, context=None):
        user_obj = self.pool.get('res.users').browse(cr, SUPERUSER_ID, uid)
        company = user_obj.company_id
        while company.parent_id:
            company = company.parent_id
        return company

    @api.cr_uid_ids_context
    def _get_default_branch(self,cr,uid,ids,context=None):
        user_obj = self.pool.get('res.users')        
        user_browse = user_obj.browse(cr,SUPERUSER_ID,uid)
        branch_ids = False
        branch_ids = user_browse.branch_ids and len(user_browse.branch_ids) == 1 and user_browse.branch_ids[0].id or False                
        return branch_ids 
            
    branch_id = fields.Many2one('dym.branch', string='Branch Approval', required=True, default=_get_default_branch)
    division = fields.Selection([('Finance','Finance')], string='Division',default='Finance', required=True,change_default=True, select=True)
    name = fields.Char(string='No')
    date = fields.Date(string="Date",required=True,readonly=True, default=fields.Date.context_today)
    periode_id = fields.Many2one('account.period', required=True, string='Periode')
    state= fields.Selection(STATE_SELECTION, string='State', readonly=True,default='draft')
    move_consol_ids = fields.Many2many('account.move.line.consol', 'move_consol_elim_rel', 'consol_line_id', 'elim_id', 'Journal Consolidation')
    move_id = fields.Many2one('account.move.consol', string='Account Entry', copy=False)
    move_ids = fields.One2many('account.move.line.consol',related='move_id.line_id',string='Journal Elimination', readonly=True)
    confirm_uid = fields.Many2one('res.users',string="Confirmed by")
    confirm_date = fields.Datetime('Confirmed on')
    approval_ids = fields.One2many('dym.approval.line','transaction_id',string="Table Approval",domain=[('form_id','=',_name)])
    approval_state =  fields.Selection([
        ('b','Belum Request'),
        ('rf','Request For Approval'),
        ('a','Approved'),
        ('r','Reject')
    ],'Approval State', readonly=True,default='b')
    filename = fields.Char('Filename') 
    datafile = fields.Binary('Data File')
    move_diff_ids = fields.One2many('account.move.line.consol','elimination_id','Different Sale Journals')
    
    @api.onchange('periode_id')
    def fill_consol(self):
        domain = {}
        if self.periode_id:
            if self.periode_id.state == 'done':
                self.move_consol_ids = False
                raise osv.except_osv(('Perhatian !'), ("Period: %s sudah di close")%(self.periode_id.name))  
            company = self.get_group_company()
            period = self.periode_id
            date_start = datetime.strptime(period.date_start, DEFAULT_SERVER_DATE_FORMAT).strftime(DEFAULT_SERVER_DATE_FORMAT)
            date_stop = datetime.strptime(period.date_stop, DEFAULT_SERVER_DATE_FORMAT).strftime(DEFAULT_SERVER_DATE_FORMAT)  
            branch_period_ids = period.search([('company_id','!=',company.id),('date_start','=',period.date_start),('date_stop','=',period.date_stop)])
            branch_unconsolidated_ids = []
            if branch_period_ids:
                request = ("SELECT lx.branch_id as branch_id FROM account_move_line lx left join account_move mx on lx.move_id = mx.id left join account_period ax on mx.period_id = ax.id WHERE ax.id in %s and (lx.consolidate_posted = 'f' or  lx.consolidate_posted is null) and mx.state = 'posted' and lx.branch_id is not null group by lx.branch_id")
                params = (tuple(branch_period_ids.ids),)
                self._cr.execute(request, params)
                rows = self._cr.dictfetchall()
                branch_unconsolidated_ids = [row['branch_id'] for row in rows]

            # if branch_unconsolidated_ids:
            #     branch_unconsolidated = self.env['dym.branch'].browse(branch_unconsolidated_ids)
            #     self.move_consol_ids = False
            #     raise osv.except_osv(('Perhatian !'), ("Period: %s branch: %s belum di consolidate")%(period.name,', '.join(branch_unconsolidated.mapped('name')))) 

            # request = ("SELECT l.id as line_id FROM account_move_line_consol l left join account_move_consol m on l.move_id = m.id left join account_period a on m.period_id = a.id left join account_move_line lx on l.consolidation_move_line_id = lx.id WHERE lx.move_id in (select ly.move_id from account_move_line_consol lz left join res_partner p on p.id = lz.partner_id left join account_move_line ly on ly.id = lz.consolidation_move_line_id left join account_move_consol mz on mz.id = lz.move_id where p.partner_type = 'Konsolidasi' and lz.period_id = %s and (lz.eliminate_posted = 'f' or lz.eliminate_posted is null) and mz.state = 'posted' and lz.elimination_move_line_id is null) and a.id = %s and (l.eliminate_posted = 'f' or l.eliminate_posted is null) and m.state = 'posted' and l.elimination_move_line_id is null order by lx.move_id")
            where_account = " l.account_id in %s" % str(tuple([x.account_id.id for x in self.periode_id.company_id.account_elimination_line]))
            where_period = " l.period_id = %s" % str(self.periode_id.id)
            where_journal_type = " jx.type in ('cash','bank')"
            where_journal_jual = " jx.type in ('sale','sale_refund','purchase','purchase_refund')"
            contain = "intercompany"
            request = ("""SELECT l.id as line_id FROM account_move_line_consol l
                        left join account_move_line lx on l.consolidation_move_line_id = lx.id
                        left join account_journal jx on lx.journal_id = jx.id
                        WHERE %s  AND ((%s AND %s) OR (%s AND %s AND jx.name like '%%%%%s%%%%'))""" % (where_period,where_account,where_journal_type,where_account,where_journal_jual,contain)) 
            
            params = ((self.periode_id.id),(self.periode_id.id),)
            self._cr.execute(request, params)
            rows = self._cr.dictfetchall()
            line_ids = [row['line_id'] for row in rows]
            if not line_ids:
                self.move_consol_ids = False
                raise osv.except_osv(('Perhatian !'), ("Period: %s tidak ditemukan transaksi intercompany untuk dieliminasi")%(period.name)) 
            domain['move_consol_ids'] = [('id','in',line_ids)]
        else:
            self.move_consol_ids = False
            domain['move_consol_ids'] = [('id','=',0)]
        return {'domain':domain}

    @api.model
    def create(self,vals,context=None):
        vals['name'] = self.env['ir.sequence'].get_per_branch(vals['branch_id'], 'JEL', division=False) 
        vals['date'] = datetime.today() 
        res =  super(dym_journal_elimination, self).create(vals)  
        return res

    @api.multi
    def write(self,values,context=None):
        res =  super(dym_journal_elimination,self).write(values)
        return res

    @api.multi
    def generate_elimination(self):
        self.action_create_move_line_eliminate()
        if self.move_diff_ids:
            move = False
            for line in self.move_diff_ids:
                move = line.move_id
                line.write({'move_id':self.move_ids[0].move_id.id})
            move.unlink()

    @api.multi
    def action_create_move_line_eliminate(self):
        move_pool = self.env['account.move.consol']
        move_line_pool = self.env['account.move.line.consol']
        period_obj = self.env['account.period']
        company = self.get_group_company()
        journal_id = company.journal_eliminate_multi_company_id.id 
        if not company.journal_eliminate_multi_company_id:
            raise osv.except_osv(('Perhatian !'), ("Journal eliminasi multi company belum diisi di %s!")%(company.name)) 
        if self.periode_id.company_id != company:
            raise osv.except_osv(('Perhatian !'), ("Period yang diisi harus periode grup company")) 
        if self.periode_id.state == 'done':
            raise osv.except_osv(('Perhatian !'), ("Period: %s sudah di close")%(self.periode_id.state.name))  
        name = self.name
        date = time.strftime('%Y-%m-%d %H:%M:%S')
        partner_consol = self.move_consol_ids.mapped('partner_id').filtered(lambda r: r.partner_type != 'Konsolidasi')
        if partner_consol:
            raise osv.except_osv(_('Error!'), _('Partner %s bukan partner konsolidasi!.')%(', '.join(partner_consol.mapped('name'))))
        elim_posted = self.move_consol_ids.filtered(lambda r: r.eliminate_posted == True)
        if elim_posted:
            raise osv.except_osv(_('Error!'), _('Jurnal %s sudah di eliminasi!.')%(', '.join(elim_posted.mapped('consolidation_move_line_id.move_id.name'))))
        rows = self.move_consol_ids.read(['move_id', 'id',  'name',  'ref', 'account_id', 'credit', 'debit',  'branch_id',  'division', 'currency_id', 'product_id', 'product_uom_id', 'amount_currency', 'quantity', 'company_id', 'partner_id', 'analytic_account_id', 'tax_code_id', 'tax_amount'])
        eliminate_line = []
        eliminate_move_ids = []
        eliminate_move_line_ids = []
        for row in rows:
            row['analytic_account_id'] = row['analytic_account_id'][0] if row['analytic_account_id'] else False
            row['branch_id'] = row['branch_id'][0] if row['branch_id'] else False
            row['partner_id'] = row['partner_id'][0] if row['partner_id'] else False
            row['tax_code_id'] = row['tax_code_id'][0] if row['tax_code_id'] else False
            row['currency_id'] = row['currency_id'][0] if row['currency_id'] else False
            row['product_id'] = row['product_id'][0] if row['product_id'] else False
            row['move_id'] = row['move_id'][0] if row['move_id'] else False
            row['account_id'] = row['account_id'][0] if row['account_id'] else False
            row['product_uom_id'] = row['product_uom_id'][0] if row['product_uom_id'] else False
            row['company_id'] = row['company_id'][0] if row['company_id'] else False
            debit = row['debit']
            credit = row['credit']
            row['credit'] = debit
            row['debit'] = credit
            if row['move_id'] not in eliminate_move_ids:
                eliminate_move_ids.append(row['move_id'])
            if row['id'] not in eliminate_move_line_ids:
                eliminate_move_line_ids.append(row['id'])
            row['elimination_move_line_id'] = row['id']
            row['period_id'] = self.periode_id.id
            row['date'] = date
            move_id = row['move_id']
            row_id = row['id']
            del row['id']
            del row['move_id']
            row['eliminated'] = True

            eliminate_line.append([0,False,row])
        if not eliminate_line:
            raise osv.except_osv(('Perhatian !'), ("Period: %s, tidak ditemukan jurnal entry yang akan dieliminasi")%(self.periode_id.name))
        move = {
            'name': name,
            'ref': name,
            'journal_id': journal_id,
            'date': date,
            'period_id':self.periode_id.id,
            'line_id':eliminate_line,
        }
        move_id = move_pool.create(move)
        move_line_pool.browse(eliminate_move_line_ids).with_context(bypass_check=True).write({'eliminated':True})
        if company.journal_eliminate_multi_company_id.entry_posted:
            posted = move_id.post()
        self.write({'state': 'confirm', 'move_id': move_id.id})
        return True

    @api.multi
    def wkf_request_approval(self):
        if not self.move_consol_ids:
            raise osv.except_osv(('Perhatian !'), ("Period: %s, tidak ditemukan jurnal entry yang akan dieliminasi")%(self.periode_id.name))
        total_debit = sum(line.credit for line in self.move_consol_ids)  
        total_credit = sum(line.debit for line in self.move_consol_ids) 
        if total_debit != total_credit:
            raise osv.except_osv(('Perhatian !'), ("Hasil eliminasi tidak balance! mohon di cek kembali"))
        obj_matrix = self.env["dym.approval.matrixbiaya"]
        obj_matrix.request_by_value(self, 0)

        self.state =  'waiting_for_approval'
        self.approval_state = 'rf'
        company = self.get_group_company()
        if not company.journal_eliminate_multi_company_id:
            raise osv.except_osv(('Perhatian !'), ("Journal eliminasi multi company belum diisi di %s!")%(company.name)) 
                
    @api.multi      
    def wkf_approval(self):       
        approval_sts = self.env['dym.approval.matrixbiaya'].approve(self)
        if approval_sts == 1:
            self.write({'date':datetime.today(),'approval_state':'a','confirm_uid':self._uid,'confirm_date':datetime.now()})
            self.action_create_move_line_eliminate()
        elif approval_sts == 0:
                raise osv.except_osv(('Perhatian !'), ("User tidak termasuk group Approval"))    
            
    @api.multi
    def has_approved(self):
        if self.approval_state == 'a':
            return True
        return False
    
    @api.multi
    def has_rejected(self):
        if self.approval_state == 'r':
            self.write({'state':'draft'})
            return True
        return False
    
    @api.one
    def wkf_set_to_draft(self):
        self.write({'state':'draft','approval_state':'r'})
                            
    @api.cr_uid_ids_context
    def unlink(self, cr, uid, ids, context=None):
        for item in self.browse(cr, uid, ids, context=context):
            if item.state != 'draft':
                raise osv.except_osv(('Perhatian !'), ("Journal Eliminasi tidak bisa didelete !"))
        return super(dym_journal_elimination, self).unlink(cr, uid, ids, context=context) 

    @api.multi
    def eksport_excel(self):
        data = []
        book = xlwt.Workbook()
        sheet = book.add_sheet("Selisih Penjualan")
        sheet2 = book.add_sheet("Total Selisih Penjualan")
        now = datetime.now()
        style = xlwt.easyxf('font: bold 1;')
        style_header = xlwt.easyxf('font: bold 1, name Calibri, height 210; pattern: pattern solid, fore_colour yellow;')

        debit_credit = {}
        header = ['Transaction', 'Ref Intercompany', 'Date','Branch'] 
        account_ids = [x for x in self.periode_id.company_id.account_fields_report_line]
        for account in account_ids:
            header.append(account.account_id.name)
            debit_credit[account.account_id.name] = account.credit
        header.append('Diff Amount')
        header.append('Bisnis Unit')
        data_dict = {}
        no = 0
        branch = {}
        for line in self.move_consol_ids:
            if line.account_id.name in header:
                data_dict[line.account_id.name] = line.debit or line.credit
                # no += 1
                intercom_ref = line._get_intercom_ref_id()
                bu = str(line.analytic_2.code)+' '+str(line.analytic_2.name)
                data.append({
                        # 'No': no,
                        'Transaction': line.consol_entry.name,
                        'Ref Intercompany': intercom_ref or self.intercom_ref or '',
                        'Date': line.consol_entry.date,
                        'Branch': line.branch_id.name,
                        line.account_id.name: data_dict[line.account_id.name],
                        'Diff Amount': (data_dict[line.account_id.name] * -1) if debit_credit[line.account_id.name] == True else data_dict[line.account_id.name],
                        'Bisnis Unit': bu,
                        'branch_id': line.branch_id.id,
                        'division': line.division,
                        'account_id': line.account_id.id,
                        'journal_id': line.company_id.journal_eliminate_multi_company_id.id,
                        'company_id': line.company_id.id,
                        'analytic_account_id': line.analytic_account_id.id,
                        'period_id': line.period_id.id,
                        })

                if line.branch_id.name+'#'+str(bu) not in branch:
                    branch[line.branch_id.name+'#'+str(bu)] = (data_dict[line.account_id.name] * -1) if debit_credit[line.account_id.name] == True else data_dict[line.account_id.name]
                else:
                    branch[line.branch_id.name+'#'+str(bu)] += (data_dict[line.account_id.name] * -1) if debit_credit[line.account_id.name] == True else data_dict[line.account_id.name]
                    
                
        trans_list = []
        uniq_list = []
        debit = 0
        credit = 0
        for d in data:
            if d['Transaction'] not in trans_list:   
                uniq_list.append(d)
                trans_list.append(d['Transaction'])
            else:
                for a in account_ids:
                    for datas in uniq_list:
                        if datas['Transaction'] == d['Transaction']:
                            if a.account_id.name in d:
                                if a.account_id.name not in datas:
                                    uniq_list[uniq_list.index(datas)][a.account_id.name] = d[a.account_id.name]
                                else:
                                    uniq_list[uniq_list.index(datas)][a.account_id.name] += d[a.account_id.name]
                                    
                                if debit_credit[a.account_id.name] == True:
                                    uniq_list[uniq_list.index(datas)]['Diff Amount'] -= d[a.account_id.name]                                      
                                else:
                                    uniq_list[uniq_list.index(datas)]['Diff Amount'] += d[a.account_id.name]

        obj_amlc = self.env['account.move.line.consol']
        obj_amc = self.env['account.move.consol']

        if not self.move_diff_ids:
            amc = obj_amc.create({
                        'journal_id':uniq_list[0]['journal_id'],
                        'period_id':uniq_list[0]['period_id'],
                        })
            for line in uniq_list:
                if line['Diff Amount'] != 0:
                    if not self.periode_id.company_id.account_elimination_diff_id:
                        raise osv.except_osv(('Perhatian !'), ("Account Elimination Diff. belum dilengkapi di Company"))       
                    else:
                        acc_elim_diff = self.periode_id.company_id.account_elimination_diff_id.id
                        obj_amlc.create({
                        'move_id': amc.id,
                        'analytic_account_id': line['analytic_account_id'],
                        'branch_id': line['branch_id'],
                        'division': line['division'],
                        'name': line['Transaction'],
                        'journal_id': line['journal_id'],                
                        'account_id': acc_elim_diff,
                        'company_id': line['company_id'],
                        'debit': line['Diff Amount'] * -1 if line['Diff Amount'] < 0 else 0,
                        'credit': line['Diff Amount'] if line['Diff Amount'] > 0 else 0,
                        'elimination_id': self.id,
                        'period_id': self.periode_id.id,
                        'date': self.create_date,                

                            }) 

        branch_list = []
        for b,x in branch.items():
            branch_list.append({
                    'Branch': b.split('#')[0],
                    'Amount': x,
                    'Bisnis Unit': b.split('#')[1]
            })


        uniq_list=sorted(uniq_list,key=lambda x: (x['Ref Intercompany'],x['Transaction']))

        no = 0; 
        for line in uniq_list:
            no += 1
            col = -1
            for i in header:
                col += 1
                if i in line:
                    sheet.write(no, col, line[i])

        colh = -1
        for x in header:
            colh += 1 
            sheet.write(0, colh, x)

        no = 0; 
        for line in branch_list:
            no += 1
            col = -1
            for i in ['Branch','Amount','Bisnis Unit']:
                col += 1
                if i in line:
                    sheet2.write(no, col, line[i])

        colh = -1
        for x in ['Branch','Amount','Bisnis Unit']:
            colh += 1 
            sheet2.write(0, colh, x)



        filename = 'Elimination_Report_on_%s.xls' % (now.strftime("%Y-%m-%d %H:%M:%S"))        
        file_data = StringIO.StringIO()
        book.save(file_data)
        out = base64.encodestring(file_data.getvalue())
        self.write({'datafile':out,'filename': filename})

        return True
Exemple #24
0
class MrpRawmaterialLine(models.Model):
    _name = 'mrp.raw.material.request.line'

    @api.depends('pick_qty', 'qty')
    def _compute_extra_qty(self):
        for rec in self:
            rec.extra_qty = rec.pick_qty - rec.qty
            print "selfkjhjstet tracjet======================================", rec.extra_qty

    @api.multi
    def get_available_qty(self):
        #to get available qty from stock>>>
        for line in self:
            if line.material_request_id.source_location:
                qty = 0
                quants = self.env['stock.quant'].search([
                    ('product_id', '=', line.product_id.id),
                    ('location_id', '=',
                     line.material_request_id.source_location.id)
                ])
                for q in quants:
                    qty += q.qty
                line.available_qty = qty - line.product_id.qty_reserved
            else:
                line.available_qty = line.product_id.qty_available - line.product_id.qty_reserved

    material_request_id = fields.Many2one('mrp.raw.material.request',
                                          'Request No.')
    product_id = fields.Many2one('product.product', string='Product')
    qty = fields.Float('Required Qty',
                       digits_compute=dp.get_precision('Stock qty'))
    extra_qty = fields.Float('Extra Qty',
                             digits_compute=dp.get_precision('Stock qty'),
                             compute='_compute_extra_qty')
    pick_qty = fields.Float('Pick Qty',
                            digits_compute=dp.get_precision('Stock qty'))
    uom_id = fields.Many2one('product.uom', string="Unit")
    shift_qty = fields.Float('Shift Qty')

    rm_type = fields.Selection([('stock', 'Stock'), ('mo', 'MO'),
                                ('po', 'PO')],
                               default='stock')
    pro_request_id = fields.Many2one('n.manufacturing.request',
                                     string='Production No.')
    production_id = fields.Many2one('mrp.production',
                                    string='Manufacturing No.')
    requisition_id = fields.Many2one('purchase.requisition', string='PRQ No.')
    pr_id = fields.Many2one('n.manufacturing.request',
                            string='PR No.',
                            related='production_id.request_line',
                            store=True)
    po_request_id = fields.Many2one('stock.purchase.request',
                                    string='Purchase Request No.')
    required_date = fields.Datetime('Required Date')
    expected_compl_date = fields.Datetime('Expected Completion Date')
    total_available_qty = fields.Float(
        'Total Stock',
        digits_compute=dp.get_precision('Stock qty'),
        related='product_id.qty_available')
    available_qty = fields.Float('Available Qty',
                                 digits_compute=dp.get_precision('Stock qty'),
                                 compute='get_available_qty')

    #pending_qty = fields.Float('Pending Qty',digits_compute=dp.get_precision('Stock qty'))
    #reserve_qty = fields.Float('Reserve Qty',digits_compute=dp.get_precision('Stock qty'))
    #res_ids = fields.One2many('reserve.history', 'rm_line_id', 'Reserve History')
    #reserve_status = fields.Selection([('draft','Draft'),('approve','Approve'),('reject','reject'),
    #				('cancel','Cancel'),('reserve','Reserve'),('send','Send')],default='draft')

    # reserve quantity of raw material for send to manufacture
    '''@api.multi
	def reserve_do(self):
		form_id = self.env.ref('api_raw_material.raw_material_reserve_wizard', False)
		if form_id:
		    qty=round(self.qty-self.reserve_qty,2) if (self.qty-self.reserve_qty)>0 else 0
		    return {
			'type': 'ir.actions.act_window',
			'view_type': 'form',
			'view_mode': 'form',
			'res_model': 'raw.material.reserve.release',
			'views': [(form_id.id, 'form')],
			'view_id': form_id.id,
			'target': 'new',
			'context': {'default_line_id': self.id,'default_product_id':self.product_id.id,
				'default_avl_qty':self.available_qty,'default_total_qty_reserve':qty,
				'default_avl_uom':self.uom_id.id,'default_uom_id2':self.uom_id.id,
				'default_reserve_uom':self.uom_id.id,'default_reserve_qty':qty},
		    }
		    
	# release quantity of reserve raw material 
	@api.multi
	def release_do(self):
		form_id = self.env.ref('api_raw_material.raw_material_release_wizard', False)
		if form_id:
		    return {
			'type': 'ir.actions.act_window',
			'view_type': 'form',
			'view_mode': 'form',
			'res_model': 'raw.material.reserve.release',
			'views': [(form_id.id, 'form')],
			'view_id': form_id.id,
			'target': 'new',
			'context': {'default_line_id': self.id,'default_product_id':self.product_id.id,
				'default_res_qty':self.reserve_qty,'default_reserve_uom':self.uom_id.id,
				'default_release_uom':self.uom_id.id,'default_release_qty':self.reserve_qty},
		    }

	# release quantity of reserve raw material 
	@api.multi
	def open_history(self):
		tree_id = self.env.ref('api_raw_material.raw_material_reserve_history_tree', False)
		if tree_id:
		    return {
			'type': 'ir.actions.act_window',
			'view_type': 'form',
			'view_mode': 'tree',
			'res_model': 'reserve.history',
			'views': [(tree_id.id, 'tree')],
			'view_id': tree_id.id,
			'target': 'new',
			'domain':[('rm_line_id','=',self.id)],
		    }'''

    @api.multi
    def back_schedule(self):
        error_string = ''
        try:
            for record in self:
                if record.pro_request_id:
                    if record.pro_request_id.state == 'draft':
                        body = '<b>Production Request Cancelled By Logistic Department:  </b>'
                        body += '<ul><li> Production No.:' + str(
                            record.pro_request_id.name) + '</li></ul>'
                        body += '<ul><li> Product Name : ' + str(
                            record.product_id.name) + '</li></ul>'
                        body += '<ul><li> Product Qty : ' + str(
                            record.qty) + '</li></ul>'
                        body += '<ul><li> Cancelled By  : ' + str(
                            self.env.user.name) + '</li></ul>'
                        body += '<ul><li> Cancelled Date  : ' + str(
                            date.today()) + '</li></ul>'
                        #record.pro_request_id.message_post(body=body)
                        record.message_post(body=body)
                        record.pro_request_id = False
                        record.rm_type = 'stock'
                    elif record.pro_request_id.state != 'draft':
                        error_string = "Production request in Process you can not cancel it."
                        raise
                if record.po_request_id:
                    purchase_request = self.env[
                        'stock.purchase.request.line'].search(
                            [('purchase_request_id',
                              '=', record.po_request_id.id),
                             ('qty', '=', record.qty),
                             ('requisition_id', '=', False)],
                            limit=1)
                    if purchase_request:
                        body = '<b>Purchase Request Line Deleted By Logistic Department:  </b>'
                        body += '<ul><li> Purchase Request No. : ' + str(
                            purchase_request.name) + '</li></ul>'
                        body += '<ul><li> Product Name : ' + str(
                            record.product_id.name) + '</li></ul>'
                        body += '<ul><li> Product Qty : ' + str(
                            record.qty) + '</li></ul>'
                        body += '<ul><li> Cancelled By  : ' + str(
                            self.env.user.name) + '</li></ul>'
                        body += '<ul><li> Cancelled Date  : ' + str(
                            date.today()) + '</li></ul>'
                        record.material_request_id.message_post(body=body)
                        record.po_request_id.message_post(body=body)
                        record.po_request_id = False
                        record.rm_type = 'stock'
                        purchase_request.unlink()

        except Exception as err:
            if error_string:
                raise UserError(UserError)
            else:
                exc_type, exc_obj, exc_tb = sys.exc_info()
                _logger.error(
                    "API-EXCEPTION..Exception in Cancel Production request {} {}"
                    .format(err, exc_tb.tb_lineno))
                raise UserError(
                    "API-EXCEPTION..Exception in Cancel Production request {} {}"
                    .format(err, exc_tb.tb_lineno))

    @api.multi
    def schedule_mo(self):
        for record in self:
            if record.product_id and record.rm_type == 'mo':
                pr = self.env['n.manufacturing.request'].create({
                    'n_state':
                    'draft',
                    'n_product_id':
                    record.product_id.id,
                    'n_delivery_date':
                    record.required_date,
                    'n_unit':
                    record.uom_id.id,
                    'n_order_qty':
                    math.ceil(record.qty),
                    'n_category':
                    record.product_id.categ_id.id,
                    #'n_client_date':record.required_date,
                    'request_type':
                    'raw',
                    'n_default_code':
                    record.product_id.default_code
                })
                record.pro_request_id = pr.id
                body = '<b>Production Request sent for Raw Material:  </b>'
                body += '<ul><li> Production No. : ' + str(
                    pr.name) + '</li></ul>'
                body += '<ul><li> Product Name : ' + str(
                    record.product_id.name) + '</li></ul>'
                body += '<ul><li> Product Qty : ' + str(
                    record.qty) + '</li></ul>'
                body += '<ul><li> Created By  : ' + str(
                    self.env.user.name) + '</li></ul>'
                body += '<ul><li> Created Date  : ' + str(
                    date.today()) + '</li></ul>'
                #pr.message_post(body=body)
                record.material_request_id.message_post(body=body)

            if record.product_id and record.rm_type == 'po':
                rq_data = self.env['stock.purchase.request']
                if record.product_id:
                    record.rm_type = 'po'
                    reqst_search = rq_data.search(
                        [('product_id', '=', record.product_id.id),
                         ('p_state', 'in', ('draft', 'requisition'))],
                        limit=1)
                    if reqst_search:
                        record.po_request_id = reqst_search.id
                        line = self.env['stock.purchase.request.line'].create({
                            'product_id':
                            record.product_id.id,
                            'qty':
                            math.ceil(record.qty),
                            'uom_id':
                            record.uom_id.id,
                            'material_request_id':
                            record.material_request_id.id,
                            'required_date':
                            record.required_date,
                            'production_id':
                            record.material_request_id.production_id.id,
                            'purchase_request_id':
                            reqst_search.id
                        })

                        body = '<b>Purchase Request Sent for Product:  </b>'
                        body += '<ul><li> Purchase Request No. : ' + str(
                            reqst_search.name) + '</li></ul>'
                        body += '<ul><li> Product Name : ' + str(
                            reqst_search.product_id.name) + '</li></ul>'
                        body += '<ul><li> Product Qty : ' + str(
                            record.qty) + '</li></ul>'
                        body += '<ul><li> Created By  : ' + str(
                            self.env.user.name) + '</li></ul>'
                        body += '<ul><li> Created Date  : ' + str(
                            date.today()) + '</li></ul>'
                        reqst_search.message_post(body=body)
                        record.material_request_id.message_post(body=body)
                    else:
                        request = rq_data.create({
                            'product_id':
                            record.product_id.id,
                            'material_request_id':
                            record.material_request_id.id,
                            'production_id':
                            record.material_request_id.production_id.id
                        })
                        body = '<b>Purchase Request Sent for Product:  </b>'
                        body += '<ul><li> Purchase Request No. : ' + str(
                            request.name) + '</li></ul>'
                        body += '<ul><li> Product Name : ' + str(
                            request.product_id.name) + '</li></ul>'
                        body += '<ul><li> Product Qty : ' + str(
                            record.qty) + '</li></ul>'
                        body += '<ul><li> Created By  : ' + str(
                            self.env.user.name) + '</li></ul>'
                        body += '<ul><li> Created Date  : ' + str(
                            date.today()) + '</li></ul>'
                        record.po_request_id = request.id
                        request.message_post(body=body)
                        record.material_request_id.message_post(body=body)
                        if request:
                            line = self.env[
                                'stock.purchase.request.line'].create({
                                    'product_id':
                                    record.product_id.id,
                                    'qty':
                                    math.ceil(record.qty),
                                    'required_date':
                                    record.required_date,
                                    'production_id':
                                    record.material_request_id.production_id.
                                    id,
                                    'material_request_id':
                                    record.material_request_id.id,
                                    'uom_id':
                                    record.uom_id.id,
                                    'purchase_request_id':
                                    request.id
                                })
Exemple #25
0
class MrpWordkorderShifts(models.Model):

	_name="mrp.workorder.rm.shifts"
	
	name = fields.Char('Name')
	request_id=fields.Many2one('mrp.raw.material.request',string='Raw Material')
	workorder_id = fields.Many2one('mrp.production.workcenter.line','Workorder No.')
	production_id = fields.Many2one('mrp.production','Manufacturing No.',related='workorder_id.production_id')
	product = fields.Many2one('product.product', string='Product Name')
	sub_product = fields.One2many('mrp.workorder.rm.shifts.line','shift_id',string='Product Details')
	wo_shift_product = fields.Many2many('mrp.workorder.rm.shifts.line','wo_shift_product_rel',
					'shift_id','pro_id',string='Product Details')
	wo_raw_shift_product = fields.Many2many('mrp.workorder.rm.shifts.line','wo_shift_raw_product_rel',
					'shift_id','pro_id',string='Product Details')
	#receive_sub_product = fields.One2many('mrp.workorder.rm.shifts.line','receive_shift_id',string='Receive Product Details')
	
	# fields for raw material process shifts
	raw_qty = fields.Float('Qty',help="Manufacture Order Quantity per Shift")
    	raw_uom = fields.Many2one('product.uom', string='Unit')
    	raw_hours = fields.Float('Hours')
    	
    	# fields for non raw material process shifts
    	qty = fields.Float('Qty',help="Manufacture Order Quantity per Shift")
    	uom = fields.Many2one('product.uom', string='Unit')
    	stock_qty = fields.Float('Qty',help="Manufacture Order Quantity per Shift for Inventory to send Raw Material")
    	wo_qty = fields.Float('Workorder qty',help="Workorder Quantity per Shift")
    	wo_uom = fields.Many2one('product.uom', string='Unit')
    	date = fields.Datetime('Schedule Date')		# date for logistics
    	
	hours = fields.Float('Hours')
	start_time = fields.Datetime('Start Time')
	end_time = fields.Datetime('End Time')
	raw_start_time = fields.Datetime('Start Time')
	raw_end_time = fields.Datetime('End Time')
	
	status=fields.Selection([('draft','Draft'),('request','Raw Material Request'),
				 ('picking','Delivery In Progress'),('hold','Hold'),('delivered','Delivered'),
				 ('received','Received'),('start','Start'),
				 ('end','End'),('cancel','Cancel')])
	date_history = fields.One2many('mrp.workorder.rm.shifts.date.history','shift_id',string='Re-schedule History')
	used_work_id = fields.Many2one('mrp.production.workcenter.line','Used in WO',help='Raw Material Shift USed for workorder')
	state = fields.Selection([('draft','Requested'),('approve','Approved'),('partialy','Partialy Send'),
   			   ('send','Send'),('reject','Rejeted'),('cancel','Cancelled')],related='request_id.state')
   	received_qty = fields.Float('Received RM',help='Raw Material is received in previous SHift,This fields shows only when you changes in number of shifts more than one')
   	rec_qty_uom = fields.Many2one('product.uom', string='Unit')
   	
   	wo_state = fields.Selection([('draft','Draft'),('pause','Pause'),('hold','On Hold'),('ready','Ready'),
    				('startworking', 'In Progress'),('done','Finished'),('cancel','Cancelled'),],
    				'Status', readonly=True, copy=False,related='workorder_id.state')
        picking_ids = fields.Many2many('stock.picking','raw_material_send_picking_rel','rm_id','picking_id',
        				'Delivery No.',help="Send Raw Material To Manufacturing Department")
        rec_picking_id = fields.Many2many('stock.picking','raw_material_receive_picking_rel','rm_id','picking_id',
        				'Delivery No.',help="Receive Raw Material Delivery no.")
	next_shift_id = fields.Many2one('mrp.workorder.rm.shifts','Next Shift',help='Next Shift id')
        
        shift_wo_raw_line =fields.Many2many('mrp.production.workcenter.line','work_order_raw_shift_rel',
				'shift_id','workorder_id','Working Shifts') # get shifts details of Raw Process
    	shift_wo_line =fields.Many2many('mrp.production.workcenter.line','work_order_shift_rel',
				'shift_id','workorder_id','Working Shifts') # get shifts details of Non Raw Process
	request_bool=fields.Boolean('filter in shifts in rm reqiest')
				
	@api.multi
	def create_picking(self):
		for record in self:
		   #if  record.work_order_ids:
		   	record.status='picking'
			if record.production_id.product_id.categ_id.cat_type == 'film':
		       		location_1='send_film_rm_picking'
		       		location_2='receive_film_rm_picking'
			elif record.production_id.product_id.categ_id.cat_type == 'injection':
				location_1='send_injection_rm_picking'
		       		location_2='receive_injection_rm_picking'
			else:
		       	  	raise UserError("Product Internal Type is not proper")
		       	  
			data_obj = self.env['ir.model.data']
			raw_picking_location1 = data_obj.get_object_reference('api_raw_material', location_1)[1]
			picking_type1=self.env['stock.picking.type'].search([('id','=',raw_picking_location1)],limit=1)

			body='<b>Created Transfered Orders for Scheduled Work Orders  :  </b>'
			body +='<ul><li> Manufanufacturing No. : '+str(record.production_id.name) +'</li></ul>'
			body +='<ul><li> Product Name : '+str(record.product.name) +'</li></ul>'
			body +='<ul><li> Created By  : '+str(self.env.user.name) +'</li></ul>'
			body +='<ul><li> Created Date  : '+str(date.today()) +'</li></ul>'
			body +="<table class='table' style='width:50%; height: 50%;font-family:arial; text-align:left;'><tr><th>Transered Order Name </th><th> Required Date</th></tr>"                  
			
			# Create procurement group>>
			procurement_id=self.env['procurement.group'].create({'name':record.production_id.name,
							      'move_type':'direct'})
			lst=[]
			picking=picking1=False
			for line in record.sub_product:
				if line.qty < (line.stock_qty+line.available_qty):
					raise UserError("requested Raw material quantity is not proper")
				move_ids = self.env['stock.move'].create({ 'date':record.date,
						  'product_id':line.product.id,'product_uom_qty':line.stock_qty,
						  'product_uom':line.uom.id, 'picking_type_id':picking_type1.id,  
						  'location_dest_id':picking_type1.default_location_dest_id.id,
						  'location_id':record.request_id.source_location.id, 
						  'name':record.request_id.name,'group_id':procurement_id.id})
				move_ids.with_context({'rm_route':True,'product_id':record.request_id.product_id.id}).action_confirm()
				picking=move_ids.picking_id
			if picking:
				picking.material_request_id=record.request_id.id
				picking.origin=record.request_id.name
				picking.ntransfer_type ='rm_virtual'
				for move in picking.move_lines:
					if move.move_dest_id and move.move_dest_id.picking_id:
						picking1 = move.move_dest_id.picking_id
						break 
			if picking1:
				picking1.material_request_id=record.request_id.id
				picking1.production_id=record.request_id.production_id.id
				picking1.origin=record.request_id.name
				picking1.ntransfer_type ='rm_production'
				picking1.next_prev_picking_id=[(4,picking.id)]	
			else:
				raise UserError("Routes are not set for Raw Material products, Please go to setting and set Injection or Film")		
			for rm in record.sub_product:
			    rm.available_qty += rm.stock_qty
		   	    if record.shift_wo_line:
				for wo_rm in record.shift_wo_line.raw_materials_id:
					if wo_rm.product_id.id==rm.product.id:
						wo_rm.requested_qty += rm.stock_qty
						
			for rm in record.sub_product:
			    if record.shift_wo_line:
				for wo_rm in record.shift_wo_raw_line.raw_materials_id:
					if wo_rm.product_id.id==rm.product.id:
						if wo_rm.next_order_id.id == record.shift_wo_line.id:
							wo_rm.requested_qty += rm.stock_qty
			
			record.request_id.picking_ids = [(4,picking.id)]		# in Send part of SHIFT
			record.picking_ids=[(4,picking.id)]				# in RM
			record.rec_picking_id=[(4,picking1.id)]				# in receive part of SHIFT
			
			if record.shift_wo_raw_line:		# add picking in raw materil process WO
				record.shift_wo_raw_line.rm_picking_ids = [(4,picking1.id)]
			if record.shift_wo_line:		# add picking in non raw materil process WO
				record.shift_wo_line.rm_picking_ids = [(4,picking1.id)]
			record.workorder_id.production_id.delivery_ids= [(4,picking1.id)]		# MO
			body +="<tr><td>%s</td><td>%s</td></tr>"%(str(picking.name), str(picking.request_sch_date_mo)) 
			body +="</table>"
			record.request_id.message_post(body=body)
			record.production_id.message_post(body=body)
		return True
		
	@api.multi
	def allow_picking(self):
		for res in self:
			if res.request_id.state in ('reject','cancel'):
				raise UserError("Raw Material Request For Manufacturing Order is Canceld By Logistics.")
				
			flag=False
			for rec in res.sub_product:  # Check if requset qty is ZERO but button is visible 
				if not rec.required_qty:
					res.status='received'
					flag=True
			if flag:			# if request qty is zero the break the loop
				break
				
			shift_id=self.search([('next_shift_id','=',res.id)])
			if shift_id.status =='draft':
				raise UserError("First send the request for {}".format(shift_id.name))
			rec_shift_id=self.search([('status','=','request'),('workorder_id','=',res.workorder_id.id)])

			if len(rec_shift_id)>=2:
				raise UserError("You can not send request for more than two shifts at same time")
				
			location=False
			if res.production_id.product_id.categ_id.cat_type == 'film':
		       		location='receive_film_rm_picking'
			elif res.production_id.product_id.categ_id.cat_type == 'injection':
		       		location='receive_injection_rm_picking'
			else:
		       	  	raise UserError("Product Internal Type is not proper")
		       	  
			data_obj = self.env['ir.model.data']
			raw_picking_type = data_obj.get_object_reference('api_raw_material', location)[1]
			if not res.production_id.raw_request:
				res.production_id.RM_Request_Mo()
				
			pickings=self.env['stock.picking'].search([('material_request_id','=',res.request_id.id),
							('picking_type_id','=',raw_picking_type),('state','!=','cancel')])
			product_data={}
			print "mmmmmmm...",pickings
			for pick in pickings:
				if pick.move_lines:
					for move in pick.move_lines:
						product_data[move.product_id.id] = product_data[move.product_id.id]+move.product_uom_qty if product_data.get(move.product_id.id) else move.product_uom_qty
				else:
					for operation in pick.pack_operation_product_ids:
						product_data[operation.product_id.id] = product_data[operation.product_id.id]+operation.qty_done if product_data.get(operation.product_id.id) else operation.qty_done
							
			shifts=self.env['mrp.workorder.rm.shifts'].search([('workorder_id','=',res.workorder_id.id),
									('status','in',('request','hold')),])
			print "Shifts..............",shifts,product_data
			for sh in shifts:
				for sub in res.sub_product:
					product_data[sub.product.id] = product_data[sub.product.id]+sub.required_qty if product_data.get(sub.product.id) else sub.required_qty
			
			for line in res.sub_product:
				product_data[line.product.id] = product_data[line.product.id]+line.required_qty if product_data.get(line.product.id) else line.required_qty
			for mo in res.workorder_id.production_id.product_lines:
				if product_data.get(mo.product_id.id):
					if int(mo.product_qty)<int(product_data.get(mo.product_id.id)):
						raise UserError("Raw Material Request quantity For product {} is out of rquired quantity ".format(mo.product_id.name))
			raw_date=False
			for shift in res.workorder_id.wo_shift_line:
				if raw_date and shift.date :
					if raw_date > datetime.strptime(shift.date,'%Y-%m-%d %H:%M:%S'):
						raw_date = datetime.strptime(shift.date,'%Y-%m-%d %H:%M:%S')
				elif shift.date:
					raw_date=datetime.strptime(shift.date,'%Y-%m-%d %H:%M:%S')
					
			for rm_request in res.production_id.material_request_id:
				if rm_request.request_type !='extra':
					rm_request.request_date = raw_date
					res.request_id = rm_request.id
					
			for rm in res.sub_product:
				rm.stock_qty = rm.required_qty 
				rm.required_qty = 0.0
			res.status='request'
		return True
		
	@api.multi
	def cancel_picking(self):
		for res in self:
			for rec in res.sub_product:  
				rec.required_qty = rec.qty-rec.available_qty
				rec.stock_qty=0.0
			res.status='draft'

	@api.multi
	def change_date(self):
		for res in self:
			form_view = self.env.ref('api_raw_material.reschedule_shift_form_view', False)
			context=self._context.copy()
			context.update({'default_shift_id':res.id,'default_start_time':res.start_time,
					'default_end_time':res.end_time})
			if form_view:
				return {
				    'type': 'ir.actions.act_window',
				    'view_type': 'form',
				    'view_mode': 'form',
				    'res_model': 'mrp.workorder.rm.shifts.date.history',
				    'views': [(form_view.id, 'form')],
				    'view_id': form_view.id,
				    'target': 'new',
				    'context':context
				}	
Exemple #26
0
class MrpRawmaterial(models.Model):
    _name = 'mrp.raw.material.request'
    _inherit = ['mail.thread']
    _order = 'id desc'

    rm_reject_reason = fields.Char(string='RM Reject Reason',
                                   track_visibility='always',
                                   copy=False)
    name = fields.Char('Name')
    production_id = fields.Many2one('mrp.production', string='Production No.')
    request_line_ids = fields.One2many('mrp.raw.material.request.line',
                                       'material_request_id',
                                       string='Request Line')
    state = fields.Selection([('draft', 'Requested'), ('approve', 'Approved'),
                              ('partialy', 'Partialy Send'), ('send', 'Send'),
                              ('reject', 'Rejeted'), ('cancel', 'Cancelled')],
                             string='Status',
                             default='draft')

    wastage_qty = fields.Float('Wastage Qty')
    request_date = fields.Datetime('Requested Date')
    partner_id = fields.Many2one(related='production_id.partner_id',
                                 store=True)
    expected_compl_date = fields.Datetime('Expected Completion Date')
    wastage_allow = fields.Float('Wastage Allowed')
    required_qty = fields.Float('Required Qty')
    allow_wastage_uom_id = fields.Many2one('product.uom')
    wastage_uom_id = fields.Many2one('product.uom')
    required_uom_id = fields.Many2one('product.uom')
    product_id = fields.Many2one('product.product', string='Product')
    note = fields.Text('Remark')
    note_mgnr = fields.Text('Manager Remark')
    document = fields.Binary('Document')
    request_type = fields.Selection([('normal', 'Normal Request'),
                                     ('extra', 'Extra Request')],
                                    string='Request Type')
    reason = fields.Selection([('wastage', 'Wastage'),
                               ('extra production', 'Extra Production')],
                              string='Reason')

    delivery_id = fields.Many2one('stock.picking', 'Delivery No.')
    picking_ids = fields.Many2many(
        'stock.picking',
        'raw_material_request_send_picking_rel',
        'rm_id',
        'picking_id',
        'Delivery No.',
        help="Send Raw Material To Manufacturing Department")

    work_order_ids = fields.One2many('mrp.production.workcenter.line',
                                     'rm_request_id',
                                     string='Work Orders')
    work_rm_ids = fields.One2many('workorder.raw.material',
                                  'rm_request_id',
                                  string='Work Orders')
    #schedule_raw_bool=fields.Boolean('Hide Schedule Raw button', default=False)
    source_location = fields.Many2one('stock.location')
    shift_request_line = fields.One2many('mrp.workorder.rm.shifts',
                                         'request_id',
                                         string='Delivery Numbers')
    mo_cancel = fields.Boolean('MO Cancel')

    @api.model
    def create(self, vals):
        if not vals.get('name'):
            vals['name'] = self.env['ir.sequence'].next_by_code(
                'mrp.raw.material.request') or 'New'
        result = super(MrpRawmaterial, self).create(vals)
        return result

    @api.multi
    def cancel_state(self):
        self.state = 'cancel'

    @api.multi
    @api.onchange('source_location')
    def on_change_source(self):
        #to get available qty from stock>>>
        try:
            for line in self:
                if line.source_location:
                    for res in line.request_line_ids:
                        qty = 0
                        quants = self.env['stock.quant'].search([
                            ('product_id', '=', res.product_id.id),
                            ('location_id', '=', line.source_location.id)
                        ])
                        for q in quants:
                            qty += q.qty
                        res.available_qty = qty - res.product_id.qty_reserved if (
                            qty - res.product_id.qty_reserved) > 0 else 0
        except Exception as err:
            raise UserError(
                "Exception in Source Location selection in raw Material Request -: {} "
                .format(err))

    @api.multi
    def approve_state(self):
        error_print = ''
        try:
            for rec in self:
                #                   for both extra and normal reqest type of mrp production order internal pikcing shud get created
                if rec.request_type in ('extra', 'normal'):
                    location_1 = False
                    if rec.production_id.product_id.categ_id.cat_type == 'film':
                        location_1 = 'send_film_rm_picking'
                    elif rec.production_id.product_id.categ_id.cat_type == 'injection':
                        location_1 = 'send_injection_rm_picking'
                    else:
                        error_print = "Product Internal Type is not proper"
                        raise

                    data_obj = self.env['ir.model.data']
                    raw_picking_location1 = data_obj.get_object_reference(
                        'api_raw_material', location_1)[1]
                    picking_type1 = self.env['stock.picking.type'].search(
                        [('id', '=', raw_picking_location1)], limit=1)
                    print "picking_type1picking_type1", picking_type1
                    procurement_id = self.env['procurement.group'].create({
                        'name':
                        rec.production_id.name,
                        'move_type':
                        'direct'
                    })
                    lst = []
                    picking = picking1 = False
                    if any(line.pick_qty == 0.0
                           for line in rec.request_line_ids):
                        raise UserError(
                            _("You cannot pick 0 qty for raw materials!!!"))
                    for line in rec.request_line_ids:
                        move_ids = self.env['stock.move'].create({
                            'date':
                            rec.request_date,
                            'origin':
                            rec.name,
                            'product_id':
                            line.product_id.id,
                            'product_uom_qty':
                            line.pick_qty,
                            'product_uom':
                            line.uom_id.id,
                            'picking_type_id':
                            picking_type1.id,
                            'location_dest_id':
                            picking_type1.default_location_dest_id.id,
                            'location_id':
                            rec.source_location.id,
                            'name':
                            rec.name,
                            'group_id':
                            procurement_id.id
                        })
                        move_ids.with_context({
                            'rm_route': True,
                            'product_id': rec.product_id.id
                        }).action_confirm()
                        picking = move_ids.picking_id
                    if picking:
                        picking.material_request_id = rec.id
                        picking.min_date = rec.request_date
                        picking.expected_comple_date = rec.expected_compl_date
                        picking.origin = rec.production_id.name
                        picking.ntransfer_type = 'rm_virtual'
                        rec.picking_ids = [(4, picking.id)]
                        for move in picking.move_lines:
                            if move.move_dest_id and move.move_dest_id.picking_id:
                                picking1 = move.move_dest_id.picking_id
                                break
                        rec.delivery_id = picking.id
                        rec.production_id.delivery_ids = [(4, picking.id)
                                                          ]  # MO

                    if picking1:
                        picking1.material_request_id = rec.id
                        picking1.min_date = rec.request_date
                        picking.expected_comple_date = rec.expected_compl_date

                        picking1.production_id = rec.production_id.id
                        picking1.origin = rec.name
                        picking1.next_prev_picking_id = [(4, picking.id)]
                        picking1.ntransfer_type = 'rm_production'
                        rec.production_id.delivery_ids = [(4, picking1.id)
                                                          ]  # MO
#			else:
#				error_print = "Routes are not set for Raw Material products, Please go to setting and set Injection or Film"
#				raise

                rec.state = 'approve'
                for line in rec.request_line_ids:
                    line.reserve_status = 'approve'

#		   if rec.request_type in ('extra','normal'):
#			   temp_id = self.env.ref('api_raw_material.email_template_extra_raw_material_approve')
#			   if temp_id:
#			       user_obj = self.env['res.users'].browse(self.env.uid)
#			       base_url = self.env['ir.config_parameter'].get_param('web.base.url')
#			       query = {'db': self._cr.dbname}
#			       fragment = {
#				    'model': 'mrp.production',
#				     'view_type': 'form',
#				     'id': rec.production_id.id,
#				      }
#			       url = urljoin(base_url, "/web?%s#%s" % (urlencode(query), urlencode(fragment)))
#			       text_link = _("""<a href="%s">%s</a> """) % (url,rec.production_id.name)
#			       body_html = """<div>
#				<p> <strong>Raw Material Request Approved</strong><br/><br/>
#				 <b>Dear: %s,</b><br/>
#				 <b>Production Number :</b>%s ,<br/>
#				  <b>Customer Name :</b>%s ,<br/>
#				  <b>Product Name :</b>%s ,<br/>
#				  <b>Allowed Wastage :</b>%s %s,<br/>
#				  <b>  Wastage Qty : %s %s</b><br/>
#				  <b>  Required Qty : %s %s</b><br/>
#				  <b>  Reason : </b>%s<br/>
#				  <b>  Production Remark : </b>%s<br/>
#				  <b>  Manager Remark : </b>%s
#				</p>
#				</div>#"""%(rec.production_id.user_id.name, text_link or '',rec.production_id.partner_id.name,
#				    rec.product_id.name, rec.wastage_allow,
#				   rec.allow_wastage_uom_id.name,
#				  rec.wastage_qty, rec.wastage_uom_id.name, rec.required_qty,
#				 rec.required_uom_id.name,rec.reason, rec.note, rec.note_mgnr)
#			       body_html +="<table class='table' style='width:50%; height: 50%;font-family:arial; text-align:left;'><tr><th>Material Name </th><th> qty</th></tr>"
#			       for line in rec.request_line_ids:
#				   body_html +="<tr><td>%s</td><td>%s %s</td></tr>"%(str(line.product_id.name), str(line.qty), str(line.uom_id.name))
#			       body_html +="</table>"
#			       body_html = self.pool['mail.template'].render_template(self._cr, self._uid, body_html, 'mrp.raw.material.request',rec.id, context=self._context)
#			       n_emails=str(rec.production_id.user_id.login)
#			       temp_id.write({'body_html': body_html, 'email_to' : n_emails, 'email_from': str(rec.production_id.user_id.login)})
#			       temp_id.send_mail(rec.id)
        except Exception as err:
            raise UserError(
                "Exception in Approval of raw Material Request -: {} ".format(
                    error_print if error_print else err))
        return True

    @api.multi
    def reject_rm_request(self):
        cofirm_form = self.env.ref('api_account.pay_cancel_wizard_view_form',
                                   False)
        if cofirm_form:
            return {
                'name': 'RM Reject Wizard',
                'type': 'ir.actions.act_window',
                'view_type': 'form',
                'view_mode': 'form',
                'res_model': 'cancel.pay.reason.wizard',
                'views': [(cofirm_form.id, 'form')],
                'view_id': cofirm_form.id,
                'target': 'new'
            }

    @api.multi
    def reject_state(self):
        error_print = ''
        try:
            for rec in self:
                rec.state = 'reject'
                for line in rec.request_line_ids:
                    line.reserve_status = 'reject'
                rec.production_id.write({'state': 'rmr'})

                if rec.request_type == 'extra':
                    if not rec.note_mgnr:
                        error_print = "Pleas fill the Manager Remark...."
                        raise


#			temp_id = self.env.ref('api_raw_material.email_template_extra_raw_material_reject')
#			if temp_id:
#			       user_obj = self.env['res.users'].browse(self.env.uid)
#			       base_url = self.env['ir.config_parameter'].get_param('web.base.url')
#			       query = {'db': self._cr.dbname}
#			       fragment = {
#				    'model': 'mrp.production',
#				     'view_type': 'form',
#				     'id': rec.production_id.id,
#				      }
#			       url = urljoin(base_url, "/web?%s#%s" % (urlencode(query), urlencode(fragment)))
#			       text_link = _("""<a href="%s">%s</a> """) % (url,rec.production_id.name)
#			       body_html = """<div>
#				<p> <strong>Extra Raw Material Request Rejected</strong><br/><br/>
#				 <b>Dear: %s,</b><br/>
#				 <b>Production Number :</b>%s ,<br/>
#				 <b>Customer Name :</b>%s ,<br/>
#				  <b>Product Name :</b>%s ,<br/>
#				  <b>Allowed Wastage :</b>%s %s,<br/>
#				  <b>  Wastage Qty : %s %s</b><br/>
#				  <b>  Required Qty : %s %s</b><br/>
#				  <b>  Reason : </b>%s<br/>
#				  <b>  Production Remark : </b>%s<br/>
#				  <b>  Manager Remark : </b>%s
#				</p>
#				</div>#"""%(rec.production_id.user_id.name, text_link or '',rec.production_id.partner_id.name,
#				    rec.product_id.name, rec.wastage_allow,
#				   rec.allow_wastage_uom_id.name,
#				  rec.wastage_qty, rec.wastage_uom_id.name, rec.required_qty,
#				 rec.required_uom_id.name,rec.reason, rec.note, rec.note_mgnr)
#			       body_html +="<table class='table' style='width:50%; height: 50%;font-family:arial; text-align:left;'><tr><th>Material Name </th><th> qty</th></tr>"
#			       for line in rec.request_line_ids:
#				   body_html +="<tr><td>%s</td><td>%s %s</td></tr>"%(str(line.product_id.name), str(line.qty), str(line.uom_id.name))
#			       body_html +="</table>"
#			       body_html = self.pool['mail.template'].render_template(self._cr, self._uid, body_html, 'mrp.raw.material.request',rec.id, context=self._context)
#			       n_emails=str(rec.production_id.user_id.login)
#
#			       temp_id.write({'body_html': body_html, 'email_to' : n_emails, 'email_from': str(rec.production_id.user_id.login)})
#			       temp_id.send_mail(rec.id)
        except Exception as err:
            raise UserError("{} ".format(error_print if error_print else err))

        return True
Exemple #27
0
class dym_bank_transfer(models.Model):
    _name = 'dym.bank.transfer'
    _description = 'Bank Transfer'
    _order = 'date desc, name desc'
       
    STATE_SELECTION = [
        ('draft', 'Draft'),
        ('waiting_for_approval','Waiting For Approval'),
        ('waiting_for_confirm_received','Waiting For Confirm Received'),
        ('confirmed', 'Waiting Approval'),
        ('app_approve', 'Approved'),
        ('app_received', 'Received'),
        ('approved','Done'),
        ('cancel','Cancelled')
    ]

    @api.one
    @api.depends('line_ids.amount','bank_fee')
    def _compute_amount(self):
        self.amount_total = sum(line.amount for line in self.line_ids) + self.bank_fee
        self.amount_show = self.amount_total
        # Allow Backdate
        # if self.amount_total > self.current_balance:
        #     raise UserError(_('Total transaksi tidak boleh lebih dari saldo tersedia.'))

    @api.cr_uid_ids_context
    @api.depends('period_id')
    def _get_period(self, cr, uid, ids,context=None):
        if context is None: context = {}
        if context.get('period_id', False):
            return context.get('period_id')
        periods = self.pool.get('account.period').find(cr, uid, context=context)
        return periods and periods[0] or False

    def terbilang(self,amount):
        hasil = fungsi_terbilang.terbilang(amount, "idr", 'id')
        return hasil
    
    def ubah_tanggal(self,tanggal):
        try:
            conv = datetime.strptime(tanggal, '%d-%m-%Y %H:%M')
            return conv.strftime('%d-%m-%Y')
        except Exception as e:
            conv = datetime.strptime(tanggal, '%Y-%m-%d %H:%M:%S')
            return conv.strftime('%d-%m-%Y')

    @api.cr_uid_ids_context
    def change_amount(self,cr,uid,ids,bank,branch_id,context=None):
        value = {}
        if bank and branch_id:
            journal = self.pool.get('account.journal')
            journal_srch = journal.search(cr,uid,[('id','=',bank)])
            journal_brw = journal.browse(cr,uid,journal_srch)
            if journal_brw.type in ['cash','bank']: 
                analytic_branch_ids = self.pool.get('account.analytic.account').search(cr, uid, [('segmen','=',3),('branch_id','=',branch_id),('type','=','normal'),('state','not in',('close','cancelled'))])
                analytic_cc_ids = self.pool.get('account.analytic.account').search(cr, uid, [('segmen','=',4),('type','=','normal'),('state','not in',('close','cancelled')),('parent_id','child_of',analytic_branch_ids)])
                sql_query = ' AND l.analytic_account_id in %s' % str(tuple(analytic_cc_ids))
            else :
                value = {'amount_show':False}    
        else :
            value = {'payment_from_id':False}
        return {'value':value}
    
    @api.cr_uid_ids_context
    def change_amount_show(self,cr,uid,ids,amount,context=None):
        value = {}
        if amount :
            value = {'amount':amount}
        else :
            value = {'amount':False}
        return {'value':value}    
    
    @api.model
    def _get_default_branch(self):
        res = self.env.user.get_default_branch()
        return res

    @api.model
    def _getCompanyBranch(self):
        transaction_type = self._context.get('default_transaction_type',False)
        company_id = self._context.get('company_id', self.env.user.company_id.id)
        user = self.env.user
        if user.branch_type == 'HO':
            branch_ids = [b.id for b in user.branch_ids if b.branch_type=='HO' and b.company_id.id==company_id]
        else:
            branch_ids = [user.get_default_branch()]
        return [('id','in',branch_ids)]
            
    @api.onchange('date')
    def get_default_date(self):
        if not self.allow_backdate:
            user = self.env['res.users'].search([('id','=',self._uid)])
            tz = pytz.timezone(user.tz) if user.tz else pytz.timezone('Asia/Jakarta')
            date_time = pytz.UTC.localize(datetime.now())
            date_time_utc = date_time.astimezone(tz)
            self.date = date_time_utc.date()

    @api.onchange('division')
    def onchange_division(self):
        self.division = 'Finance'

    @api.model
    def _get_analytic_company(self):
        company = self.pool.get('res.users').browse(self._cr, self._uid, self._uid).company_id
        level_1_ids = self.pool.get('account.analytic.account').search(self._cr, self._uid, [('segmen','=',1),('company_id','=',company.id),('type','=','normal'),('state','not in',('close','cancelled'))])
        if not level_1_ids:
            raise osv.except_osv(('Perhatian !'), ("[dym_bank_transfer-2] Tidak ditemukan data analytic untuk company %s")%(company.name))
        return level_1_ids[0]

    @api.model
    def _get_default_backdate(self):
        flag = False
        if self.env['res.users'].has_group('dym_account_voucher.group_dym_account_voucher_allow_backdate'):
            flag = True
        return flag

    @api.multi
    @api.depends('payment_from_id')
    def _get_current_balance(self):
        for rec in self:
            rec.current_balance = rec.payment_from_id.default_debit_account_id.balance
        return True
        
    allow_backdate = fields.Boolean(string='Backdate', default=_get_default_backdate)
    name = fields.Char(string="Name", readonly=True, default='/')
    company_id = fields.Many2one('res.company', string='Company', required=True, index=True, default=lambda self: self.env.user.company_id,
        help="Company related to this journal")

    branch_id = fields.Many2one('dym.branch', string='Branch', required=True, default=_get_default_branch, domain=_getCompanyBranch)
    amount = fields.Float('Amount')
    state = fields.Selection(STATE_SELECTION, string='State', readonly=True,default='draft')
    date = fields.Date(string="Date", required=True)
    receive_date = fields.Date(string="Receive Date", required=False)
    payment_from_id = fields.Many2one('account.journal',string="Source of Fund",domain="[('branch_id','in',[branch_id,False]),('type','in',['cash','bank'])]")

    payment_from_id_deposit = fields.Many2one('account.journal', string="Source of Fund",domain="[('branch_id','in',[branch_id,False]),('type','in',['cash'])]")
    payment_from_id_withdraw = fields.Many2one('account.journal', string="Source of Fund",domain="[('branch_id','in',[branch_id,False]),('type','in',['bank'])]")
    payment_from_id_ats = fields.Many2one('account.journal', string="Source of Fund",domain="[('branch_id','in',[branch_id,False]),('type','in',['bank'])]")
    payment_from_id_ho2branch = fields.Many2one('account.journal', string="Source of Fund",domain="[('branch_id','in',[branch_id,False]),('type','in',['bank'])]")
    payment_from_id_inhouse = fields.Many2one('account.journal', string="Source of Fund",domain="[('branch_id','in',[branch_id,False]),('type','in',['bank'])]")

    description = fields.Char(string="Description")
    move_id = fields.Many2one('account.move', string='Account Entry', copy=False)
    move_ids = fields.One2many('account.move.line',related='move_id.line_id',string='Journal Items', readonly=True)    
    line_ids = fields.One2many('dym.bank.transfer.line','bank_transfer_id',string="Bank Transfer Line")
    line_ids2 = fields.One2many('dym.bank.transfer.line','bank_transfer_id', related='line_ids', string="Bank Transfer Line")
    bank_fee = fields.Float(string='Bank Transfer Fee',digits=dp.get_precision('Account'))
    amount_total = fields.Float(string='Total Amount',digits=dp.get_precision('Account'), store=True, readonly=True, compute='_compute_amount',)
    period_id = fields.Many2one('account.period',string="Period",required=True, readonly=True,default=_get_period)
    note = fields.Text(string="Note")
    division = fields.Selection([('Unit','Showroom'),('Sparepart','Workshop'),('Umum','General'),('Finance','Finance')], string='Division',default='Unit', required=True,change_default=True, select=True)
    journal_type = fields.Selection(related='payment_from_id.type',string="Journal Type")
    amount_show = fields.Float(related='amount',string='Amount')
    confirm_uid = fields.Many2one('res.users',string="Posted by")
    confirm_date = fields.Datetime('Posted on')
    cancel_uid = fields.Many2one('res.users',string="Cancelled by")
    cancel_date = fields.Datetime('Cancelled on')
    analytic_1 = fields.Many2one('account.analytic.account', 'Account Analytic Company', default=_get_analytic_company)
    analytic_2 = fields.Many2one('account.analytic.account', 'Account Analytic Bisnis Unit')
    analytic_3 = fields.Many2one('account.analytic.account', 'Account Analytic Branch')
    analytic_4 = fields.Many2one('account.analytic.account', 'Account Analytic Cost Center')
    move_mit_id = fields.Many2one('account.move', string='Account Entry MIT', copy=False)
    move_mit_ids = fields.One2many('account.move.line',related='move_mit_id.line_id',string='Journal Items MIT', readonly=True)
    value_date = fields.Date('Value Date')
    transfer_type = fields.Selection([('normal','Normal'),('branch_replenishment','Penggantian Uang Cabang')], default="branch_replenishment")
    branch_type = fields.Selection(related='branch_id.branch_type')
    voucher_ids = fields.One2many('dym.bank.transfer.voucher', 'bank_transfer_id', string='Vouchers')
    ref = fields.Char('Reff')    
    current_balance = fields.Float(compute=_get_current_balance, string='Current Balance')
    transaction_type = fields.Selection(TRANSACTION_TYPES, string='Trasnsaction Type')
    payment_method = fields.Selection([
        ('giro','Giro'),
        ('ats','ATS'),
        ('cheque','Cheque'),
        ('internet_banking','Internet Banking'),
        ('auto_debit','Auto Debit')
        ], string='Payment Method')
    cheque_giro_number = fields.Many2one('dym.checkgyro.line', string='Chk/Giro No', domain="[('journal_id','=',payment_from_id)]")
    cheque_giro_date = fields.Date(string='Chk/Giro Date',required=True,default=fields.Date.context_today)
    clearing_bank = fields.Boolean(string='Clearing Bank', default=True)
    clearing_bank_readonly = fields.Boolean(string='Clearing Bank', related="clearing_bank")

    @api.cr_uid_ids_context
    def button_dummy(self, cr, uid, ids, context=None):
        return True

    @api.onchange('payment_method')
    def onchange_payment_method(self):
        self.clearing_bank = False
        if self.payment_method in ['giro','ho2branch','cheque','internet_banking']:
            self.clearing_bank = True
        if self.transaction_type in ['deposit','withdraw','inhouse','ats','ho2branch']:
            self.clearing_bank = True

    @api.onchange('payment_from_id_deposit','payment_from_id_withdraw','payment_from_id_ats','payment_from_id_ho2branch','payment_from_id_inhouse')
    def onchange_payment_from_dwhai_id(self):

        dom = {}
        val = {}
        war = {}

        user = self.env.user
        self.payment_from_id = False
        if self.payment_from_id_deposit:
            self.payment_from_id = self.payment_from_id_deposit.id
        if self.payment_from_id_withdraw:
            self.payment_from_id = self.payment_from_id_withdraw.id
        if self.payment_from_id_ats:
            self.payment_from_id = self.payment_from_id_ats.id
        if self.payment_from_id_ho2branch:
            self.payment_from_id = self.payment_from_id_ho2branch.id
        if self.payment_from_id_inhouse:
            self.payment_from_id = self.payment_from_id_inhouse.id

        transaction_type = self.env.context.get('transaction_type',False)
        # Deposit
        if transaction_type == 'deposit':
            return {
                'domain': {
                    'payment_from_id_deposit': [('type','=',self.env.context.get('journal_type',False))]
                },
            }

        # Withdrawal
        if transaction_type == 'withdraw':
            if self.payment_from_id_withdraw:
                acc_number = self.env['res.partner.bank'].search([('journal_id','=',self.payment_from_id_withdraw.id)])
                if not acc_number:
                    return {
                        'warning': {
                            'title': _('Warning!'), 
                            'message': _('Jurnal %s tidak memiliki rekening bank. Jika ini adalah jurnal bank, silahkan buat rekening di menu Sale > Configuration > Localization > Bank Account.' % self.payment_from_id_withdraw.name)
                        }
                    }
                self.clearing_bank = True
            return {
                'domain': {
                    # 'payment_from_id_withdraw': [('type','=',self.env.context.get('journal_type',False))],
                    'payment_from_id_withdraw': [('type','=','bank'),('transaction_type','=','out'),('branch_id','=',self.branch_id.id)],
                },
                'value': {
                    'payment_method': 'cheque',
                }
            }

        # ATS
        if transaction_type == 'ats':
            if self.payment_from_id_ats:
                acc_number = self.env['res.partner.bank'].search([('journal_id','=',self.payment_from_id_ats.id)])
                if not acc_number:
                    self.payment_from_id_ats = False
                    return {
                        'warning': {
                            'title': _('Warning!'), 
                            'message': _('Jurnal %s tidak memiliki rekening bank. Jika ini adalah jurnal bank, silahkan buat rekening di menu Sale > Configuration > Localization > Bank Account.' % self.payment_from_id_withdraw.name)
                        }
                    }
            return {
                'domain': {
                    'payment_from_id_ats': [('type','=',self.env.context.get('journal_type',False))]
                },
            }

        # HO2Branch
        if transaction_type == 'ho2branch':
            if user.branch_type != 'HO':
                self.branch_id = False
                raise osv.except_osv(('Perhatian !'), ("Maaf, user %s tidak memiliki akses untuk membuat transaksi Head Office." % user.login))
            if self.payment_from_id_ho2branch:
                acc_number = self.env['res.partner.bank'].search([('journal_id','=',self.payment_from_id_ho2branch.id)])
                if not acc_number:
                    self.payment_from_id_ho2branch = False
                    return {
                        'warning': {
                            'title': _('Warning!'), 
                            'message': _('Jurnal %s tidak memiliki rekening bank. Jika ini adalah jurnal bank, silahkan buat rekening di menu Sale > Configuration > Localization > Bank Account.' % self.payment_from_id_withdraw.name)
                        }
                    }
                self.clearing_bank = True
            return {
                'domain': {
                    'payment_from_id_ho2branch': [('type','=',self.env.context.get('journal_type',False))]
                },
            }

        # InHouse
        if transaction_type == 'inhouse':
            if user.branch_type != 'HO':
                self.branch_id = False
                raise osv.except_osv(('Perhatian !'), ("Maaf, user %s tidak diperbolehkan untuk membuat transaksi pemindahan uang antar rekening bank." % user.login))
            if self.payment_from_id_inhouse:
                acc_number = self.env['res.partner.bank'].search([('journal_id','=',self.payment_from_id_inhouse.id)])
                if not acc_number:
                    self.payment_from_id_inhouse = False
                    return {
                        'warning': {
                            'title': _('Warning!'), 
                            'message': _('Jurnal %s tidak memiliki rekening bank. Jika ini adalah jurnal bank, silahkan buat rekening di menu Sale > Configuration > Localization > Bank Account.' % self.payment_from_id_withdraw.name)
                        }
                    }
                self.clearing_bank = True
            return {
                'domain': {
                    'payment_from_id_inhouse': [('type','=',self.env.context.get('journal_type',False))]
                },
            }

    @api.multi
    def update_cheque_giro_book(self,vals):
        for rec in self:
            if not rec.cheque_giro_number:
                return
            transfer_id = rec.id
            if transfer_id:
                for x in self.env['dym.checkgyro.line'].search([('transfer_id','=',transfer_id)]):
                    x.state = 'available'
                    x.transfer_id = False

            cheque_giro_id = vals.get('cheque_giro_number',False)
            checkgyro_id = self.env['dym.checkgyro.line'].browse([cheque_giro_id])

            if not transfer_id:
                return False

            amount = 0.0
            if 'amount' in vals and vals.get('amount',False):
                amount = vals.get('amount',False)
            if rec.cheque_giro_number:
                rec.cheque_giro_number.amount = amount
            rec.cheque_giro_number.state = 'used'
            rec.cheque_giro_number.transfer_id = transfer_id
            rec.cheque_giro_number.used_date = rec.date

    @api.one
    def write(self, vals):
        super(dym_bank_transfer, self).write(vals)
        self.update_cheque_giro_book(vals)
        
    @api.model
    def create(self,vals,context=None):        
        # vals['name'] = self.env['ir.sequence'].get_per_branch(vals['branch_id'], 'BTR', division='Umum') 
        # vals['date'] = datetime.today() 
        bank_transfer = []
        for x in vals['line_ids']:
            bank_transfer.append(x[2]) 
        total_amount = 0.0
        if 'bank_fee' in vals:
            total_amount = vals['bank_fee']
        for y in bank_transfer :
            total_amount += y['amount']
        vals['amount_show'] = total_amount
        vals['amount'] = total_amount
        res_id = super(dym_bank_transfer, self).create(vals)
        self.update_cheque_giro_book(vals)
        return res_id
    
    @api.one
    def post_bank(self):
        user = self.env['res.users'].search([('id','=',self._uid)])
        tz = pytz.timezone(user.tz) if user.tz else 'Asia/Jakarta'

        date_time = pytz.UTC.localize(datetime.now())
        date_time_utc = date_time.astimezone(tz)  # Convert to UTC

        if self.allow_backdate == True:
            self.write({'state':'approved','confirm_uid':self._uid,'confirm_date':datetime.now()})    
        else:
            periods = self.env['account.period'].find(dt=date_time_utc.date())
            self.write({'state':'approved','confirm_uid':self._uid,'confirm_date':datetime.now(),'date':date_time_utc.date(),'period_id':periods and periods[0].id})    
        debit_account = self.payment_from_id.default_debit_account_id
        if self.move_mit_id:
            for mit_line in self.move_mit_ids:
                if mit_line.account_id.id != self.payment_from_id.default_debit_account_id.id:
                    debit_account = mit_line.account_id
        if self.payment_from_id.type == 'cash' :
            analytic_branch_ids = self.env['account.analytic.account'].search([('segmen','=',3),('branch_id','=',self.branch_id.id),('type','=','normal'),('state','not in',('close','cancelled'))])
            analytic_cc_ids = self.env['account.analytic.account'].search([('segmen','=',4),('type','=','normal'),('state','not in',('close','cancelled')),('parent_id','child_of',analytic_branch_ids.ids)])
            sql_query = ' AND l.analytic_account_id in %s' % str(tuple(analytic_cc_ids.ids))
            if not self.move_mit_id:
                if self.amount > debit_account.with_context(sql_query=sql_query).balance or self.amount_show > debit_account.with_context(sql_query=sql_query).balance :
                    raise osv.except_osv(('Perhatian !'), ("xSaldo kas di account %s tidak mencukupi !") % (debit_account.name))

        self.action_move_line_create()
        return True  

    @api.multi
    def action_cancel(self):
        self.write({'state': 'cancel', 'move_id': False})
        if moves:
            moves.button_cancel()
            moves.unlink()
        self._log_event(-1.0, 'Cancel Invoice')
        return True

    @api.one
    def cancel_bank(self):
        if self.move_mit_id:
            self.move_mit_id.action_reverse_journal()
        if self.move_id:
            self.move_id.action_reverse_journal()
        self.write({'state':'cancel','cancel_uid':self._uid,'cancel_date':datetime.now()})
        return True    

    @api.cr_uid_ids_context
    def action_move_line_create(self, cr, uid, ids, mit=False, context=None):
        this = self.browse(cr, uid, ids, context=context)
        if context is None:
            context = {}
        move_pool = self.pool.get('account.move')
        move_line_pool = self.pool.get('account.move.line')
        for banktransfer in self.browse(cr, uid, ids, context=context):
            name = banktransfer.name
            date = banktransfer.date
            if banktransfer.state in ['approved','app_received']:
                if not banktransfer.receive_date:
                    raise osv.except_osv(('Perhatian !'), ("Tanggal terima wajib diisi"))
                date = banktransfer.receive_date

            if banktransfer.transaction_type == 'deposit':
                payment_from_id = banktransfer.payment_from_id_deposit 
            elif banktransfer.transaction_type == 'withdraw':
                payment_from_id = banktransfer.payment_from_id_withdraw 
            elif banktransfer.transaction_type == 'ats':
                payment_from_id = banktransfer.payment_from_id_ats 
            elif banktransfer.transaction_type == 'ho2branch':
                payment_from_id = banktransfer.payment_from_id_ho2branch 
            elif banktransfer.transaction_type == 'inhouse':
                payment_from_id = banktransfer.payment_from_id_inhouse 
            else:
                raise osv.except_osv(('Perhatian !'), ("Journal Bank Pengirim tidak ditemukan"))

            self.write(cr, uid, ids, {'payment_from_id':payment_from_id.id}, context=context) 
                
            journal_id = banktransfer.payment_from_id.id
            credit_account_id = banktransfer.payment_from_id.default_credit_account_id
            debit_account_id = banktransfer.payment_from_id.default_debit_account_id
            
            if not credit_account_id or not debit_account_id:
                raise osv.except_osv(('Perhatian !'), ("Account belum diisi dalam journal %s!")%(banktransfer.payment_from_id.name))
            amount = banktransfer.amount          
            period_id = banktransfer.period_id.id  
            config_id = self.pool.get('dym.branch.config').search(cr,uid,[('branch_id','=',banktransfer.branch_id.id)])

            if not config_id :
                raise osv.except_osv(('Perhatian !'), ("Tidak ditemukan konfigurasi untuk cabang '%s', hubungi system administrator." % banktransfer.branch_id.name))  
           
            config = self.pool.get('dym.branch.config').browse(cr, uid, config_id, context=context)
            
            if mit and not config.banktransfer_mit:
                raise osv.except_osv(('Perhatian !'), ("System diminta untuk membuat journal entry dengan akun perantara (Money in transit) tapi di konfigurasi cabang bank transfer mit tidak dicentang. Hubungi system administrator untuk melanjutkan."))  

            if banktransfer.bank_fee > 0:
                bank_fee_account = config.bank_transfer_fee_account_id
                if not bank_fee_account:
                    raise osv.except_osv(('Perhatian !'), ("Akun untuk menampung bank transfer fee belum disetting. Silahkan setting dulu di Branch Config."))  

            if config.banktransfer_mit:
                if this.transaction_type=='deposit':
                    if not config.bank_deposit_mit_account_id:
                        raise osv.except_osv(('Perhatian !'), ("Tidak ditemukan konfigurasi akun perantara untuk transaksi Setoran (biasanya akun Setoran Tunai Perantara) pada cabang '%s', hubungi system administrator." % this.branch_id.name))  
                    for line in this.line_ids:
                        if line.payment_to_id.type != 'bank':
                            raise osv.except_osv(('Perhatian !'), ("Jurnal %s tidak termasuk jurnal bank tapi jurnal %s. Transaksi Deposit / penyetoran kas ke bank hanya boleh dari jurnal Kas ke jurnal Bank saja. Silahkan hubungi system administrator untuk melanjutkan." % (line.payment_to_id.name,line.payment_to_id.type)))  
                    bank_mit_account = config.bank_deposit_mit_account_id

                elif this.transaction_type=='withdraw':
                    if not config.bank_withdrawal_mit_account_id:
                        raise osv.except_osv(('Perhatian !'), ("Tidak ditemukan konfigurasi akun perantara untuk transaksi Penarikan (biasanya akun Penggantian Kas) pada cabang '%s', hubungi system administrator." % this.branch_id.name))  
                    for line in this.line_ids:
                        if line.payment_to_id.type not in ['pettycash','cash']:
                            raise osv.except_osv(('Perhatian !'), ("Jurnal %s tidak termasuk jurnal 'Cash/Petty Cash' tapi jurnal %s. Transaksi Withdrawal / pengambilan bank hanya boleh dari jurnal bank ke jurnal cash saja. Silahkan hubungi system administrator untuk melanjutkan." % (line.payment_to_id.name,line.payment_to_id.type)))  
                    bank_mit_account = config.bank_withdrawal_mit_account_id

                elif this.transaction_type in ['ats','ho2branch','inhouse']:
                    if not config.bank_transfer_mit_account_id:
                        raise osv.except_osv(('Perhatian !'), ("Tidak ditemukan konfigurasi akun perantara untuk transaksi ATS, Ho2Branch dan Inhouse Transfer (biasanya akun Pindahan Antar bank) pada cabang '%s', hubungi system administrator." % this.branch_id.name))  
                    for line in this.line_ids:
                        if line.payment_to_id.type != 'bank':
                            raise osv.except_osv(('Perhatian !'), ("Jurnal %s tidak termasuk jurnal bank tapi jurnal %s. Transaksi ini hanya boleh dari jurnal bank ke jurnal bank saja. Silahkan hubungi system administrator untuk melanjutkan." % (line.payment_to_id.name,line.payment_to_id.type)))  
                    bank_mit_account = config.bank_transfer_mit_account_id
                else:
                    raise osv.except_osv(('Perhatian !'), ("System tidak mengenal transaksi ini, system hanya mengenal transaksi deposit, witdrawal, ats, ho2branch dan inhouse saja."))  

                if bank_mit_account.type != 'liquidity':
                    raise osv.except_osv(('Perhatian !'), ("Akun Money In Transit %s type-nya harus liquidity, silahkan hubungi administrator untuk melanjutkan." % bank_mit_account.name))  

                if not bank_mit_account.reconcile:
                    raise osv.except_osv(('Perhatian !'), ("Akun Money In Transit %s harus reconcileable (bisa direkonsiliasi), silahkan hubungi administrator untuk melanjutkan." % bank_mit_account.name))  

            move_vals = {
                'name': name,
                'ref':name,
                'journal_id': journal_id,
                'date': date,
                'period_id':period_id,
                'transaction_id':banktransfer.id,
                'model':banktransfer.__class__.__name__,
            }            
            move_id = move_pool.create(cr, uid, move_vals, context=None)

            # clearing_bank = banktransfer.payment_from_id.type == 'bank' and 'open' or 'not_clearing'
            clearing_bank = 'not_clearing'
            if banktransfer.clearing_bank:
                clearing_bank = 'open'
            move_line1 = {
                'name':name,
                'ref':name,
                'account_id': credit_account_id.id if not banktransfer.move_mit_id.id else bank_mit_account.id,
                'move_id': move_id,
                'journal_id': journal_id,
                'period_id': period_id,
                'date': date,
                'debit': 0.0,
                'credit': banktransfer.amount,
                'branch_id' : banktransfer.branch_id.id,
                'division' : banktransfer.division,
                'analytic_account_id' : banktransfer.analytic_4.id,
                'clear_state': clearing_bank,
            }
            line_id = move_line_pool.create(cr, uid, move_line1, context)   
            if mit == True:
                move_line_mit = {
                    'name':name,
                    'clear_state':'open',
                    'ref':name,
                    'account_id': bank_mit_account.id,
                    'move_id': move_id,
                    'journal_id': journal_id,
                    'period_id': period_id,
                    'date': date,
                    'debit': banktransfer.amount,
                    'credit': 0.0,
                    'branch_id' : banktransfer.branch_id.id,
                    'division' : banktransfer.division,
                    'clearing_bank': clearing_bank,
                    'analytic_account_id' : banktransfer.analytic_4.id     
                }     
                line_mit_id = move_line_pool.create(cr, uid, move_line_mit, context)
            else:
                if banktransfer.bank_fee > 0 :
                    move_line3 = {
                        'name': _('Bank Transfer Fee'),
                        'ref':name,
                        'account_id': bank_fee_account.id,
                        'move_id': move_id,
                        'journal_id': journal_id,
                        'period_id': period_id,
                        'date': date,
                        'debit': banktransfer.bank_fee,
                        'credit': 0.0,
                        'branch_id' : banktransfer.branch_id.id,
                        'division' : banktransfer.division,
                        'analytic_account_id' : banktransfer.analytic_4.id                 
                    }    
                    line_id3 = move_line_pool.create(cr, uid, move_line3, context)                     
                for y in banktransfer.line_ids :
                    branch_destination = self.pool.get('dym.branch').search(cr,SUPERUSER_ID,[('code','=',y.branch_destination_id)])
                    branch_dest = self.pool.get('dym.branch').browse(cr,SUPERUSER_ID,branch_destination)
                
                    move_line_2 = {
                        'name': _('Bank Transfer Detail %s')%(branch_dest.name),
                        'ref':name,
                        'account_id': y.payment_to_id.default_debit_account_id.id,
                        'move_id': move_id,
                        'journal_id': journal_id,
                        'period_id': period_id,
                        'date': date,
                        'debit': y.amount,
                        'credit': 0.0,
                        'branch_id' : branch_dest.id,
                        'division' : banktransfer.division,
                        'analytic_account_id' : y.analytic_4.id                             
                    }           
                    line_id2 = move_line_pool.create(cr, uid, move_line_2, context)
                    if y.reimbursement_id :
                        y.reimbursement_id.write({'state':'paid'})
            if banktransfer.payment_from_id.entry_posted:
                posted = move_pool.post(cr, uid, [move_id], context=None)
            if mit == False:
                self.write(cr, uid, banktransfer.id, {'state': 'approved', 'move_id': move_id})
            else:
                self.write(cr, uid, banktransfer.id, {'move_mit_id': move_id})
        return True
     
    @api.cr_uid_ids_context   
    def create_intercompany_lines(self,cr,uid,ids,move_id,context=None):       
        branch_rekap = {}       
        branch_pool = self.pool.get('dym.branch')        
        vals = self.browse(cr,uid,ids) 
        move_line = self.pool.get('account.move.line')
        move_line_srch = move_line.search(cr,SUPERUSER_ID,[('move_id','=',move_id)])
        move_line_brw = move_line.browse(cr,SUPERUSER_ID,move_line_srch)
        
        branch = branch_pool.search(cr,uid,[('id','=',vals.branch_id.id)])

        if branch :
            branch_browse = branch_pool.browse(cr,uid,branch)
            inter_branch_header_account_id = branch_browse.inter_company_account_id.id
            if not inter_branch_header_account_id :
                raise osv.except_osv(('Perhatian !'), ("Account Inter Company belum diisi dalam Master branch %s !")%(vals.branch_id.name))
        
        for x in move_line_brw :
            if x.branch_id not in branch_rekap :
                branch_rekap[x.branch_id] = {}
                branch_rekap[x.branch_id]['debit'] = x.debit
                branch_rekap[x.branch_id]['credit'] = x.credit
            else :
                branch_rekap[x.branch_id]['debit'] += x.debit
                branch_rekap[x.branch_id]['credit'] += x.credit  
        
        for key,value in branch_rekap.items() :
            if key != vals.branch_id :        
                inter_branch_detail_account_id = key.inter_company_account_id.id                
                if not inter_branch_detail_account_id :
                    raise osv.except_osv(('Perhatian !'), ("Account Inter belum diisi dalam Master branch %s - %s!")%(key.code, key.name))

                balance = value['debit']-value['credit']
                debit = abs(balance) if balance < 0 else 0
                credit = balance if balance > 0 else 0
                
                if balance != 0:
                    move_line_create = {
                        'name': _('Interco Bank Transfer %s')%(key.name),
                        'ref':_('Interco Bank Transfer %s')%(key.name),
                        'account_id': inter_branch_header_account_id,
                        'move_id': move_id,
                        'journal_id': vals.payment_from_id.id,
                        'period_id': vals.period_id.id,
                        'date': vals.date,
                        'debit': debit,
                        'credit': credit,
                        'branch_id' : key.id,
                        'division' : vals.division                    
                    }    
                    inter_first_move = move_line.create(cr, uid, move_line_create, context)    
                             
                    move_line2_create = {
                        'name': _('Interco Bank Transfer %s')%(vals.branch_id.name),
                        'ref':_('Interco Bank Transfer %s')%(vals.branch_id.name),
                        'account_id': inter_branch_detail_account_id,
                        'move_id': move_id,
                        'journal_id': vals.payment_from_id.id,
                        'period_id': vals.period_id.id,
                        'date': vals.date,
                        'debit': credit,
                        'credit': debit,
                        'branch_id' : vals.branch_id.id,
                        'division' : vals.division                    
                    }    
                    inter_second_move = move_line.create(cr, uid, move_line2_create, context)       
        return True

    @api.cr_uid_ids_context
    def unlink(self, cr, uid, ids, context=None):
        for item in self.browse(cr, uid, ids, context=context):
            if item.state != 'draft':
                raise osv.except_osv(('Perhatian !'), ("Bank Transfer sudah diproses, data tidak bisa didelete !"))
        return super(dym_bank_transfer, self).unlink(cr, uid, ids, context=context)     

    def branch_id_change(self, cr, uid, ids, branch_id, context=None):
        value = {}
        if branch_id :
            value['payment_from_id'] = False
            branch = self.pool.get('dym.branch').browse(cr, uid, branch_id)
            analytic_1_general, analytic_2_general, analytic_3_general, analytic_4_general = self.pool.get('account.analytic.account').get_analytical(cr, uid, branch, 'Umum', False, 4, 'General')
            value['analytic_1'] = analytic_1_general
            value['analytic_2'] = analytic_2_general
            value['analytic_3'] = analytic_3_general
            value['analytic_4'] = analytic_4_general

            branch_config_obj = self.pool.get('dym.branch.config')
            config_id = branch_config_obj.search(cr, uid,[('branch_id','=',branch_id)])
        return {'value':value}


    @api.onchange('payment_from_id')
    def onchange_payment_from_id(self):
        return {
            'domain': {
                'cheque_giro_number': [('journal_id','=',self.payment_from_id.id)]
            }
        }
Exemple #28
0
class dym_reimbursed_bank(models.Model):
    _name = "dym.reimbursed.bank"
    _description = "Reimbursed Bank"
    _inherit = ['mail.thread']

    STATE_SELECTION = [
        ('draft', 'Draft'),
        ('posted', 'Posted'),
        ('requested', 'Requested'),
        ('nextrequest', 'Next Request'),
        ('norequest', 'No Requested'),
        ('req2ho', 'Requested to HO'),  #Saat dipanggil oleh tranfer request
        ('hoapproved',
         'HO Approved'),  #Saat orang HO pencet oleh tranfer request
        ('horejected',
         'HO Rejected'),  #Saat orang HO pencet oleh tranfer request
        ('paid', 'HO Paid'),
        ('cancel', 'Cancelled'),
    ]

    @api.cr_uid_ids_context
    @api.depends('period_start')
    def _get_period(self, cr, uid, ids, context=None):
        if context is None: context = {}
        if context.get('period_start', False):
            return context.get('period_start')
        periods = self.pool.get('account.period').find(cr,
                                                       uid,
                                                       context=context)
        res = periods and periods[0] or False
        print "======>", res
        return res

    @api.one
    @api.depends('line_ids.amount')
    def _compute_amount(self):
        total_debit = sum(line.debit for line in self.line_ids)
        total_credit = sum(line.credit for line in self.line_ids)
        self.amount_total = total_credit - total_debit

    @api.cr_uid_ids_context
    def _get_default_branch(self, cr, uid, ids, context=None):
        user_obj = self.pool.get('res.users')
        user_browse = user_obj.browse(cr, uid, uid)
        branch_ids = False
        branch_ids = user_browse.branch_ids and len(
            user_browse.branch_ids
        ) == 1 and user_browse.branch_ids[0].id or False
        return branch_ids

    def terbilang(self, amount):
        hasil = fungsi_terbilang.terbilang(amount, "idr", 'id')
        return hasil

    @api.one
    @api.depends('line_ids')
    def _count_detail_payslip(self):
        bank_ids = []
        count = 0
        for line in self.line_ids:
            if line.bank_id.id in bank_ids:
                continue
            count += 1
            bank_ids.append(line.bank_id.id)
        self.bank_count = count

    def ubah_tanggal(self, tanggal):
        try:
            conv = datetime.strptime(tanggal, '%d-%m-%Y %H:%M')
            return conv.strftime('%d-%m-%Y')
        except Exception as e:
            conv = datetime.strptime(tanggal, '%Y-%m-%d %H:%M:%S')
            return conv.strftime('%d-%m-%Y')

    def ubah_tanggal_2(self, tanggal):
        try:
            conv = datetime.strptime(tanggal, '%d-%m-%Y')
            return conv.strftime('%d-%m-%Y')
        except Exception as e:
            conv = datetime.strptime(tanggal, '%Y-%m-%d')
            return conv.strftime('%d-%m-%Y')

    @api.model
    def _getCompanyBranch(self):
        user = self.env.user
        if user.branch_type != 'HO':
            if not user.branch_id:
                raise osv.except_osv(('Perhatian !'), (
                    "User %s tidak memiliki default branch. Hubungi system administrator agar menambahkan default branch di User Setting."
                    % self.env.user.name))
            return [('id', '=', user.branch_id.id)]
        company_id = self._context.get('company_id',
                                       self.env.user.company_id.id)
        branch_ids = [
            b.id for b in self.env.user.branch_ids
            if b.company_id.id == company_id
        ]
        return [('id', 'in', branch_ids)]

    name = fields.Char(string="Name", readonly=True, default='')
    period_start = fields.Many2one('account.period',
                                   string="Period Start",
                                   required=True,
                                   default=_get_period)
    period_end = fields.Many2one('account.period', string="Period End")
    company_id = fields.Many2one('res.company',
                                 string='Company',
                                 required=True,
                                 index=True,
                                 default=lambda self: self.env.user.company_id,
                                 help="Company related to this journal")
    branch_id = fields.Many2one('dym.branch',
                                string='Branch',
                                required=True,
                                domain=_getCompanyBranch)
    division = fields.Selection([('Unit', 'Showroom'),
                                 ('Sparepart', 'Workshop'),
                                 ('Umum', 'General'), ('Finance', 'Finance')],
                                string='Division',
                                default='Umum',
                                change_default=True,
                                select=True)
    journal_id = fields.Many2one(
        'account.journal',
        string="Payment Method",
        domain="[('branch_id','in',[branch_id,False]),('type','=','bank')]")
    state = fields.Selection(STATE_SELECTION,
                             string='State',
                             readonly=True,
                             default='draft')
    date = fields.Date(string="Date Requested",
                       required=True,
                       readonly=True,
                       default=fields.Date.context_today)
    date_approve = fields.Date(string="Date Approved", readonly=True)
    date_cancel = fields.Date(string="Date Canceled", readonly=True)
    amount_total = fields.Float(
        string='Total Amount',
        digits=dp.get_precision('Account'),
        store=True,
        readonly=True,
        compute='_compute_amount',
    )
    amount_requested = fields.Float(string='Amount Requested',
                                    digits=dp.get_precision('Account'))
    confirm_uid = fields.Many2one('res.users', string="Requested by")
    confirm_date = fields.Datetime('Requested on')
    cancel_uid = fields.Many2one('res.users', string="Cancelled by")
    cancel_date = fields.Datetime('Cancelled on')
    bank_count = fields.Integer(compute=_count_detail_payslip, string="Items")
    line_ids = fields.One2many('dym.reimbursed.bank.line', 'reimbursed_id')
    notes = fields.Char('Notes')

    @api.model
    def default_get(self, fields):
        res = super(dym_reimbursed_bank, self).default_get(fields)
        user = self.env.user
        if not user.branch_id:
            raise osv.except_osv(('Perhatian !'), (
                "User %s tidak memiliki default branch. Hubungi system administrator agar menambahkan default branch di User Setting."
                % self.env.user.name))
        if user.branch_type != 'HO':
            res['division'] = 'Unit'
        else:
            res['division'] = 'Finance'
        return res

    # @api.multi
    # def action_validate(self):
    #     warning = {}
    #     Voucher = self.env['account.voucher']
    #     if self.amount_total < 0:
    #         self.state = 'nextrequest'
    #     else:
    #         next_requests = self.search([
    #             ('journal_id','=',self.journal_id.id),
    #             ('state','=','nextrequest'),
    #         ])
    #         for nr in next_requests:

    #         if not self.line_ids:
    #             vouchers = Voucher.search([
    #                 ('period_id','=',self.period_id.id),
    #                 ('journal_id','=',self.journal_id.id),
    #                 ('journal_id.type','in',['bank']),
    #                 ('type','in',('receipt','payment')),
    #                 ('state','=','posted'),
    #                 ('move_id','!=',False),
    #                 ('transaction_type','in',('in','out'))
    #             ], order="date")
    #             if not vouchers:
    #                 self.name = self.env['ir.sequence'].get_per_branch(vals['branch_id'], 'RBK', division=self.division)
    #                 self.state = 'norequest'
    #                 warning = {
    #                     'title': ('Perhatian !'),
    #                     'message': (_('Tidak ditemukan transaksi bank in dan bank out para periode terpilih yaitu: %s, maka status dari dokumen ini dijaikan No Request.' % self.period_id.name)),
    #                 }
    #             else:
    #                 raise osv.except_osv(('Perhatian !'), ("Jangan dulu validasi sebab ada transaksi yang belum masuk, silahkan Compute dulu."))
    #         else:
    #             self.name = self.env['ir.sequence'].get_per_branch(vals['branch_id'], 'RBK', division=self.division)
    #             self.action_post()
    #     return {'warning':warning}

    @api.multi
    def action_post(self):
        self.state = 'posted'

    @api.multi
    def action_draft(self):
        self.state = 'draft'

    @api.multi
    def action_compute(self):
        return self._action_compute_lines()

    @api.multi
    def _action_compute_lines(self):
        res = {}
        Voucher = self.env['account.voucher']
        vouchers = Voucher.search([('period_id', '=', self.period_id.id),
                                   ('journal_id', '=', self.journal_id.id),
                                   ('journal_id.type', 'in', ['bank']),
                                   ('type', 'in', ('receipt', 'payment')),
                                   ('state', '=', 'posted'),
                                   ('move_id', '!=', False),
                                   ('transaction_type', 'in', ('in', 'out'))],
                                  order="date")
        lines = []
        for voucher in vouchers:
            for ml in voucher.move_id.line_id:
                if voucher.transaction_type == 'in' and ml.credit == 0.0:
                    continue
                if voucher.transaction_type == 'out' and ml.debit == 0.0:
                    continue
                values = {
                    'voucher_id': voucher.id,
                    'name': ml.name,
                    'date': voucher.date,
                    'account_id': ml.account_id.id,
                    'debit': ml.credit,
                    'credit': ml.debit,
                }
                lines.append((0, 0, values))
        self.line_ids.unlink()
        self.write({'line_ids': lines})
        return res

    # def button_bank_out(self,cr,uid,ids,context=None):
    #     mod_obj = self.pool.get('ir.model.data')
    #     act_obj = self.pool.get('ir.actions.act_window')
    #     result = mod_obj.get_object_reference(cr, uid, 'dym_bank', 'bank_action')
    #     id = result and result[1] or False
    #     result = act_obj.read(cr, uid, [id], context=context)[0]
    #     val = self.browse(cr, uid, ids)
    #     bank_ids = []
    #     for line in val.line_ids:
    #         bank_ids.append(line.bank_id.id)
    #     if bank_ids:
    #         result['domain'] = "[('id','in',"+str(bank_ids)+")]"
    #     else:
    #         res = mod_obj.get_object_reference(cr, uid, 'dym_bank', 'bank_tree_view')
    #         result['views'] = [(res and res[1] or False, 'tree')]
    #         result['res_id'] = False
    #     return result

    @api.cr_uid_ids_context
    def button_dummy(self, cr, uid, ids, context=None):
        return True
Exemple #29
0
class maintenance_demande_intervention(models.Model):
    _name = 'maintenance.demande.intervention'
    _rec_name = 'reference_intervention'

    #button workflow annuler
    @api.one
    def action_annuler(self):
        self.write({'state': 'annule'})

    #button workflow planifier
#	@api.one
#	def action_planifier(self):
#		self.write({'state': 'planifie'})

#button workflow traiter
#	@api.one
#	def action_traiter(self):
#		self.write({'state': 'traite'})

#		#creer demande intervention
#		if self.maintenance_preventive_id and self.maintenance_preventive_id.type_intervalle == 'intervalle':
#			intervalle = self.maintenance_preventive_id.intervalle
#			date_planifie = datetime.datetime.now() + datetime.timedelta(days=intervalle)
#			self.env['maintenance.demande.intervention'].create({'machine_id': self.machine_id.id,
#																'maintenance_preventive_id': self.maintenance_preventive_id.id,
#																'panne_id': self.panne_id.id,
#																'date_entretien_planifie': date_planifie})

#		if self.maintenance_preventive_id and self.maintenance_preventive_id.type_intervalle == 'duree':
#			date_planifie = datetime.datetime.now() + datetime.timedelta(days=self.maintenance_preventive_id.duree)
#			duree_planifie = self.maintenance_preventive_id.duree * 7 + self.machine_id.duree_fonctionnement
#			self.env['maintenance.demande.intervention'].create({'machine_id': self.machine_id.id,
#																'maintenance_preventive_id': self.maintenance_preventive_id.id,
#																'panne_id': self.panne_id.id,
#																'date_entretien_planifie': date_planifie,
#																'duree_planifie': duree_planifie})

#button workflow evaluer
#	@api.one
#	def action_evaluer(self):
#		self.write({'state': 'evalue'})

#button workflow cloturer

    @api.one
    def action_cloturer(self):
        self.write({'state': 'cloture'})

    @api.one
    #	@api.depends('date_entretien_planifie')
    def _get_jours_restants(self):
        if self.date_entretien_planifie:
            dt_p = datetime.datetime.fromtimestamp(
                time.mktime(
                    time.strptime(self.date_entretien_planifie,
                                  "%Y-%m-%d %H:%M:%S")))
            jours_restants = dt_p - datetime.datetime.now()
            self.jours_restants = jours_restants.days

    @api.one
    #	@api.depends('duree_planifie')
    def _get_duree_restants(self):
        if self.duree_planifie:
            self.duree_restants = self.duree_planifie - self.machine_id.duree_fonctionnement

    @api.one
    @api.depends('heure_travaillee', 'cout_horaire')
    def _calcul_cout(self):
        for rec in self:
            if rec.cout_horaire and rec.heure_travaillee:
                self.cout = rec.cout_horaire * rec.heure_travaillee

    @api.one
    def _get_delai(self):
        if self.date_entretien_planifie:
            dt_p = datetime.datetime.fromtimestamp(
                time.mktime(
                    time.strptime(self.date_entretien_planifie,
                                  "%Y-%m-%d %H:%M:%S")))
            jours_restants = dt_p - datetime.datetime.now()
            if jours_restants.days > 0 and jours_restants.days <= 10:
                self.delai = 'orange'
            elif jours_restants.days > 10:
                self.delai = 'vert'
            else:
                self.delai = 'rouge'

    reference_intervention = fields.Char('Référence',
                                         default='/',
                                         required=True)
    #demande
    demandeur = fields.Char('Demandeur')
    maintenance_preventive_id = fields.Many2one('maintenance.preventive',
                                                'Référence MP',
                                                ondelete='cascade')
    type_intervalle_rel = fields.Selection(
        [('duree', 'Durée de fonctionnement'), ('intervalle', 'Intervalle')],
        string='Type',
        related='maintenance_preventive_id.type_intervalle')
    date_demande = fields.Datetime(
        'Date demande', default=lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'))
    machine_id = fields.Many2one('production.machine',
                                 'Machine',
                                 required=True,
                                 ondelete='cascade')
    panne_id = fields.Many2one('maintenance.panne',
                               'Panne?',
                               required=True,
                               ondelete='cascade')
    priorite = fields.Selection([('basse', 'Basse'), ('normal', 'Normal'),
                                 ('urgent', 'Urgent'), ('autres', 'Autres')],
                                'Priorité',
                                default='normal')
    jours_restants = fields.Integer(compute='_get_jours_restants',
                                    string='Delai (j)')
    duree_restants = fields.Integer(compute='_get_duree_restants',
                                    string='Durée restants (h)')

    #planification
    type_prestataire = fields.Selection([('externe', 'Externe'),
                                         ('interne', 'Interne')],
                                        'Type prestataire',
                                        default='externe')
    prestataire_id = fields.Many2one('maintenance.prestataire',
                                     'Prestataire',
                                     ondelete='cascade')
    operateur_id = fields.Many2one('production.operateur',
                                   'Operateur',
                                   ondelete='cascade')
    date_entretien_planifie = fields.Datetime('Date entretien planifiée')
    duree_planifie = fields.Float('Durée de fonctionnement planifiée')
    #traitement
    traitement_effectue = fields.Text('Traitement effectué')
    demande_intervention_piece_rel_ids = fields.One2many(
        'demande.intervention.piece.rel', 'demande_intervention_id',
        'Pièces de rechange')
    date_entretien = fields.Datetime('Date début entretien')
    date_fin_entretien = fields.Datetime('Date fin entretien')

    heure_travaillee = fields.Integer('Heure travaillée')
    cout_horaire = fields.Float('Coût horaire',
                                related="operateur_id.cout_horaire")
    cout = fields.Float(compute='_calcul_cout', string='Coût')
    montant_facture = fields.Float('Montant facturé')
    temp_arret = fields.Float('temp d\'arrêt (h)')

    #evaluation
    date_evaluation = fields.Date('Date évaluation')

    remarque = fields.Text('Remarque')
    state = fields.Selection([('non_planifie', 'Non planifié'),
                              ('planifie', 'Planifiée'), ('traite', 'Traitée'),
                              ('evalue', 'Evaluée'), ('cloture', 'Cloturée'),
                              ('annule', 'Annulée')],
                             'Etat',
                             required=True,
                             default='non_planifie')

    delai = fields.Selection([('vert', 'vert'), ('rouge', 'rouge'),
                              ('orange', 'orange')],
                             compute='_get_delai',
                             string='Delai')

    @api.model
    def create(self, values):
        #generer code sequence "reference_intervention" s'il n'est pas spécifié
        if ('reference_intervention'
                not in values) or (values.get('reference_intervention')
                                   == '/'):
            values['reference_intervention'] = self.env['ir.sequence'].get(
                'maintenance.demande.intervention')

        #test reference_intervention doit etre unique
        if self.env['maintenance.demande.intervention'].search_count([
            ('reference_intervention', '=', values['reference_intervention'])
        ]) > 0:
            raise Warning(
                _('Erreur!'),
                _('Référence intervention existe déjà [ %s ].') %
                (values['reference_intervention']))

        return super(maintenance_demande_intervention, self).create(values)

    @api.multi
    def write(self, values):
        obj_id = super(maintenance_demande_intervention, self).write(values)
        #test reference_intervention doit etre unique
        if self.env['maintenance.demande.intervention'].search_count([
            ('reference_intervention', '=', self.reference_intervention)
        ]) > 1:
            raise Warning(
                _('Erreur!'),
                _('Référence intervention existe déjà [ %s ].') %
                (self.reference_intervention))

        return obj_id

    @api.multi
    def evaluer_prestataire(self):
        self.date_evaluation = datetime.date.today()
        self.state = 'evalue'
        return {
            'name': _("Evaluation"),
            'type': 'ir.actions.act_window',
            'view_type': 'form',
            'view_mode': 'form',
            'res_model': 'maintenance.evaluation.prestataire',
            'view_id': False,
            'target': 'new',
            'context': {
                'default_maintenance_prestataire_id': self.prestataire_id.id,
                'default_demande_intervention_id': self.id,
                'default_delai_prevu': self.date_entretien_planifie,
                'default_delai_reel': self.date_entretien,
                'default_maintenance_corrective_id': self.id,
            },
        }

    @api.multi
    def evaluer_operateur(self):
        self.date_evaluation = datetime.date.today()
        self.state = 'evalue'
        return {
            'name': _("Evaluation"),
            'type': 'ir.actions.act_window',
            'view_type': 'form',
            'view_mode': 'form',
            'res_model': 'maintenance.evaluation.operateur',
            'view_id': False,
            'target': 'new',
            'context': {
                'default_production_operateur_id': self.operateur_id.id,
                'default_date_evaluation': self.date_evaluation,
            },
        }
Exemple #30
0
class dym_pettycash_in(models.Model):
    _name = "dym.pettycash.in"
    _description = "Petty Cash In"

    STATE_SELECTION = [
        ('draft', 'Draft'),
        ('posted', 'Posted'),
        ('cancel', 'Cancelled'),
    ]

    @api.cr_uid_ids_context
    @api.depends('period_id')
    def _get_period(self, cr, uid, ids, context=None):
        if context is None: context = {}
        if context.get('period_id', False):
            return context.get('period_id')
        periods = self.pool.get('account.period').find(cr,
                                                       uid,
                                                       context=context)
        return periods and periods[0] or False

    @api.model
    def _get_default_branch(self):
        res = self.env.user.get_default_branch()
        return res

    @api.model
    def _getCompanyBranch(self):
        user = self.env.user
        if user.branch_type != 'HO':
            if not user.branch_id:
                raise osv.except_osv(('Perhatian !'), (
                    "User %s tidak memiliki default branch. Hubungi system administrator agar menambahkan default branch di User Setting."
                    % self.env.user.name))
            return [('id', '=', user.branch_id.id)]
        company_id = self._context.get('company_id',
                                       self.env.user.company_id.id)
        branch_ids = [
            b.id for b in self.env.user.branch_ids
            if b.company_id.id == company_id
        ]
        return [('id', 'in', branch_ids)]

    @api.one
    @api.depends('line_ids.amount_real')
    def _compute_amount(self):
        if self.line_ids:
            self.amount_real = sum(line.amount_real for line in self.line_ids)

    @api.one
    @api.depends('line_ids.amount', 'pettycash_id.amount')
    def _get_amount(self):
        if self.line_ids:
            amount = self.pettycash_id.amount - sum(line.amount
                                                    for line in self.line_ids)
            self.amount = amount

    @api.one
    @api.depends('line_ids.amount', 'pettycash_id.amount')
    def _get_total_cash_in(self):
        total_cash_in = sum(line.amount for line in self.line_ids)
        self.total_cash_in = total_cash_in

    def ubah_tanggal(self, tanggal):
        if not tanggal:
            return False
        try:
            conv = datetime.strptime(tanggal, '%d-%m-%Y %H:%M')
            return conv.strftime('%d-%m-%Y')
        except Exception as e:
            conv = datetime.strptime(tanggal, '%Y-%m-%d %H:%M:%S')
            return conv.strftime('%d-%m-%Y')

    def ubah_tanggal_2(self, tanggal):
        if not tanggal:
            return False
        try:
            conv = datetime.strptime(tanggal, '%d-%m-%Y')
            return conv.strftime('%d-%m-%Y')
        except Exception as e:
            conv = datetime.strptime(tanggal, '%Y-%m-%d')
            return conv.strftime('%d-%m-%Y')

    @api.model
    def _get_analytic_company(self):
        company = self.pool.get('res.users').browse(self._cr, self._uid,
                                                    self._uid).company_id
        level_1_ids = self.pool.get('account.analytic.account').search(
            self._cr, self._uid, [('segmen', '=', 1),
                                  ('company_id', '=', company.id),
                                  ('type', '=', 'normal'),
                                  ('state', 'not in', ('close', 'cancelled'))])
        if not level_1_ids:
            raise osv.except_osv(
                ('Perhatian !'),
                ("Tidak ditemukan data analytic untuk company %s") %
                (company.name))
        return level_1_ids[0]

    name = fields.Char(string="Name", readonly=True, default='')
    branch_id = fields.Many2one('dym.branch',
                                string='Branch',
                                required=True,
                                default=_get_default_branch,
                                domain=_getCompanyBranch)
    division = fields.Selection(DIVISION_SELECTION,
                                string='Division',
                                default='Umum',
                                change_default=True,
                                select=True)
    amount = fields.Float('Receive Amount', compute=_get_amount)
    branch_destination_id = fields.Many2one('dym.branch',
                                            string='Branch Destination',
                                            required=True)
    journal_id = fields.Many2one(
        'account.journal',
        string="Payment Method",
        domain="[('branch_id','in',[branch_id,False]),('type','=','pettycash')]"
    )
    line_ids = fields.One2many('dym.pettycash.in.line',
                               'pettycash_id',
                               string="PettyCash Line")
    line_ids2 = fields.One2many('dym.pettycash.in.line',
                                'pettycash_id',
                                string="PettyCash Line")
    pay_supplier_invoice = fields.Boolean('Pay Supplier Invoice')
    state = fields.Selection(STATE_SELECTION,
                             string='State',
                             readonly=True,
                             default='draft')
    date = fields.Date(string="Date",
                       required=True,
                       readonly=True,
                       default=fields.Date.context_today)
    move_id = fields.Many2one('account.move',
                              string='Account Entry',
                              copy=False)
    move_ids = fields.One2many('account.move.line',
                               related='move_id.line_id',
                               string='Journal Items',
                               readonly=True)
    period_id = fields.Many2one('account.period',
                                string="Period",
                                required=True,
                                readonly=True,
                                default=_get_period)
    account_id = fields.Many2one('account.account', string="Account")
    confirm_uid = fields.Many2one('res.users', string="Posted by")
    confirm_date = fields.Datetime('Posted on')
    pettycash_id = fields.Many2one(
        'dym.pettycash',
        string='PCO (Kas Bon)',
        domain=
        "[('state','=','posted'),('branch_id','=',branch_id),('division','=',division),('kas_bon','=',True),('cash_in_ids','=',False),('line_ids.settlement','=',False)]"
    )
    pettycash_new_id = fields.Many2one('dym.pettycash', string='PCO (New)')
    pettycash_amount = fields.Float(related='pettycash_id.amount',
                                    string='Jumlah Kas Bon',
                                    readonly=True)
    journal_id_show = fields.Many2one(
        related='journal_id',
        store=True,
        readonly=True,
        string="Payment Method",
        domain="[('branch_id','=',branch_id),('type','=','pettycash')]")
    branch_destination_id_show = fields.Many2one(
        related='branch_destination_id',
        string='Branch Destination',
        readonly=True,
        store=True)

    analytic_1 = fields.Many2one('account.analytic.account',
                                 'Account Analytic Company')
    analytic_2 = fields.Many2one('account.analytic.account',
                                 'Account Analytic Bisnis Unit')
    analytic_3 = fields.Many2one('account.analytic.account',
                                 'Account Analytic Branch')
    analytic_4 = fields.Many2one('account.analytic.account',
                                 'Account Analytic Cost Center')

    balance = fields.Float('Balance')
    total_cash_in = fields.Float('Exepensed', compute=_get_total_cash_in)
    refund_all = fields.Boolean(
        string='Dikembalikan Semua',
        help='Cengtang jika uang tidak jadi digunakan, dikembalikan semua')

    date_cancel = fields.Date(string="Date Canceled", readonly=True)
    cancel_uid = fields.Many2one('res.users', string="Cancelled by")
    cancel_date = fields.Datetime('Cancelled on')

    _defaults = {
        'analytic_1': _get_analytic_company,
    }

    # @api.constrains('line_ids','pettycash_id')
    # def _constraint_amount(self):
    #     if self.amount < 0:
    #         raise osv.except_osv(('Perhatian !'), ("Amount di detail tidak boleh lebih besar dari Jumlah Kas Bon..."))

    @api.model
    def default_get(self, fields):
        res = super(dym_pettycash_in, self).default_get(fields)
        user = self.env.user
        if not user.branch_id:
            raise osv.except_osv(('Perhatian !'), (
                "User %s tidak memiliki default branch. Hubungi system administrator agar menambahkan default branch di User Setting."
                % self.env.user.name))
        if user.branch_type != 'HO':
            res['division'] = 'Unit'
        else:
            res['division'] = 'Finance'
        return res

    @api.multi
    def get_equal_amount(self, pettycash_id, received_amount, pettycash):
        pco = self.env['dym.pettycash'].browse(pettycash_id)
        pco_amount = pco.amount
        total_expenses = 0.0
        for x in pettycash:
            total_expenses += x['amount']
        if pco_amount != total_expenses + received_amount:
            raise osv.except_osv(
                ('Perhatian !'),
                ("Total Amount tidak sesuai, mohon cek kembali data Anda."))
        return True

    @api.model
    def create(self, vals, context=None):
        # if not vals['line_ids'] :
        #     raise osv.except_osv(('Perhatian !'), ("Detail belum diisi. Data tidak bisa di save."))
        pettycash = []
        rekap = []
        for x in vals['line_ids']:
            pettycash.append(x.pop(2))
        vals['date'] = datetime.today()
        if vals['journal_id']:
            journal_obj = self.env['account.journal'].search([
                ('id', '=', vals['journal_id'])
            ])
            vals['name'] = self.env['ir.sequence'].get_per_branch(
                vals['branch_id'], "PCI", division='Umum')
        if not vals['line_ids']:
            pettycash_id = super(dym_pettycash_in, self).create(vals)
        else:
            del [vals['line_ids']]
            equal_amount = self.get_equal_amount(vals['pettycash_id'],
                                                 vals['amount'], pettycash)
            pettycash_id = super(dym_pettycash_in, self).create(vals)
            if pettycash_id:
                total_amount = 0
                for y in pettycash:
                    pettycash_pool = self.env['dym.pettycash.in.line']
                    pettycash_pool.create({
                        'pettycash_id': pettycash_id.id,
                        'name': y['name'],
                        'account_id': y['account_id'],
                        'amount': y['amount'],
                        'analytic_1': y['analytic_1'],
                        'analytic_2': y['analytic_2'],
                        'analytic_3': y['analytic_3'],
                        'analytic_4': y['analytic_4'],
                    })
                    if y['account_id'] in rekap:
                        raise osv.except_osv(('Perhatian !'), (
                            "Tidak boleh ada Account yang sama dalam detail transaksi"
                        ))
                    elif y['account_id'] not in rekap:
                        rekap.append(y['account_id'])
                    total_amount += y['amount']

                # if pettycash_id.pettycash_id.amount - total_amount < 0:
                #     raise osv.except_osv(('Perhatian !'), ("Amount di detail tidak boleh lebih besar dari Jumlah Kas Bon"))
            else:
                return False
        return pettycash_id

    @api.onchange('division')
    def onchange_division(self):
        val = {}
        if self.branch_id and self.division:
            analytic_1, analytic_2, analytic_3, analytic_4 = self.env[
                'account.analytic.account'].get_analytical(
                    self.branch_id.id, self.division, False, 4, 'General')
            self.analytic_1 = analytic_1
            self.analytic_2 = analytic_2
            self.analytic_3 = analytic_3
            self.analytic_4 = analytic_4
        self.pettycash_id = False
        val['line_ids'] = []
        return {'value': val}

    @api.onchange('pettycash_id', 'branch_id', 'division')
    def onchange_branch(self):
        dom = {}
        self.branch_destination_id = self.pettycash_id.branch_destination_id
        self.journal_id = self.pettycash_id.journal_id
        self.account_id = self.pettycash_id.account_id
        self.journal_id_show = self.pettycash_id.journal_id
        self.branch_destination_id_show = self.pettycash_id.branch_destination_id
        self.pettycash_amount = self.pettycash_id.amount
        if self.branch_id and self.division:
            analytic_1, analytic_2, analytic_3, analytic_4 = self.env[
                'account.analytic.account'].get_analytical(
                    self.branch_id, 'Umum', False, 4, 'General')
            self.analytic_1 = analytic_1
            self.analytic_2 = analytic_2
            self.analytic_3 = analytic_3
            self.analytic_4 = analytic_4
        return {'domain': dom}

    # @api.multi
    # def action_return_all(self):
    #     move_line_id = self.pettycash_id.move_ids.filtered(lambda s:s.debit>0)
    #     for rec in self:
    #         rec.refund_all = True
    #         rec.amount = move_line_id.debit
    #         if not rec.line_ids:
    #             values = {
    #                 'name':move_line_id.name,
    #                 'pettycash_id':rec.id,
    #                 'account_id':move_line_id.account_id.id,
    #                 'amount':move_line_id.debit,
    #             }
    #             rec.write({'line_ids':[(0,0,values)]})

    @api.multi
    def action_cancel_return_all(self):
        for rec in self:
            rec.refund_all = False
            rec.amount = 0.0
            if rec.line_ids:
                rec.write({'line_ids': [(6, 0, [])]})

    @api.multi
    def post_pettycash_in(self):
        if not self.line_ids:
            view_id = self.env['ir.ui.view'].search([
                ("name", "=", "dym.pettycash.full.return.reason.wizard"),
                ("model", "=", 'dym.pettycash.full.return.reason'),
            ])
            return {
                'name': _('Petty cash full refund reason'),
                'view_type': 'form',
                'view_mode': 'form',
                'res_model': 'dym.pettycash.full.return.reason',
                'view_id': view_id.id,
                'domain': "[]",
                'target': 'new',
                'type': 'ir.actions.act_window',
            }
        self.action_move_line_create()
        self.action_update_amount_real()
        return True

    @api.multi
    def action_update_amount_real(self):
        pettycash = self.env['dym.pettycash.line']
        petty_in = {}
        srch_pettycash = pettycash.search([
            ('pettycash_id', '=', self.pettycash_id.id),
        ])[0]
        amount = 0
        for x in self.line_ids:
            amount += x.amount
        if amount > 0:
            srch_pettycash.write({
                'amount_real': amount,
                'settlement': True,
                'amount_reimbursed': 0
            })
        else:
            srch_pettycash.write({'settlement': True, 'amount_reimbursed': 0})

    @api.multi
    def action_revise(self):
        pass

    @api.multi
    def write(self, vals, context=None):
        vals.get('line_ids', []).sort(reverse=True)
        line = vals.get('line_ids', False)
        if line:
            for x, item in enumerate(line):
                petty_id = item[1]
                if item[0] == 1 or item[0] == 0:
                    value = item[2]
                    if value.get('account_id'):
                        for y in self.line_ids:
                            if y.account_id.id == value['account_id']:
                                raise osv.except_osv(('Perhatian !'), (
                                    "Tidak boleh ada Account yang sama dalam detail transaksi"
                                ))
        return super(dym_pettycash_in, self).write(vals)

    @api.multi
    def cancel_pettycash(self):
        self.state = 'cancel'
        self.date_cancel = datetime.today()
        self.cancel_uid = self._uid
        self.cancel_date = datetime.now()

    @api.multi
    def action_move_line_create(self):
        move_pool = self.env['account.move']
        move_line_pool = self.env['account.move.line']
        pco_pool = self.env['dym.pettycash']
        petty_line = self.env['dym.pettycash.line']
        for pci in self:
            account_id = pci.journal_id.default_credit_account_id.id or pci.journal_id.default_debit_account_id.id
            amount = pci.amount
            periods = self.env['account.period'].find(pci.date)
            pci.write({'period_id': periods.id})

            # REVERSE PCO KASBON JOURNAL
            move_data = {
                'name': pci.name,
                'journal_id': pci.journal_id.id,
                'date': pci.date,
                'ref': pci.pettycash_id.name,
                'period_id': pci.period_id.id,
                'transaction_id': pci.id,
                'model': pci.__class__.__name__,
            }
            move_id = move_pool.create(move_data)
            for pml in self.pettycash_id.move_id.line_id:
                pml_data = {
                    'name': pml.name,
                    'ref': pml.ref,
                    'account_id': pml.account_id.id,
                    'move_id': move_id.id,
                    'journal_id': pml.journal_id.id,
                    'period_id': periods.id,
                    'date': pci.date,
                    'debit': pml.credit or 0.0,
                    'credit': pml.debit or 0.0,
                    'branch_id': self.branch_id.id,
                    'division': self.division,
                    'analytic_account_id': pml.analytic_4.id
                }
                line_id = move_line_pool.create(pml_data)

            if pci.line_ids:
                # CREATE NEW PCO
                new_pco_lines = []
                total_amount_real = 0.0
                total_amount = 0.0
                for tpl in pci.line_ids:
                    total_amount_real += tpl.amount
                    total_amount += tpl.amount
                    new_pco_lines.append([
                        0, False, {
                            'branch_id': tpl.branch_id.id,
                            'division': tpl.division,
                            'name': tpl.name,
                            'account_id': tpl.account_id.id,
                            'amount': tpl.amount,
                            'kas_bon': False,
                            'amount_total': tpl.amount,
                            'amount_real': tpl.amount,
                            'amount_reimbursed': tpl.amount,
                            'analytic_1': tpl.analytic_1.id,
                            'analytic_2': tpl.analytic_2.id,
                            'analytic_3': tpl.analytic_3.id,
                            'analytic_4': tpl.analytic_4.id,
                            'analytic_4_readonly': tpl.analytic_4.id,
                        }
                    ])
                old_pco = pci.pettycash_id

                new_pco = {
                    "branch_id":
                    self.branch_id.id,
                    "analytic_1":
                    old_pco.analytic_1.id,
                    "analytic_2":
                    old_pco.analytic_2.id,
                    "analytic_3":
                    old_pco.analytic_3.id,
                    "analytic_4":
                    old_pco.analytic_4.id,
                    "journal_id":
                    old_pco.journal_id.id,
                    "amount_real":
                    total_amount_real,
                    "division":
                    old_pco.division,
                    "account_id":
                    old_pco.account_id.id,
                    "branch_destination_id":
                    old_pco.branch_destination_id.id,
                    "period_id":
                    periods.id,
                    "date":
                    pci.date,
                    "name":
                    self.env['ir.sequence'].get_per_branch(
                        self.branch_id.id, 'PCO', division=old_pco.division),
                    "amount":
                    total_amount,
                    "kas_bon":
                    False,
                    "line_ids":
                    new_pco_lines,
                    "cash_in":
                    pci.id,
                }

                new_pco_id = pco_pool.create(new_pco)
                pci.pettycash_new_id = new_pco_id
                if pci.journal_id.entry_posted:
                    posted = move_id.post()

            pci.write({
                'date': datetime.today(),
                'state': 'posted',
                'move_id': move_id.id,
                'account_id': account_id,
                'confirm_uid': self.env.user.id,
                'confirm_date': datetime.now()
            })

        return True

    '''
    @api.cr_uid_ids_context
    def action_move_line_create(self, cr, uid, ids, context=None):
        if context is None:
            context = {}
        move_pool = self.pool.get('account.move')
        move_line_pool = self.pool.get('account.move.line')
        petty_line = self.pool.get('dym.pettycash.line')
        periods = self.pool.get('account.period').find(cr, uid, context=context)
        for pettycash in self.browse(cr, uid, ids, context=context):
            pettycash.write({'period_id':periods and periods[0]})
            name = pettycash.name
            date = pettycash.date
            journal_id = pettycash.journal_id.id
            account_id = pettycash.journal_id.default_credit_account_id.id or pettycash.journal_id.default_debit_account_id.id
            amount = pettycash.amount          
            period_id = pettycash.period_id.id
            
            move = {
                'name': name,
                'journal_id': journal_id,
                'date': date,
                'ref':name,
                'period_id':period_id,
                'transaction_id':pettycash.id,
                'model':pettycash.__class__.__name__,
            }
            move_id = move_pool.create(cr, uid, move, context=None)

            if pettycash.refund_all:
                analytic_4 = pettycash.pettycash_id.analytic_4.id
                move_line1 = {
                    'name': _('PCO dikembalikah full'),
                    'ref':name,
                    'account_id': account_id,
                    'move_id': move_id,
                    'journal_id': journal_id,
                    'period_id': period_id,
                    'date': date,
                    'debit': pettycash.pettycash_amount,
                    'credit': 0.0,
                    'branch_id' : pettycash.branch_destination_id.id,
                    'division' : pettycash.division,   
                    'analytic_account_id' :analytic_4   
                }      
                line_id = move_line_pool.create(cr, uid, move_line1, context)
                move_line2 = {
                    'name': _('PCO dikembalikah full'),
                    'ref':name,
                    'account_id': pettycash.pettycash_id.line_ids[0].account_id.id,
                    'move_id': move_id,
                    'journal_id': journal_id,
                    'period_id': period_id,
                    'date': date,
                    'debit': 0.0,
                    'credit': pettycash.pettycash_amount,
                    'branch_id' : pettycash.branch_id.id,
                    'division' : pettycash.division,
                    'analytic_account_id' : pettycash.pettycash_id.line_ids[0].analytic_4.id     
                }
                line_id = move_line_pool.create(cr, uid, move_line2, context)
                if pettycash.journal_id.entry_posted:
                    posted = move_pool.post(cr, uid, [move_id], context=None)
                self.write(cr, uid, pettycash.id, {'date':datetime.today(),'state': 'posted', 'move_id': move_id,'account_id':account_id,'confirm_uid':uid,'confirm_date':datetime.now()})
            else:
                move_line1 = {
                    'name': _('PCO Kas Bon'),
                    'ref':name,
                    'account_id': pettycash.pettycash_id.line_ids[0].account_id.id,
                    'move_id': move_id,
                    'journal_id': journal_id,
                    'period_id': period_id,
                    'date': date,
                    'debit': 0.0,
                    'credit': pettycash.pettycash_amount,
                    'branch_id' : pettycash.branch_id.id,
                    'division' : pettycash.division,
                    'analytic_account_id' : pettycash.pettycash_id.line_ids[0].analytic_4.id     
                }
                line_id = move_line_pool.create(cr, uid, move_line1, context)
                if pettycash.amount > 0:
                    move_line1 = {
                        'name': _('Cash Back'),
                        'ref':name,
                        'account_id': account_id,
                        'move_id': move_id,
                        'journal_id': journal_id,
                        'period_id': period_id,
                        'date': date,
                        'debit': pettycash.amount,
                        'credit': 0.0,
                        'branch_id' : pettycash.pettycash_id.branch_id.id,
                        'division' : pettycash.pettycash_id.division,
                        'analytic_account_id' : pettycash.pettycash_id.analytic_4.id     
                    }
                    line_id3 = move_line_pool.create(cr, uid, move_line1, context)

                if pettycash.amount < 0:
                    move_line2 = {
                        'name': _('PCO Kas Bon'),
                        'ref':name,
                        'account_id': account_id,
                        'move_id': move_id,
                        'journal_id': journal_id,
                        'period_id': period_id,
                        'date': date,
                        'debit': 0.0,
                        'credit': abs(pettycash.amount),
                        'branch_id' : pettycash.branch_id.id,
                        'division' : pettycash.division,
                        'analytic_account_id' : pettycash.pettycash_id.line_ids[0].analytic_4.id     
                    }
                    line_id = move_line_pool.create(cr, uid, move_line2, context)

                for y in pettycash.line_ids :
                    petty_line_src = petty_line.search(cr, uid, [('pettycash_id','=',pettycash.pettycash_id.id),('account_id','=',y.account_id.id)])
                    analytic_4 = False
                    if petty_line_src:
                        analytic_4 = petty_line.browse(cr, uid, petty_line_src[0]).analytic_4.id
                    total_expenses = y.amount
                    move_line_3 = {
                        'name': y.name,
                        'ref':name,
                        'account_id': y.account_id.id,
                        'move_id': move_id,
                        'journal_id': journal_id,
                        'period_id': period_id,
                        'date': date,
                        'debit': y.amount,
                        'credit': 0.0,
                        'branch_id' : pettycash.branch_destination_id.id,
                        'division' : pettycash.division,   
                        'analytic_account_id' :y.analytic_4.id
                    }
                    line_id2 = move_line_pool.create(cr, uid, move_line_3, context)
                if pettycash.journal_id.entry_posted :    
                    posted = move_pool.post(cr, uid, [move_id], context=None)
                self.write(cr, uid, pettycash.id, {'date':datetime.today(),'state': 'posted', 'move_id': move_id,'account_id':account_id,'confirm_uid':uid,'confirm_date':datetime.now()})
                move_line_uang_muka = pettycash.pettycash_id.move_ids.filtered(lambda r: r.debit > 0 and r.account_id.id == pettycash.pettycash_id.line_ids[0].account_id.id)
                reconcile_id = move_line_pool.reconcile_partial(cr, uid, [line_id] + move_line_uang_muka.ids, 'auto')
        return True 
    '''

    @api.cr_uid_ids_context
    def unlink(self, cr, uid, ids, context=None):
        for item in self.browse(cr, uid, ids, context=context):
            if item.state != 'draft':
                raise osv.except_osv(
                    ('Perhatian !'),
                    ("Petty Cash in sudah diproses, data tidak bisa didelete !"
                     ))
        return super(dym_pettycash_in, self).unlink(cr,
                                                    uid,
                                                    ids,
                                                    context=context)

    @api.cr_uid_ids_context
    def create_intercompany_lines(self, cr, uid, ids, move_id, context=None):
        branch_rekap = {}
        branch_pool = self.pool.get('dym.branch')
        vals = self.browse(cr, uid, ids)
        move_line = self.pool.get('account.move.line')
        move_line_srch = move_line.search(cr, uid, [('move_id', '=', move_id)])
        move_line_brw = move_line.browse(cr, uid, move_line_srch)
        config = branch_pool.search(cr, uid, [('id', '=', vals.branch_id.id)])
        if config:
            config_browse = branch_pool.browse(cr, uid, config)
            inter_branch_header_account_id = config_browse.inter_company_account_id.id
            if not inter_branch_header_account_id:
                raise osv.except_osv(('Perhatian !'), (
                    "Account Inter Company belum diisi dalam Master branch %s !"
                ) % (vals.branch_id.name))

        #Merge Credit and Debit by Branch
        for x in move_line_brw:
            if x.branch_id not in branch_rekap:
                branch_rekap[x.branch_id] = {}
                branch_rekap[x.branch_id]['debit'] = x.debit
                branch_rekap[x.branch_id]['credit'] = x.credit
            else:
                branch_rekap[x.branch_id]['debit'] += x.debit
                branch_rekap[x.branch_id]['credit'] += x.credit

        #Make account move
        for key, value in branch_rekap.items():
            if key != vals.branch_id:
                branch = branch_pool.search(cr, uid, [('id', '=', key.id)])

                if branch:
                    branch_browse = branch_pool.browse(cr, uid, branch)
                    inter_branch_detail_account_id = branch_browse.inter_company_account_id.id
                    if not inter_branch_detail_account_id:
                        raise osv.except_osv(('Perhatian !'), (
                            "Account Inter belum diisi dalam Master branch %s - %s!"
                        ) % (key.code, key.name))

                balance = value['debit'] - value['credit']
                debit = abs(balance) if balance < 0 else 0
                credit = balance if balance > 0 else 0

                if balance != 0:
                    move_line_create = {
                        'name': _('Interco Petty Cash In %s') % (key.name),
                        'ref': _('Interco Petty Cash In %s') % (key.name),
                        'account_id': inter_branch_header_account_id,
                        'move_id': move_id,
                        'journal_id': vals.journal_id.id,
                        'period_id': vals.period_id.id,
                        'date': vals.date,
                        'debit': debit,
                        'credit': credit,
                        'branch_id': key.id,
                        'division': vals.division
                    }
                    inter_first_move = move_line.create(
                        cr, uid, move_line_create, context)

                    move_line2_create = {
                        'name':
                        _('Interco Petty Cash In %s') % (vals.branch_id.name),
                        'ref':
                        _('Interco Petty Cash In %s') % (vals.branch_id.name),
                        'account_id':
                        inter_branch_detail_account_id,
                        'move_id':
                        move_id,
                        'journal_id':
                        vals.journal_id.id,
                        'period_id':
                        vals.period_id.id,
                        'date':
                        vals.date,
                        'debit':
                        credit,
                        'credit':
                        debit,
                        'branch_id':
                        vals.branch_id.id,
                        'division':
                        vals.division
                    }
                    inter_second_move = move_line.create(
                        cr, uid, move_line2_create, context)
        return True