Esempio n. 1
0
 def _check_complex_requirements(self):
     """
     Checks fields requirements that are dependant on others
     """
     if self.application_id.web_create_type == "base":
         if not self.title:
             raise except_orm(
                 _('Data error!'),
                 _("You need to specify a title when applying for a base")
             )
         if not self.prefix:
             raise except_orm(
                 _('Data error!'),
                 _("You need to specify a prefix when applying for a base")
             )
         if not self.domain_id:
             raise except_orm(
                 _('Data error!'),
                 _("You need to specify a domain when applying for a base")
             )
     elif self.application_id.web_create_type == "service":
         if not self.suffix:
             raise except_orm(
                 _('Data error!'),
                 _("You need to specify a suffix when "
                   "applying for a service")
             )
         if not (self.environment_id or self.environment_prefix):
             raise except_orm(
                 _('Data error!'),
                 _("You need to specify an existing or new environment "
                   "when applying for a service")
             )
Esempio n. 2
0
    def _check_links_and_metadata(self):
        """
        Checks that at least one - and only one - of the three links is defined
        Checks that the application_metadata has the right application id
        """
        # At least one should be defined
        if not self.link:
            raise except_orm(
                _('Pricegrid error!'),
                _("You cannot define a pricegrid line without linking "
                  "it to a base or service or application.")
            )
        # No more than one should be defined
        if (self.link_base and self.link_application or
                self.link_base and self.link_service or
                self.link_application and self.link_service):
            raise except_orm(
                _('Pricegrid error!'),
                _("Pricegrid links to application/service/base "
                  "are exclusive to one another.")
            )

        # Update application_id since the links may have changed
        self.application_id = self._compute_application_id()[0]

        if self.application_id.id != \
                self.application_metadata.application_id.id:
            raise except_orm(
                _('Pricegrid error!'),
                _("The metadata should be associated with the "
                  "same application as the pricegrid.")
            )
Esempio n. 3
0
    def _check_env_and_prefix_not_used(self):
        """
        Checks that there is no existing service
        using this environment with the same service suffix
        """
        if self.application_id.web_create_type == 'service' \
                and self.environment_id:
            service = self.env['clouder.service'].search([
                ('suffix', '=', self.suffix),
                ('environment_id', '=', self.environment_id.id)
            ])

            if service:
                raise except_orm(
                    _('Session duplicate error!'),
                    _('Container already exists with environment '
                      '{0} and prefix {1}').format(
                        self.environment_id.prefix,
                        self.suffix
                    )
                )
            session = self.search([
                ('id', '!=', self.id),
                ('suffix', '=', self.suffix),
                ('environment_id', '=', self.environment_id.id)
            ])
            if session:
                raise except_orm(
                    _('Session duplicate error!'),
                    _('Session already exists with environment '
                      '{0} and prefix {1}').format(
                        self.environment_id.prefix,
                        self.suffix
                    )
                )
Esempio n. 4
0
    def _check_envprefix_not_used(self):
        """
        Checks that there is no existing environment using the same prefix
        """
        if self.application_id.web_create_type == 'service' \
                and self.prefix and not self.environment_id:
            env = self.env['clouder.environment'].search([
                ('prefix', '=', self.environment_prefix)
            ])
            if env:
                raise except_orm(
                    _('Session duplicate error!'),
                    _('Environment prefix \'{0}\' already exists.').format(
                        self.environment_prefix
                    )
                )

            app_ids = [
                app.id for app in self.env['clouder.application'].search([
                    ('web_create_type', '=', 'service')
                ])
            ]
            session = self.search([
                ('id', '!=', self.id),
                ('application_id', 'in', app_ids),
                ('environment_id', '=', False),
                ('environment_prefix', '=', self.environment_prefix)
            ])
            if session:
                raise except_orm(
                    _('Session duplicate error!'),
                    _('Environment prefix \'{0}\' is already reserved.')
                    .format(self.environment_prefix)
                )
 def _check_create_type_pricegrids(self):
     if self.web_create_type != 'disabled' and not self.pricegrid_ids:
         raise except_orm(
             _('Application error!'),
             _("You cannot define a web creation type "
               "without defining price grids.")
         )
Esempio n. 6
0
 def _check_initial_invoice_amount_positive(self):
     if self.initial_invoice_amount < 0.0:
         raise except_orm(
             _('Application invoice error!'),
             _("You cannot set a negative amount "
               "as instance creation fees.")
         )
Esempio n. 7
0
 def _check_pricegrid_product(self):
     """
     Checks that the invoicing product is set if there are pricegrids
     """
     if self.pricegrid_ids and not self.invoicing_product_id:
         raise except_orm(
             _('Application pricegrid error!'),
             _("An application with pricegrids must "
               "have an invoicing product set.")
         )
Esempio n. 8
0
 def action_done(self):
     if self.demandeur_id and self.demandeur_id.user_id:
         user = self.env.user
         if user == self.demandeur_id.user_id:
             self.state = 'done'
             self.generatePurchaseRequest()
             self.send_notification('request_purchase_draft', self._context)
         else:
             raise exceptions.except_orm(
                 _(u"Seul celui qui a initié la demande peut la valider."))
Esempio n. 9
0
 def onchange_start_time(self):
     if self.start_time:
         self.end_time = self.start_time
         if self.session_id.start_date and self.session_id.end_date:
             if self.start_time[0:10] > self.session_id.end_date[
                     0:10] or self.end_time[
                         0:10] < self.session_id.start_date[0:10]:
                 raise except_orm(
                     'Thông báo',
                     'Ngày điểm danh phải thuộc ngày lớp hoạt động')
Esempio n. 10
0
 def get_default_attributes_available_ids(self, fields):
     params = self.env['ir.config_parameter']
     try:
         juicebar_concentration_ids = params.get_param(
             'pos_juice_bars.juicebar_concentration_ids', default='[]')
         return dict(juicebar_concentration_ids=[(
             6, 0, eval(juicebar_concentration_ids))])
     except Exception as e:
         raise exceptions.except_orm('Error',
                                     'Invalid Concentration Records IDs')
Esempio n. 11
0
 def execute(self, *args):
     """
     Render report and return the number of pages generated.
     """
     try:
         return self.proxy.Report.execute(*args)
     except (client.ProtocolError, socket.error) as e:
         self.start()
         for x in range(40):
             time.sleep(1)
             try:
                 return self.proxy.Report.execute(*args)
             except (client.ProtocolError, socket.error) as e:
                 self.error("EXCEPTION: %s %s" % (str(e), str(e.args)))
                 pass
             except client.Fault as e:
                 raise except_orm(_('Report Error'), e.faultString)
     except client.Fault as e:
         raise except_orm(_('Report Error'), e.faultString)
Esempio n. 12
0
 def admission_done(self):
     '''Method to confirm admission'''
     school_standard_obj = self.env['school.standard']
     ir_sequence = self.env['ir.sequence']
     student_group = self.env.ref('atts_course.group_school_student')
     emp_group = self.env.ref('base.group_user')
     for rec in self:
         if rec.age <= 5:
             raise except_orm(
                 _('Warning'),
                 _('''The student is not eligible.
                                Age is not valid.'''))
         domain = [('standard_id', '=', rec.standard_id.id)]
         # Checks the standard if not defined raise error
         if not school_standard_obj.search(domain):
             raise except_orm(
                 _('Warning'),
                 _('''The standard is not defined in a
                                  school'''))
         # Assign group to student
         rec.user_id.write(
             {'groups_id': [(6, 0, [emp_group.id, student_group.id])]})
         # Assign roll no to student
         number = 1
         for rec_std in rec.search(domain):
             rec_std.roll_no = number
             number += 1
         # Assign registration code to student
         reg_code = ir_sequence.next_by_code('student.registration')
         registation_code = (str(rec.school_id.state_id.name) + str('/') +
                             str(rec.school_id.city) + str('/') +
                             str(rec.school_id.name) + str('/') +
                             str(reg_code))
         stu_code = ir_sequence.next_by_code('student.code')
         student_code = (str(rec.school_id.code) + str('/') +
                         str(rec.year.code) + str('/') + str(stu_code))
         rec.write({
             'state': 'done',
             'admission_date': time.strftime('%Y-%m-%d'),
             'student_code': student_code,
             'reg_code': registation_code
         })
     return True
Esempio n. 13
0
 def getFreppleURL(self):
     '''
     Create an authorization header trusted by frePPLe
     '''
     user_company_webtoken = self.env.user.company_id.webtoken_key
     if not user_company_webtoken:
       raise exceptions.except_orm("FrePPLe company web token not configured")
     encode_params = dict(exp=round(time.time()) + 600,
                          user=self.env.user.login,
                          navbar=self.env.context.get("navbar", True))
     webtoken = jwt.encode(encode_params,
                           user_company_webtoken,
                           algorithm='HS256').decode('ascii')
     _url = self.env.context.get("url", "/")
     server = self.env.user.company_id.frepple_server
     if not server:
       raise exceptions.except_orm("FrePPLe server utl not configured")
     url = "%s%s?webtoken=%s" % (server, _url, webtoken)
     return url
Esempio n. 14
0
    def create(self, vals):
        result = super(account_move, self).create(vals)

        if 'cheque_expiry_date' in vals and vals['cheque_expiry_date']:
            current_date = date.today()
            current_date = datetime.strptime(str(current_date), "%Y-%m-%d")
            comp_date = datetime.strptime(vals['cheque_expiry_date'],
                                          "%Y-%m-%d")
            chk_date = datetime.strptime(vals['cheque_date'], "%Y-%m-%d")
            if comp_date < current_date:
                raise except_orm(
                    _('Warning!'),
                    _("Cheque Expiry Date should be after current date!"))
            if chk_date > comp_date:
                raise except_orm(
                    _('Warning!'),
                    _("Cheque Expiry Date should be after cheque date!"))

        return result
Esempio n. 15
0
 def onchange_phone_number(self, phone, field):
     res = {}
     if phone:
         res = self.validate_phone_number(phone, field)
         if not res:
             raise exceptions.except_orm(
                 _('Advertencia!'),
                 _(u'El número telefónico tiene el formato incorrecto. Ej: 0123-4567890. Por favor intente de nuevo'
                   ))
     return {'value': res}
Esempio n. 16
0
    def onchange_rif_er(self, field_value):
        res = {}

        if field_value:
            res = self.validate_rif_er(field_value)
            if not res:
                raise exceptions.except_orm(('Advertencia!'), (
                    'El rif tiene el formato incorrecto. Ej: VEV012345678 o VEE012345678. Por favor intente de nuevo'
                ))
        return {'value': res}
 def recompute_biaya(self):
     self.ensure_one()
     print('Recompute Biaya Siswa')
     if self.biayas and len(self.biayas) > 0:
         # siswas = self.env['siswa_ocb11.rombel_siswa'].search([('tahunajaran_id','=',self.tahunajaran_id.id),('jenjang','=',self.jenjang)])
         siswas = self.env['siswa_ocb11.rombel_siswa'].search([('tahunajaran_id','=',self.tahunajaran_id.id),('jenjang_id','=',self.jenjang_id.id)])
         for biy in self.biayas:
             for sis in siswas:
                 found = False
                 for siswa_biaya in sis.siswa_id.biayas:
                     if(siswa_biaya.biaya_id.id == biy.biaya_id.id):
                         found = True
                 
                 if not found:
                     print('Add biaya to : ' + sis.siswa_id.name)
                     # jika tidak tersedia maka inputkan baru
                     if sis.siswa_id.is_siswa_lama and biy.biaya_id.is_siswa_baru_only:
                         print('skip')
                     else:
                         if biy.biaya_id.is_bulanan:
                             for bulan_index in range(1,13):
                                 harga = biy.harga
                                 if biy.is_different_by_gender:
                                     if sis.siswa_id.jenis_kelamin == 'perempuan':
                                         harga = biy.harga_alt
                                 print(harga)
                                 self.env['siswa_keu_ocb11.siswa_biaya'].create({
                                     'name' : biy.biaya_id.name + ' ' + calendar.month_name[bulan_index],
                                     'siswa_id' : sis.siswa_id.id,
                                     'tahunajaran_id' : self.tahunajaran_id.id,
                                     'biaya_id' : biy.biaya_id.id,
                                     'bulan' : bulan_index,
                                     'harga' : harga,
                                     'amount_due' : harga,
                                     'jenjang_id' : self.jenjang_id.id
                                 })
                         else:
                             harga = biy.harga
                             if biy.is_different_by_gender:
                                 if sis.siswa_id.jenis_kelamin == 'perempuan':
                                     harga = biy.harga_alt
                             print(harga)
                             self.env['siswa_keu_ocb11.siswa_biaya'].create({
                                 'name' : biy.biaya_id.name,
                                 'siswa_id' : sis.siswa_id.id,
                                 'tahunajaran_id' : self.tahunajaran_id.id,
                                 'biaya_id' : biy.biaya_id.id,
                                 'harga' : harga,
                                 'amount_due' : harga,
                                 'jenjang_id' : self.jenjang_id.id
                             })
         print('End of Recompute Siswa Biaya')
     else:
         # raise error warning
         raise exceptions.except_orm(_('Warning'), _('There is no data to validate.'))
Esempio n. 18
0
    def action_move_line_create(self):

        for voucher_obj in self:
            wf_service = netsvc.LocalService('workflow')
            _logger.info(" comienzo voucher_obj.type : %s", voucher_obj.type)
            if voucher_obj.type == 'payment':
                if voucher_obj.issued_check_ids:
                    for check in voucher_obj.issued_check_ids:
                        check.write({
                            'issued':
                            True,
                            'receiving_partner_id':
                            voucher_obj.partner_id.id,
                        })
                        wf_service.trg_validate(self.env.uid,
                                                'account.issued.check',
                                                check.id, 'draft_handed',
                                                self.env.cr)
                else:
                    if voucher_obj.third_check_ids:
                        for check in voucher_obj.third_check_ids:

                            check_obj = self.env['account.third.check']
                            #result = check_obj.browse(self, check.id)
                            result = check_obj.browse(check.id)
                            if result.state != 'holding':
                                raise exceptions.except_orm(
                                    _('State!'),
                                    _('The check must be in holding state.'))
                                return False
                            else:
                                check.write({
                                    'destiny_partner_id':
                                    voucher_obj.partner_id,
                                })
                                # _logger.info("por el else de tercero result.state: %s",result.state)
                                wf_service.trg_validate(
                                    self.env.uid, 'account.third.check',
                                    check.id, 'draft_holding', self.env.cr)
                                wf_service.trg_validate(
                                    self.env.uid, 'account.third.check',
                                    check.id, 'holding_handed', self.env.cr)

            elif voucher_obj.type == 'receipt':
                _logger.info("priemro voucher_obj.type: %s and voucher_obj %s",
                             (voucher_obj.type, voucher_obj))

                for check in voucher_obj.third_check_receipt_ids:
                    check.write({
                        'source_partner_id': voucher_obj.partner_id.id,
                    })
                    wf_service.trg_validate(self.env.uid,
                                            'account.third.check', check.id,
                                            'draft_holding', self.env.cr)
        return super(account_payment, self).action_move_line_create()
    def write(self, vals):
        block_on_reserve = ("product_id", "product_uom", "type")
        update_on_reserve = ("price_unit", "product_uom_qty")
        keys = set(vals.keys())
        test_block = keys.intersection(block_on_reserve)
        test_update = keys.intersection(update_on_reserve)
        if test_block:
            for line in self:
                if not line.reservation_ids:
                    continue
                raise except_orm(
                    _("Error"),
                    _(
                        "You cannot change the product or unit of measure "
                        "of lines with a stock reservation. "
                        "Release the reservation "
                        "before changing the product."
                    ),
                )
        res = super().write(vals)
        if test_update:
            for line in self:
                if not line.reservation_ids:
                    continue
                if len(line.reservation_ids) > 1:
                    raise except_orm(
                        _("Error"),
                        _(
                            "Several stock reservations are linked with the "
                            "line. Impossible to adjust their quantity. "
                            "Please release the reservation "
                            "before changing the quantity."
                        ),
                    )

                line.reservation_ids.write(
                    {
                        "price_unit": line.price_unit,
                        "product_uom_qty": line.product_uom_qty,
                    }
                )
        return res
Esempio n. 20
0
    def create(self, values):
        if values:
            """if values.get('patient_phone'):
                res = self._validate_patient_phone(values['patient_phone'])
                if not res:
                    raise exceptions.except_orm(('Advertencia!'), (u'El número telefónico tiene un formato incorrecto.\nEj: 0123-4567890.\nPor favor intente de nuevo'))"""
            if values.get('calling_form_number'):
                res = self.env['calling']._validate_form_number(
                    values['calling_form_number'])
                if res:
                    if res.get('warning'):
                        raise exceptions.except_orm(('Advertencia!'), (
                            u'El número de planilla "%s" ya se encuentra registrado'
                        ) % (values['patient_id']))
                else:
                    raise exceptions.except_orm(
                        ('Advertencia!'),
                        (u'El número de planilla debe contener solo números.'))

            #DESCOMENTAR SI EL CLIENTE QUE TIENE COLECTIVOS ASOCIADOS DEBA SER SELECCIONADO DE FORMA OBLIGATORIA
            #if values.get('calling_client'):
            #    calling_collective_obj = self.env['collective']
            #    calling_collective_ids = calling_collective_obj.search([('collective_client_id','=',values.get('calling_client'))])
            #    if calling_collective_ids:
            #        if not values.get('calling_collective', False):
            #           raise exceptions.except_orm(('Advertencia!'), (u"Cliente seleccionado, posee colectivos asociados y Ud. no ha seleccionado ninguno. "
            #                                                                     "Por favor seleccione un colectivo para éste cliente."))
            """if not values.get('calling_user'):
                 raise exceptions.except_orm(('Advertencia!'), (
                     u"Debe seleccionar el teleoperador que está registrando la llamada. "))"""
            #else:
            #user_id = self.env['hr.employee'].search([('user_id', '=', self._uid)])
            #if user_id:
            #   if values.get('calling_user') != user_id.id:
            #       raise exceptions.except_orm(('Advertencia!'), (u"El teleoperador seleccionado no corresponde con el usuario que está registrando la llamada. "
            #        u"Por favor verifique que el teleoperador y el usuario sean el mismo."))
            #else:
            #    raise exceptions.except_orm(('Advertencia!'), (u"El teleoperador no ha sido asociado con el usuario de la aplicación. "
            #        u"Por favor verifique que el operador esté asociado al usuario del ERP."))

        record = super(calling, self).create(values)
        return record
Esempio n. 21
0
    def approve_request(self):
        """This Approve the employee salary advance request.
                   """
        emp_obj = self.env['hr.employee']
        address = emp_obj.browse([self.employee_id.id]).address_home_id
        if not address.id:
            raise except_orm('Error!', 'Define home address for employee')
        salary_advance_search = self.search([('employee_id', '=',
                                              self.employee_id.id),
                                             ('id', '!=', self.id),
                                             ('state', '=', 'approve')])
        current_month = datetime.strptime(str(self.date),
                                          '%Y-%m-%d').date().month
        for each_advance in salary_advance_search:
            existing_month = datetime.strptime(str(each_advance.date),
                                               '%Y-%m-%d').date().month
            if current_month == existing_month:
                raise except_orm('Error!',
                                 'Advance can be requested once in a month')
        if not self.employee_contract_id:
            raise except_orm('Error!', 'Define a contract for the employee')
        struct_id = self.employee_contract_id.struct_id
        if not struct_id.max_percent or not struct_id.advance_date:
            raise except_orm(
                'Error!',
                'Max percentage or advance days are not provided in Contract')
        adv = self.advance
        amt = (self.employee_contract_id.struct_id.max_percent *
               self.employee_contract_id.wage) / 100
        if adv > amt and not self.exceed_condition:
            raise except_orm('Error!',
                             'Advance amount is greater than allotted')

        if not self.advance:
            raise except_orm('Warning',
                             'You must Enter the Salary Advance amount')
        payslip_obj = self.env['hr.payslip'].search([
            ('employee_id', '=', self.employee_id.id), ('state', '=', 'done'),
            ('date_from', '<=', self.date), ('date_to', '>=', self.date)
        ])
        if payslip_obj:
            raise except_orm('Warning', "This month salary already calculated")

        for slip in self.env['hr.payslip'].search([('employee_id', '=',
                                                    self.employee_id.id)]):
            slip_moth = datetime.strptime(str(slip.date_from),
                                          '%Y-%m-%d').date().month
            if current_month == slip_moth + 1:
                slip_day = datetime.strptime(str(slip.date_from),
                                             '%Y-%m-%d').date().day
                current_day = datetime.strptime(str(self.date),
                                                '%Y-%m-%d').date().day
                if current_day - slip_day < struct_id.advance_date:
                    raise exceptions.Warning(
                        _('Request can be done after "%s" Days From prevoius month salary'
                          ) % struct_id.advance_date)
        self.state = 'waiting_approval'
Esempio n. 22
0
 def create(self, vals):
     class_obj = self.env['education.student.class']
     class_brw = class_obj.browse(vals['class_id'])
     if 'class_id' in vals and 'promote_to_class' in vals:
         if vals['class_id'] and vals['promote_to_class']:
             if class_brw.is_last_class:
                 raise except_orm(
                     _('Warning!'),
                     _("You cannot proceed with promotion process for %s!")
                     % class_brw.name)
             if not class_brw.next_class:
                 raise except_orm(_('Warning!'),
                                  _("Next class is not defined!"))
             if class_obj.browse(vals['promote_to_class']
                                 ).id != class_brw.next_class.id:
                 raise except_orm(
                     _('Warning!'),
                     _("promote to class can not be equal to or lower than current class!!"
                       ))
     return super(PromoteStudent, self).create(vals)
    def validate_process(self):
        """Validate process by checking all the conditions and return back with inbound shipment
            object"""
        shipment_obj = self.env['inbound.shipment.plan.ept']
        if not self.choose_file:
            raise except_orm(('Unable to process..!'),
                             ('Please select file to process...'))

        shipment_plan = shipment_obj.browse(
            self._context.get('shipment_id', []))
        return shipment_plan
Esempio n. 24
0
 def onchange_major_id_session_id(self):
     if self.major_id and self.session_id:
         major_id = self.major_id.id
         is_in = False
         for item in self.session_id.timetable_ids:
             if item.major_id:
                 if major_id == item.major_id.id:
                     is_in = True
                     break
         if not is_in:
             raise except_orm('Thông báo', 'Môn học phải thuộc lớp học')
Esempio n. 25
0
    def create(self, vals):
        new = super(hr_employee_overtime, self).create(vals)

        #kiểm tra phòng ban
        if new.employee_id.department_id:
            new.department_id = new.employee_id.department_id.id
        else:
            raise except_orm('Thông báo',
                             'Nhân viên không thuộc phòng ban nào!')

        return new
Esempio n. 26
0
 def onchange_applicant_id(self):
     if self.applicant_id:
         query = """select status_applicant from hr_applicant where id = %s"""
         self._cr.execute(query, (self.applicant_id.id, ))
         res_query = self._cr.dictfetchone()
         print("nguyen vân nh " + str(res_query))
         if res_query:
             if res_query['status_applicant'] == 'is_employee':
                 raise except_orm(_('Thông báo'),
                                  _('Ứng viên này đã là nhân viên!'))
                 return
Esempio n. 27
0
 def getFreppleURL(self):
     '''
     Create an authorization header trusted by frePPLe
     '''
     user_company_webtoken = self.env.user.company_id.webtoken_key
     if not user_company_webtoken:
         raise exceptions.except_orm(
             "FrePPLe company web token not configured")
     encode_params = dict(exp=round(time.time()) + 600,
                          user=self.env.user.login,
                          navbar=self.env.context.get("navbar", True))
     webtoken = jwt.encode(encode_params,
                           user_company_webtoken,
                           algorithm='HS256').decode('ascii')
     _url = self.env.context.get("url", "/")
     server = self.env.user.company_id.frepple_server
     if not server:
         raise exceptions.except_orm("FrePPLe server utl not configured")
     url = "%s%s?webtoken=%s" % (server, _url, webtoken)
     return url
Esempio n. 28
0
    def onchange_job_id(self):
        list_job = []

        for r in self.recruitment_session_id.recruitment_session_line_ids:
            list_job.append(r.job_id.id)

        if self.job_id.id not in list_job:
            raise except_orm(
                _('Thông báo'),
                _('Chức danh này không có trong đợt phỏng vấn. Vui lòng chọn lại !!!!!'
                  ))
 def action_done(self):
     is_finished = True
     for line in self.purchase_request_line_ids:
         if not line.is_finished:
             raise exceptions.except_orm(
                 "Chưa hoàn thành các yêu cầu mua hàng: cần cập nhật trạng thái hoàn thành cho từng yêu cầu."
             )
             is_finished = False
             break
     if is_finished:
         self.state = "done"
Esempio n. 30
0
 def action_invoice_cancel(self):
     '''
     @param self: object pointer
     '''
     if not self.order_id:
         raise except_orm(_('Warning'), _('Order id is not available'))
     for sale in self:
         for line in sale.order_line:
             line.write({'invoiced': 'invoiced'})
     self.state = 'invoice_except'
     return self.order_id.action_invoice_cancel
Esempio n. 31
0
    def create(self, vals):
        res = {}
        if vals.get('partner_id'):
            partner_id = vals.get('partner_id')
            partner_obj = self.env['res.partner'].search([('id', '=',
                                                           partner_id)])
            if (partner_obj.company_type == 'person'
                    and not partner_obj.identification_id):
                raise exceptions.except_orm(('Advertencia!'), (
                    u'El Cliente no posee Documento Fiscal, por favor diríjase a la configuación de %s, y realice el registro correctamente para poder continuar'
                ) % (partner_obj.name))
            if (partner_obj.company_type == 'company'):
                if (partner_obj.people_type_company == 'pjdo'
                        and not partner_obj.vat):
                    raise exceptions.except_orm(('Advertencia!'), (
                        u'El Cliente no posee Documento Fiscal, por favor diríjase a la configuación de %s, y realice el registro correctamente para poder continuar'
                    ) % (partner_obj.name))

        res = super(SaleOrderInnherit, self).create(vals)
        return res
Esempio n. 32
0
    def validacion_categoria(self, categoria):

        filtro = [('categoria', '=', categoria)]
        consulta = self.env['rules.org.structure'].search(filtro)

        if len(consulta) >= 1:
            raise except_orm(
                _('Error'),
                _('La estructura organizacional %s, ya cuenta con esa categoria favor de seleccionar otra !'
                  ) % consulta.name)
        return
Esempio n. 33
0
 def create(self, vals):
     res = {}
     if vals.get('vat'):
         res = self.validate_rif_er(vals.get('vat'))
         if not res:
             raise exceptions.except_orm(('Advertencia!'), (
                 'El rif tiene el formato incorrecto. Ej: V-012345678, E-012345678, J-012345678 o G-012345678. Por favor verifique el formato y si posee los 9 digitos como se indica en el Ej. e intente de nuevo'
             ))
         if not self.validate_rif_duplicate(vals.get('vat', False), True):
             raise exceptions.except_orm(('Advertencia!'), (
                 u'El cliente o proveedor ya se encuentra registrado con el rif: %s y se encuentra activo'
             ) % (vals.get('vat', False)))
     if vals.get('email'):
         res = self.validate_email_addrs(vals.get('email'), 'email')
         if not res:
             raise exceptions.except_orm(('Advertencia!'), (
                 'El email es incorrecto. Ej: [email protected]. Por favor intente de nuevo'
             ))
     res = super(RespartnerRif, self).create(vals)
     return res
Esempio n. 34
0
 def action_dg(self):
     direction = self.env['hr.department'].search([('code', '=', 'DG')])[0]
     if direction and self.env.user == direction.manager_id.user_id:
         self.state = 'ret_finance'
         if self.alerte_mail:
             self.send_notification('request_retour_finance_notif',
                                    self._context)
     else:
         raise exceptions.except_orm(
             _(u'Seul le Directeur Général peut valider la DA à ce niveau.')
         )
Esempio n. 35
0
 def validar_periodo(self, fecha):
     '''Función para validar Fecha de Documento'''
     fecha = datetime.strptime(fecha, "%Y-%m-%d")
     periodo = self.env['account.period'].search([('name', '=', fecha.year)
                                                  ])
     if len(periodo) == 0:
         raise except_orm("Error", "No hay ningún Período Contable")
     periodo_contable = periodo.lineas_periodo.filtered(
         lambda x: x.code == fecha.month)
     if len(periodo_contable) == 0:
         raise except_orm("Error", "No hay ningún Período Contable")
     fecha_actual = fields.Date.today()
     if datetime.strptime(fecha_actual, "%Y-%m-%d") < datetime.strptime(
             periodo_contable.fecha_inicio, "%Y-%m-%d"):
         raise except_orm(
             "Error",
             "La Fecha del registro está fuera del rango del Período")
     if datetime.strptime(fecha_actual, "%Y-%m-%d") > datetime.strptime(
             periodo_contable.fecha_cierre, "%Y-%m-%d"):
         raise except_orm("Error", "El Período Contable está Cerrado")
Esempio n. 36
0
    def copy(self, default=None):
        """ Lines can not be duplicated in this model
        """
        # NOTE: use ids argument instead of id for fix the pylint error W8106
        # method-required-super.
        if False:
            return super(AccountWhSrc, self).copy(default)

        raise exceptions.except_orm(
            _('Invalid Procedure!'),
            _("You can not duplicate lines"))
Esempio n. 37
0
    def move_to_next_status(self):
        self.forcing = False
        status_ids_ordered = self.env['adm.application.status'].search([], order="sequence")
        index = 0
        for status in status_ids_ordered:
            if status == self.status_id:
                # print("Encontrado! -> {}".format(index))
                break
            index += 1

        index += 1
        if index < len(status_ids_ordered):
            next_status = status_ids_ordered[index]

            if self.status_id.type_id == 'done':
                raise exceptions.except_orm(_('Application completed'), _('The Application is already done'))
            elif self.status_id.type_id == 'cancelled':
                raise exceptions.except_orm(_('Application cancelled'), _('The Application cancelled'))
            else:
                self.status_id = next_status
Esempio n. 38
0
 def action_wh_iva_supervisor(self):
     """ Validate the currencys are equal
     """
     for inv in self:
         if inv.amount_total == 0.0:
             raise exceptions.except_orm(
                 _('Acción Invalida!'),
                 _('Esta factura tiene una cantidad total% s% s verifique el '
                   'precio de los productos') %
                 (inv.amount_total, inv.currency_id.symbol))
     return True
Esempio n. 39
0
    def _check_base_domain_prefix_not_used(self):
        """
        Checks that there is no domain/prefix combination in bases
        """
        if self.application_id.web_create_type == 'base':
            base = self.env['clouder.base'].search([
                ('name', '=', self.prefix),
                ('domain_id', '=', self.domain_id.id)
            ])
            if base:
                raise except_orm(
                    _('Session duplicate error!'),
                    _('Base with domain \'{0}\' and name \'{1}\' '
                      'already exists.').format(
                        self.domain_id.name,
                        self.prefix
                    )
                )

            app_ids = [
                app.id for app in self.env['clouder.application'].search([
                    ('web_create_type', '=', 'base')
                ])
            ]
            session = self.search([
                ('id', '!=', self.id),
                ('application_id', 'in', app_ids),
                ('prefix', '=', self.prefix),
                ('domain_id', '=', self.domain_id.id)
            ])
            if session:
                raise except_orm(
                    _('Session duplicate error!'),
                    _('Base with domain \'{0}\' and name \'{1}\' '
                      'is already reserved.').format(
                        self.domain_id.name,
                        self.prefix
                    )
                )
Esempio n. 40
0
 def _check_web_create_type_next(self):
     """
     Checks that the base web type can only
     be applied on application that can have bases
     Checks that the next service/node
     is correctly set depending on the web_create type
     """
     if self.web_create_type == 'base':
         if not self.base:
             raise except_orm(
                 _('Data error!'),
                 _("You cannot attribute the web type 'Base' to an "
                   "application that cannot have bases."))
         if not self.next_service_id:
             raise except_orm(
                 _('Data error!'),
                 _("You need to specify the next service "
                   "for web type 'Base'"))
     elif self.web_create_type == 'service' and not self.next_node_id:
         raise except_orm(
             _('Data error!'),
             _("You need to specify the next node for "
               "web type 'Container'"))
Esempio n. 41
0
    def invoicing_unit(self):
        """
        Returns the invoicing unit of a pricegrid line
        """
        class_to_search = self.link_type + ".metadata"
        class_link = self.link_type.split('.')[-1] + "_id"

        # Search for the metadata
        metadata = self.env[class_to_search].search([
            (class_link, '=', self.link.id),
            ('name', '=', self.application_metadata.id)
        ])
        if not metadata:
            raise except_orm(
                _('Pricegrid invoicing_unit error!'),
                _("No linked metadata found for {0} '{1}'"
                  .format(self.link_type, self.link.name))
            )

        return metadata[0].value
Esempio n. 42
0
    def make_invoice(self):
        """
        Creates invoice and links it to the session
        """
        orm_inv = self.env['account.invoice']

        for session in self:
            # Check that the function isn't called with unsuitable sessions
            if session.state != 'payment_processed' or session.invoice_id:
                raise except_orm(
                    _('Clouder Web Session error!'),
                    _("You cannot launch invoice creation when a session "
                      "is not process or already has an invoice")
                )

            # Creating invoice
            inv_desc = "{0} {1}".format(
                session.application_id.invoicing_product_id.description_sale,
                session.name
            )
            invoice_data = {
                'amount': session.amount,
                'partner_id': session.partner_id.id,
                'product_id': session.application_id.invoicing_product_id.id,
                'name': inv_desc,
                'origin': session.reference
            }
            if self.version() >= 9.0:
                invoice_data['account_id'] = \
                    session.partner_id.property_account_receivable_id.id
            else:
                invoice_data['account_id'] = \
                    session.partner_id.property_account_receivable.id

            invoice_id = orm_inv.clouder_make_invoice(invoice_data)
            invoice = orm_inv.browse([invoice_id])[0]
            session.write({'invoice_id': invoice.id})

            # Validating invoice to create reference number
            invoice.signal_workflow('invoice_open')
Esempio n. 43
0
    def invoice_amount(self):
        """
        Given pricegrid lines for a single service/base:
        computes the amount to invoice
        """
        # Check that all lines are linked to the same object
        linked_recs = []
        for pgl in self:
            if pgl.link not in linked_recs:
                linked_recs.append(pgl.link)
                if len(linked_recs) > 1:
                    raise except_orm(
                        _('Pricegrid invoice_amount error!'),
                        _("This function should only be called from a set of "
                          "records linked to the same service "
                          "OR base OR application.")
                    )
        # Grouping lines by invoicing unit
        invoicing_data = {}
        for pgl in self:
            if pgl.application_metadata.id not in invoicing_data:
                invoicing_data[pgl.application_metadata.id] = {}
            if pgl.type not in invoicing_data[pgl.application_metadata.id]:
                invoicing_data[pgl.application_metadata.id][pgl.type] = []
            invoicing_data[pgl.application_metadata.id][pgl.type].append(pgl)

        # Sorting resulting lists by threshold
        for k, v in invoicing_data.iteritems():
            for table in v:
                v[table].sort(key=lambda x: x.threshold)

        # Computing final value*
        amount = 0.0
        for tables in invoicing_data.values():
            for k, lines in tables.iteritems():
                compare_unit = lines[0].invoicing_unit
                index = 0

                # No amount to add if the first threshold
                # is above current compare value
                if lines[index].threshold > compare_unit:
                    continue

                # Searching for the right line
                while (index+1) < len(lines) \
                        and lines[index+1].threshold <= compare_unit:
                    index += 1

                # Computing and adding price
                if lines[index].type == 'fixed':
                    amount += lines[index].price
                elif lines[index].type == 'mult':
                    amount += lines[index].price * compare_unit
                else:
                    # Preventing possible future type errors
                    raise except_orm(
                        _('Pricegrid invoice_amount error!'),
                        _("Unknown type '{0}' in pricegrid line for {1} '{2}'"
                            ".".format(
                                lines[index].type,
                                lines[index].link_type,
                                lines[index].link.name
                            ))
                    )
        return amount