Beispiel #1
0
    def post(self, path, vals):
        config = self.instance()

        payload = simplejson.dumps(vals)
        url = config.get('cenit_url') + API_PATH + path
        headers = self.headers(config)

        try:
            _logger.info("[POST] %s ? %s {%s}", url, payload, headers)
            r = requests.post(url, data=payload, headers=headers)
        except Exception as e:
            _logger.error(e)
            raise exceptions.AccessError("Error trying to connect to Cenit.")
        if 200 <= r.status_code < 300:
            return r.json()

        try:
            error = r.json()
            _logger.error(error)
        except Exception as e:
            _logger.error(e)
            raise exceptions.ValidationError("Cenit returned with errors")

        if 400 <= error.get('code', 400) < 500:
            raise exceptions.AccessError("Error trying to connect to Cenit.")

        raise exceptions.ValidationError("Cenit returned with errors")
Beispiel #2
0
    def get(self, path, params=None):
        config = self.instance()

        url = config.get('cenit_url') + API_PATH + path
        headers = self.headers(config)
        try:
            _logger.info("[GET] %s ? %s {%s}", url, params, headers)
            r = requests.get(url, params=params, headers=self.headers(config))
        except Exception as e:
            _logger.error(e)
            raise exceptions.AccessError("Error trying to connect to Cenit.")

        if 200 <= r.status_code < 300:
            return r.json()

        try:
            error = r.json()
            _logger.error(error)
        except Exception as e:
            _logger.error(e)
            _logger.info("\n\n%s\n", r.content)
            raise exceptions.ValidationError("Cenit returned with errors")

        if 400 <= error.get('code', 400) < 500:
            raise exceptions.AccessError("Error trying to connect to Cenit.")

        raise exceptions.ValidationError("Cenit returned with errors")
Beispiel #3
0
    def delete(self, path):
        config = self.instance()

        url = config.get('cenit_url') + API_PATH + path
        headers = self.headers(config)

        try:
            _logger.info("[DEL] %s ? {%s}", url, headers)
            r = requests.delete(url, headers=headers)
        except Exception as e:
            _logger.error(e)
            raise exceptions.AccessError("Error trying to connect to Cenit.")

        if 200 <= r.status_code < 300:
            return True

        try:
            error = r.json()
            _logger.error(error)
        except Exception as e:
            _logger.error(e)
            raise exceptions.ValidationError("Cenit returned with errors")

        if 400 <= error.get('code', 400) < 500:
            raise exceptions.AccessError("Error trying to connect to Cenit.")

        raise exceptions.ValidationError("Cenit returned with errors")
Beispiel #4
0
 def check_amount(self):
     if self.amount_advance <= 0:
         raise exceptions.ValidationError(
             _("Amount of advance must be "
               "positive."))
     if self.env.context.get('active_id', False):
         order = self.env["sale.order"].\
             browse(self.env.context['active_id'])
         if str(self.amount_advance) > ("%.2f" %
                                        round(order.amount_residual, 2)):
             raise exceptions.ValidationError(
                 _("Amount of advance is "
                   "greater than residual "
                   "amount on sale"))
Beispiel #5
0
 def _check_private_methods(self):
     for access in self:
         if not access.private_methods:
             continue
         for line in access.private_methods.split("\n"):
             if not line:
                 continue
             if not line.startswith("_"):
                 raise exceptions.ValidationError(
                     _('Public method (not starting with "_" listed in private methods whitelist'
                       ))
             if line not in self._get_method_list():
                 raise exceptions.ValidationError(
                     _("Method %r is not part of the model's method list:\n %r"
                       ) % (line, self._get_method_list()))
Beispiel #6
0
    def _check_context(self):
        Model = self.env[self.model_id.model]
        fields = Model.fields_get()
        for record in self:
            try:
                data = json.loads(record.context)
            except ValueError:
                raise exceptions.ValidationError(
                    _("Context must be jsonable."))

            for k, _v in data.items():
                if k.startswith("default_") and k[8:] not in fields:
                    raise exceptions.ValidationError(
                        _('The model "%s" has no such field: "%s".') %
                        (Model, k[8:]))
Beispiel #7
0
 def _check_valid_range(self):
     for tc in self:
         if tc.type == 'quantitative' and tc.min_value > tc.max_value:
             raise exceptions.ValidationError(
                 _("Question '%s' is not valid: "
                   "minimum value can't be higher than maximum value.") %
                 tc.name_get()[0][1])
Beispiel #8
0
    def install_collection(self, params=None):
        cenit_api = self.env['cenit.api']

        if params:
            key = params.keys()[0]
            if key == 'id':
                path = "/setup/collection"
                path = "%s/%s" % (path, params.get(key))
            else:
                path = "/setup/collection?"
                path = "%s%s=%s" % (path, key, params.get(key))

        rc = cenit_api.get(path)
        if isinstance(rc, list):
            rc = rc[0]
        data = rc
        if 'collections' in data:
            data = data['collections'][0]

        if not params:
            raise exceptions.ValidationError(
                "Cenit failed to install the collection")

        self.install_common_data(data)

        return True
Beispiel #9
0
    def get_collection_data(self, name, version=None):
        cenit_api = self.env['cenit.api']

        args = {
            'name': name,
        }
        if not version:
            args.update({'sort_by': 'shared_version', 'limit': 1})
        else:
            args.update({'shared_version': version})

        path = "/setup/cross_shared_collection"
        rc = cenit_api.get(path, params=args).get("cross_shared_collections",
                                                  False)

        if not isinstance(rc, list):
            raise exceptions.ValidationError(
                "Hey!! something wicked just happened")
        elif len(rc) != 1:
            raise exceptions.MissingError(
                "Required '%s [%s]' not found in Cenit" %
                (name, version or "any"))
        cross_id = rc[0]['id']
        path = "/setup/cross_shared_collection/%s" % (cross_id)
        rc = cenit_api.get(path)

        # data = {
        #     'id': rc.get('id'),
        #     'params': rc.get('pull_parameters', [])
        # }

        return rc
Beispiel #10
0
    def _install_webhooks(self, values):
        webhook_pool = self.env['cenit.webhook']
        names_pool = self.env['cenit.namespace']

        for webhook in values:
            hook_data = {
                'cenitID': webhook.get('id'),
                'name': webhook.get('name'),
                # 'namespace': webhook.get('namespace'),
                'path': webhook.get('path'),
                'method': webhook.get('method'),
                'purpose': webhook.get('purpose'),
            }

            domain = [('name', '=', webhook.get('namespace'))]
            candidates = names_pool.search(domain)
            if not candidates:
                raise exceptions.ValidationError(
                    "There's no namespace named %s" %
                    (webhook.get('namespace'), ))

            hook_data.update({'namespace': candidates[0].id})

            domain = [('name', '=', hook_data.get('name')),
                      ('namespace', '=', hook_data.get('namespace'))]
            candidates = webhook_pool.search(domain)

            if not candidates:
                hook = webhook_pool.with_context(local=True).create(hook_data)
            else:
                hook = candidates[0]
                hook.with_context(local=True).write(hook_data)

            hook_params = self._get_param_lines(hook.id, webhook, "hook")
            hook.with_context(local=True).write(hook_params)
Beispiel #11
0
 def _check_validity_check_in_check_out(self):
     """ verifies if check_in is earlier than check_out. """
     for attendance in self:
         if attendance.check_in and attendance.check_out:
             if attendance.check_out < attendance.check_in:
                 raise exceptions.ValidationError(
                     _('"Check Out" time cannot be earlier than "Check In" time.'
                       ))
 def _check_reference(self):
     for transaction in self.filtered(lambda tx: tx.state not in
                                      ('cancel', 'error')):
         if self.search_count([('reference', '=', transaction.reference)
                               ]) != 1:
             raise exceptions.ValidationError(
                 _('The payment transaction reference must be unique!'))
     return True
Beispiel #13
0
 def _check_valid_answers(self):
     for tc in self:
         if (tc.type == 'qualitative' and tc.ql_values
                 and not tc.ql_values.filtered('ok')):
             raise exceptions.ValidationError(
                 _("Question '%s' is not valid: "
                   "you have to mark at least one value as OK.") %
                 tc.name_get()[0][1])
Beispiel #14
0
    def _install_connection_roles(self, values):
        role_pool = self.env['cenit.connection.role']
        conn_pool = self.env['cenit.connection']
        hook_pool = self.env['cenit.webhook']
        names_pool = self.env['cenit.namespace']

        for role in values:
            role_data = {
                'cenitID': role.get('id'),
                'name': role.get('name')
                # 'namespace': role.get('namespace'),
            }

            domain = [('name', '=', role.get('namespace'))]
            candidates = names_pool.search(domain)
            if not candidates:
                raise exceptions.ValidationError(
                    "There's no namespace named %s" %
                    (role.get('namespace'), ))

            role_data.update({'namespace': candidates[0].id})

            domain = [('name', '=', role_data.get('name')),
                      ('namespace', '=', role_data.get('namespace'))]
            candidates = role_pool.search(domain)

            if not candidates:
                crole = role_pool.with_context(local=True).create(role_data)
            else:
                crole = candidates[0]
                crole.with_context(local=True).write(role_data)

            connections = []
            webhooks = []

            for connection in role.get('connections', []):
                domain = [('name', '=', connection.get('name')),
                          ('namespace', '=', connection.get('namespace'))]
                candidates = conn_pool.search(domain)

                if candidates:
                    conn = candidates[0]
                    connections.append(conn.id)

            for webhook in role.get('webhooks', []):
                domain = [('name', '=', webhook.get('name')),
                          ('namespace', '=', webhook.get('namespace'))]
                candidates = hook_pool.search(domain)

                if candidates:
                    hook = candidates[0]
                    webhooks.append(hook.id)

            role_members = {
                'connections': [(6, False, connections)],
                'webhooks': [(6, False, webhooks)],
            }
            crole.with_context(local=True).write(role_members)
Beispiel #15
0
    def unlink(self, **kwargs):
        rc = True
        try:
            rc = self.drop_from_cenit()
        except requests.ConnectionError as e:
            _logger.exception(e)
            raise exceptions.AccessError("Error trying to connect to Cenit.")
        except exceptions.AccessError:
            raise exceptions.AccessError("Error trying to connect to Cenit.")
        except Exception as e:
            _logger.exception(e)
            raise exceptions.ValidationError("Cenit returned with errors")

        if not rc:
            raise exceptions.ValidationError("Cenit returned with errors")

        rc = super(CenitApi, self).unlink(**kwargs)
        return rc
 def _check_authorize_state(self):
     failed_tx = self.filtered(
         lambda tx: tx.state == 'authorized' and tx.acquirer_id.
         provider not in self.env['payment.acquirer']._get_feature_support(
         )['authorize'])
     if failed_tx:
         raise exceptions.ValidationError(
             _('The %s payment acquirers are not allowed to manual capture mode!'
               % failed_tx.mapped('acquirer_id.name')))
Beispiel #17
0
    def _check_validity(self):
        """ Verifies the validity of the attendance record compared to the others from the same employee.
            For the same employee we must have :
                * maximum 1 "open" attendance record (without check_out)
                * no overlapping time slices with previous employee records
        """
        for attendance in self:
            # we take the latest attendance before our check_in time and check it doesn't overlap with ours
            last_attendance_before_check_in = self.env['hr.attendance'].search([
                ('employee_id', '=', attendance.employee_id.id),
                ('check_in', '<=', attendance.check_in),
                ('id', '!=', attendance.id),
            ], order='check_in desc', limit=1)
            if last_attendance_before_check_in and last_attendance_before_check_in.check_out and last_attendance_before_check_in.check_out > attendance.check_in:
                raise exceptions.ValidationError(_("Cannot create new attendance record for %(empl_name)s, the employee was already checked in on %(datetime)s") % {
                    'empl_name': attendance.employee_id.name,
                    'datetime': fields.Datetime.to_string(fields.Datetime.context_timestamp(self, fields.Datetime.from_string(attendance.check_in))),
                })

            if not attendance.check_out:
                # if our attendance is "open" (no check_out), we verify there is no other "open" attendance
                no_check_out_attendances = self.env['hr.attendance'].search([
                    ('employee_id', '=', attendance.employee_id.id),
                    ('check_out', '=', False),
                    ('id', '!=', attendance.id),
                ], order='check_in desc', limit=1)
                if no_check_out_attendances:
                    raise exceptions.ValidationError(_("Cannot create new attendance record for %(empl_name)s, the employee hasn't checked out since %(datetime)s") % {
                        'empl_name': attendance.employee_id.name,
                        'datetime': fields.Datetime.to_string(fields.Datetime.context_timestamp(self, fields.Datetime.from_string(no_check_out_attendances.check_in))),
                    })
            else:
                # we verify that the latest attendance with check_in time before our check_out time
                # is the same as the one before our check_in time computed before, otherwise it overlaps
                last_attendance_before_check_out = self.env['hr.attendance'].search([
                    ('employee_id', '=', attendance.employee_id.id),
                    ('check_in', '<', attendance.check_out),
                    ('id', '!=', attendance.id),
                ], order='check_in desc', limit=1)
                if last_attendance_before_check_out and last_attendance_before_check_in != last_attendance_before_check_out:
                    raise exceptions.ValidationError(_("Cannot create new attendance record for %(empl_name)s, the employee was already checked in on %(datetime)s") % {
                        'empl_name': attendance.employee_id.name,
                        'datetime': fields.Datetime.to_string(fields.Datetime.context_timestamp(self, fields.Datetime.from_string(last_attendance_before_check_out.check_in))),
                    })
Beispiel #18
0
    def _install_translators(self, values):
        trans_pool = self.env['cenit.translator']
        sch_pool = self.env['cenit.schema']
        names_pool = self.env['cenit.namespace']

        for translator in values:
            if translator.get('_type') not in ('Setup::Parser',
                                               'Setup::Renderer'):
                continue
            trans_data = {
                'cenitID': translator.get('id'),
                'name': translator.get('name'),
                'type_': translator.get('type'),
                'mime_type': translator.get('mime_type', False)
            }

            # Updating namespace for translator
            rc = names_pool.search([('name', '=', translator.get('namespace'))
                                    ])
            if not rc:
                raise exceptions.ValidationError(
                    "There's no namespace named %s" %
                    (translator.get('namespace'), ))

            trans_data.update({'namespace': rc[0].id})

            # Updating schema
            schema = translator.get({
                'Setup::Parser': 'target_data_type',
                'Setup::Renderer': 'source_data_type',
            }.get(translator.get('_type')), {})

            if schema:
                namesp = names_pool.search([('name', '=',
                                             schema.get('namespace'))])
                domain = [('name', '=', schema.get('name')),
                          ('namespace', '=', namesp[0].id)]
                candidates = sch_pool.search(domain)
                if candidates:
                    schema_id = candidates[0].id

                trans_data.update({'schema': schema_id})

            domain = [('name', '=', trans_data.get('name')),
                      ('namespace', '=', trans_data.get('namespace'))]
            candidates = trans_pool.search(domain)
            if not candidates:
                trans_pool.with_context(local=True).create(trans_data)
            else:
                candidates[0].with_context(local=True).write(trans_data)
Beispiel #19
0
    def create(self, vals):
        obj = super(CenitApi, self).create(vals)

        local = self.env.context.get('local', False)
        if local:
            return obj

        rc = False
        try:
            rc = obj.push_to_cenit()
        except requests.ConnectionError as e:
            _logger.exception(e)
            raise exceptions.AccessError("Error trying to connect to Cenit.")
        except exceptions.AccessError:
            raise exceptions.AccessError("Error trying to connect to Cenit.")
        except Exception as e:
            _logger.exception(e)
            raise exceptions.ValidationError("Cenit returned with errors")

        if not rc:
            raise exceptions.ValidationError("Cenit returned with errors")

        return obj
Beispiel #20
0
 def _check_methods(self):
     for record in self:
         methods = [
             record.api_create,
             record.api_read,
             record.api_update,
             record.api_delete,
             record.api_public_methods,
         ]
         methods += (record.public_methods or "").split("\n")
         methods += (record.private_methods or "").split("\n")
         if all(not m for m in methods):
             raise exceptions.ValidationError(
                 _('You must select at least one API method for "%s" model.'
                   ) % record.model)
Beispiel #21
0
    def qrcode(self, data):
        # TODO: Make QR code parameters configurable.
        qr = qrcode.QRCode(
            version=1,
            error_correction=qrcode.constants.ERROR_CORRECT_L,
            box_size=10,
            border=4,
        )
        qr.add_data(data)
        try:
            qr.make(fit=True)
        except qrcode.exceptions.DataOverflowError:
            raise exceptions.ValidationError(_(
                u'Data size exceeds the QR code storage capacity.'))

        buf = io.BytesIO()
        qr.make_image().save(buf)

        return {
            'image': buf.getvalue(),
        }
Beispiel #22
0
    def _check_fields(self):
        # this exports record used in openapi.access
        if not self.env["openapi.access"].search_count(
            ["|", ("read_one_id", "=", self.id), ("read_many_id", "=", self.id)]
        ):
            return True

        fields = self.export_fields.mapped("name")
        for field in fields:
            field_count = fields.count(field)
            if field_count > 1:
                self.export_fields.search(
                    [("name", "=", field)], limit=field_count - 1
                ).unlink()

        fields.sort()
        for i in range(len(fields) - 1):
            if fields[i + 1].startswith(fields[i]) and "/" in fields[i + 1].replace(
                fields[i], ""
            ):
                raise exceptions.ValidationError(
                    _('You must delete the "%s" field or "%s" field')
                    % (fields[i], fields[i + 1])
                )
Beispiel #23
0
    def write(self, vals):
        res = super(CenitApi, self).write(vals)

        local = self.env.context.get('local', False)
        if local:
            return res

        cp = vals.copy()
        if cp.pop('cenitID', False):
            if len(cp.keys()) == 0:
                return res

        try:
            self.push_to_cenit()
        except requests.ConnectionError as e:
            _logger.exception(e)
            raise exceptions.AccessError("Error trying to connect to Cenit.")
        except exceptions.AccessError:
            raise exceptions.AccessError("Error trying to connect to Cenit.")
        except Exception as e:
            _logger.exception(e)
            raise exceptions.ValidationError("Cenit returned with errors")

        return res
 def _verify_pin(self):
     for employee in self:
         if employee.pin and not employee.pin.isdigit():
             raise exceptions.ValidationError(
                 _("The PIN must be a sequence of digits."))
Beispiel #25
0
 def _check_mo_grouping_interval(self):
     if self.mo_grouping_interval < 0:
         raise exceptions.ValidationError(
             _("You have to enter a positive value for interval."),
         )
Beispiel #26
0
 def _check_mo_grouping_max_hour(self):
     if self.mo_grouping_max_hour < 0 or self.mo_grouping_max_hour > 23:
         raise exceptions.ValidationError(
             _("You have to enter a valid hour between 0 and 23."),
         )
Beispiel #27
0
    def fields_view_get(self,
                        view_id=None,
                        view_type='tree',
                        context=None,
                        toolbar=False):

        rc = super(CenitAccountSettings,
                   self).fields_view_get(view_id=view_id,
                                         view_type=view_type,
                                         toolbar=toolbar)

        if self.env.context.get('next_view'):
            arch = rc['arch']

            email = self.env.context.get('email')
            passwd = self.env.context.get('passwd')
            confirmation = self.env.context.get('confirmation')

            icp = self.env["ir.config_parameter"]
            hub_host = icp.get_param("flectra_cenit.cenit_url",
                                     default='https://cenit.io')
            if hub_host.endswith("/"):
                hub_host = hub_host[:-1]
            path = "/setup/user"
            vals = {
                "email": email,
                "password": passwd,
                "password_confirmation": confirmation
            }

            payload = simplejson.dumps(vals)
            url = hub_host + "/api/v2" + path

            try:
                _logger.info("[POST] %s", url)
                r = requests.post(url, data=payload)
            except Exception as e:
                _logger.error(e)
                raise exceptions.AccessError(
                    "Error trying to connect to Cenit.")

            if 200 <= r.status_code < 300:
                response = r.json()
            else:
                try:
                    error = r.json()
                    _logger.error(error)
                except Exception as e:
                    _logger.error(e)
                    raise exceptions.ValidationError(
                        "Cenit returned with errors")

                if r.status_code == 406:
                    key = str(error.keys()[0])
                    raise exceptions.ValidationError(key.capitalize() + " " +
                                                     str(error[key][0]))
                else:
                    raise exceptions.AccessError(
                        "Error trying to connect to Cenit.")

            token = response.get('token', False)

            icp = self.env['ir.config_parameter']

            hub_hook = "captcha"
            hub_url = "{}/{}/{}".format(hub_host, hub_hook, token)

            try:
                r = requests.get(hub_url)
            except Exception as e:
                _logger.error("\n\Error: %s\n", e)
                raise exceptions.AccessError(
                    "Error trying to connect to Cenit.")

            icp.set_param('cenit.captcha.token', token)

            arch = arch.replace('img_data_here', '{}'.format(hub_url))

            rc['arch'] = arch
        return rc
Beispiel #28
0
 def _check_fi(self):
     if not self.user_fi:
         raise exceptions.ValidationError(
             "Data Final Inspeksi Tidak boleh kosong !!!")
Beispiel #29
0
 def _check_fi(self):
     if not self.user_kas:
         raise exceptions.ValidationError(
             "Data Kasir Tidak boleh kosong !!!")
Beispiel #30
0
 def _check_fi(self):
     if not self.user_pm:
         raise exceptions.ValidationError(
             "Data Partman Tidak boleh kosong !!!")