Exemplo n.º 1
0
# -*- coding: utf-8 -*-
"""Compare results controller."""
from datetime import datetime

from sqlalchemy.exc import InvalidRequestError, ProgrammingError
from werkzeug.exceptions import BadRequest, NotFound

from projects.controllers.utils import raise_if_project_does_not_exist, \
    raise_if_experiment_does_not_exist, uuid_alpha
from projects.database import db_session
from projects.models import CompareResult

NOT_FOUND = NotFound("The specified compare result does not exist")


def list_compare_results(project_id):
    """Lists all compare results under a project.
    Args:
        project_id (str): the project uuid.
    Returns:
        A list of all compare results.
    """
    raise_if_project_does_not_exist(project_id)

    compare_results = db_session.query(CompareResult) \
        .filter_by(project_id=project_id) \
        .order_by(CompareResult.created_at.asc()) \
        .all()

    return [compare_result.as_dict() for compare_result in compare_results]
 def _validate_update(self, session, obj, existing_obj):
     """Participant summaries don't have a version value; drop it from validation logic."""
     if not existing_obj:
         raise NotFound('%s with id %s does not exist' %
                        (self.model_type.__name__, id))
Exemplo n.º 3
0
 def on_account_show(self, req):
     account_id = self._get_account_id(req)
     raw = self.backend.info_account(account_id)
     if raw is not None:
         return Response(json.dumps(raw), mimetype='text/json')
     return NotFound('Account not found')
Exemplo n.º 4
0
 def get(self, mine_guid):
     mine = Mine.find_by_mine_guid(mine_guid)
     if not mine:
         raise NotFound('Mine not found.')
     return mine.mine_tailings_storage_facilities
Exemplo n.º 5
0
 def on_status_what(self, _: Request, what: str) -> Response:
     status_what = self._STATUS_WHATS.get(what)
     if not status_what:
         raise NotFound()
     status = status_what(self.imageserver)
     return JsonRespone(status)
Exemplo n.º 6
0
    def mail_update_message(self,
                            res_model,
                            res_id,
                            message,
                            message_id,
                            redirect=None,
                            attachment_ids='',
                            attachment_tokens='',
                            **post):
        # keep this mecanism intern to slide currently (saas 12.5) as it is
        # considered experimental
        if res_model != 'slide.channel':
            raise Forbidden()
        res_id = int(res_id)

        attachment_ids = [
            int(attachment_id) for attachment_id in attachment_ids.split(',')
            if attachment_id
        ]
        attachment_tokens = [
            attachment_token
            for attachment_token in attachment_tokens.split(',')
            if attachment_token
        ]
        self._portal_post_check_attachments(attachment_ids, attachment_tokens)

        pid = int(post['pid']) if post.get('pid') else False
        if not _check_special_access(res_model,
                                     res_id,
                                     token=post.get('token'),
                                     _hash=post.get('hash'),
                                     pid=pid):
            raise Forbidden()

        # fetch and update mail.message
        message_id = int(message_id)
        message_body = plaintext2html(message)
        domain = [('model', '=', res_model), ('res_id', '=', res_id),
                  ('website_published', '=', True),
                  ('author_id', '=', request.env.user.partner_id.id),
                  ('message_type', '=', 'comment'),
                  ('id', '=', message_id)]  # restrict to the given message_id
        message = request.env['mail.message'].search(domain, limit=1)
        if not message:
            raise NotFound()
        message.write({
            'body': message_body,
            'attachment_ids': [(4, aid) for aid in attachment_ids],
        })

        # update rating
        if post.get('rating_value'):
            domain = [('res_model', '=', res_model), ('res_id', '=', res_id),
                      ('website_published', '=', True),
                      ('message_id', '=', message.id)]
            rating = request.env['rating.rating'].search(
                domain, order='write_date DESC', limit=1)
            rating.write({'rating': float(post['rating_value'])})

        # redirect to specified or referrer or simply channel page as fallback
        redirect_url = redirect or (request.httprequest.referrer
                                    and request.httprequest.referrer +
                                    '#review') or '/slides/%s' % res_id
        return werkzeug.utils.redirect(redirect_url, 302)
Exemplo n.º 7
0
 def _process_args(self):
     RHUserBase._process_args(self)
     self.identity = Identity.get_one(request.view_args['identity'])
     if self.identity.user != self.user:
         raise NotFound()
    def put(self, messageid):
        '''
        Modifies the title, body and editor properties of this message.

        INPUT PARAMETERS:
        :param str messageid: The id of the message to be deleted

        ENTITY BODY INPUT FORMAT:
        The entity body is a JSON representation with the following format:
            {'title': <newTitle>, 'body': <newBody>, 'editor': <editor name>}

        If <editor> is empty, use 'Anonymous' instead.

        OUTPUT:
         * Returns 204 if the message is modified correctly
         * Returns 400 if the body of the request is not well formed or it is
           empty.
         * Returns 404 if there is no message with messageid
         * Returns 415 if the input is not JSON.

        '''
        '''
        #TASK2 TODO
        This implementation is very close Message.post() method. You can use it
        as reference.

        STEPS:
        * Check that the message exists in the database. Use the method
          g.con.contains_message(messageid)
        * Return status code 404 if the database API call return False.
        * Extracts the native pythonic representation of the request entity body
          using the request.get_json() method
        * From the previous dictionary extracts the value for "title" and
          "body".
          If the values do not exist or the method rises an exception
          the response returns status code 400.
        * You should extract also the value "editor". If does not exist use
          "Anonymous" instead.
        * Call the method g.con.modify_message(message_id,title,body,editor)
        * Return status code 204.

          Remember that the format of the returned value is a tuple with
          the format: body, responsecode, headers.
          - To indicate that a body is empty you must use ''

        '''
        dbHasMessage = g.con.contains_message(messageid)

        if not dbHasMessage:
            raise NotFound()

        title, body, editor = None, None, None

        try:
            data = request.get_json()
            title = data["title"]
            body = data["body"]
            editor = data.get("editor", "Anonymous")
        except Exception as ex:
            abort(400,
                  message="Extracting message data raised an exception".format(
                      str(ex)))

        if not title or not body:
            abort(
                400,
                message=
                "Both title and body of message must not be empty or malformed"
            )
        modifiedMessageId = g.con.modify_message(messageid, title, body,
                                                 editor)

        return '', 204
Exemplo n.º 9
0
def obj_or_404(obj):
    if obj is None:
        raise NotFound()
    return obj
Exemplo n.º 10
0
def get_instance_or_404(uuid):
    instance = STORE.get(uuid)
    if not instance:
        raise NotFound('404 Not Found: SDK server has no such instance %r' % (uuid,))
    return instance
Exemplo n.º 11
0
 def _process_args(self):
     self.error_data = load_error_data(request.view_args['error_id'])
     if self.error_data is None:
         raise NotFound(
             'Error details not found. We might be having some technical issues; please try again later.'
         )
Exemplo n.º 12
0
def _message_post_helper(res_model,
                         res_id,
                         message,
                         token='',
                         _hash=False,
                         pid=False,
                         nosubscribe=True,
                         **kw):
    """ Generic chatter function, allowing to write on *any* object that inherits mail.thread. We
        distinguish 2 cases:
            1/ If a token is specified, all logged in users will be able to write a message regardless
            of access rights; if the user is the public user, the message will be posted under the name
            of the partner_id of the object (or the public user if there is no partner_id on the object).

            2/ If a signed token is specified (`hash`) and also a partner_id (`pid`), all post message will
            be done under the name of the partner_id (as it is signed). This should be used to avoid leaking
            token to all users.

        Required parameters
        :param string res_model: model name of the object
        :param int res_id: id of the object
        :param string message: content of the message

        Optional keywords arguments:
        :param string token: access token if the object's model uses some kind of public access
                             using tokens (usually a uuid4) to bypass access rules
        :param string hash: signed token by a partner if model uses some token field to bypass access right
                            post messages.
        :param string pid: identifier of the res.partner used to sign the hash
        :param bool nosubscribe: set False if you want the partner to be set as follower of the object when posting (default to True)

        The rest of the kwargs are passed on to message_post()
    """
    record = request.env[res_model].browse(res_id)

    # check if user can post with special token/signed token. The "else" will try to post message with the
    # current user access rights (_mail_post_access use case).
    if token or (_hash and pid):
        pid = int(pid) if pid else False
        if _check_special_access(res_model,
                                 res_id,
                                 token=token,
                                 _hash=_hash,
                                 pid=pid):
            record = record.sudo()
        else:
            raise Forbidden()

    # deduce author of message
    author_id = request.env.user.partner_id.id if request.env.user.partner_id else False

    # Token Case: author is document customer (if not logged) or itself even if user has not the access
    if token:
        if request.env.user._is_public():
            # TODO : After adding the pid and sign_token in access_url when send invoice by email, remove this line
            # TODO : Author must be Public User (to rename to 'Anonymous')
            author_id = record.partner_id.id if hasattr(
                record, 'partner_id') and record.partner_id.id else author_id
        else:
            if not author_id:
                raise NotFound()
    # Signed Token Case: author_id is forced
    elif _hash and pid:
        author_id = pid

    email_from = None
    if author_id and 'email_from' not in kw:
        partner = request.env['res.partner'].sudo().browse(author_id)
        email_from = partner.email_formatted if partner.email else None

    message_post_args = dict(body=message,
                             message_type=kw.pop('message_type', "comment"),
                             subtype_xmlid=kw.pop('subtype_xmlid',
                                                  "mail.mt_comment"),
                             author_id=author_id,
                             **kw)

    # This is necessary as mail.message checks the presence
    # of the key to compute its default email from
    if email_from:
        message_post_args['email_from'] = email_from

    return record.with_context(
        mail_create_nosubscribe=nosubscribe).message_post(**message_post_args)
Exemplo n.º 13
0
def send_file(name,
              path_or_fd,
              mimetype,
              last_modified=None,
              no_cache=True,
              inline=None,
              conditional=False,
              safe=True):
    """Sends a file to the user.

    `name` is required and should be the filename visible to the user.
    `path_or_fd` is either the physical path to the file or a file-like object (e.g. a StringIO).
    `mimetype` SHOULD be a proper MIME type such as image/png. It may also be an indico-style file type such as JPG.
    `last_modified` may contain a unix timestamp or datetime object indicating the last modification of the file.
    `no_cache` can be set to False to disable no-cache headers.
    `inline` defaults to true except for certain filetypes like XML and CSV. It SHOULD be set to false only when you
    want to force the user's browser to download the file. Usually it is much nicer if e.g. a PDF file can be displayed
    inline so don't disable it unless really necessary.
    `conditional` is very useful when sending static files such as CSS/JS/images. It will allow the browser to retrieve
    the file only if it has been modified (based on mtime and size).
    `safe` adds some basic security features such a adding a content-security-policy and forcing inline=False for
    text/html mimetypes
    """

    name = secure_filename(name, 'file')
    assert '/' in mimetype
    if inline is None:
        inline = mimetype not in ('text/csv', 'text/xml', 'application/xml')
    if request.user_agent.platform == 'android':
        # Android is just full of fail when it comes to inline content-disposition...
        inline = False
    if _is_office_mimetype(mimetype):
        inline = False
    if safe and mimetype in ('text/html', 'image/svg+xml'):
        inline = False
    try:
        rv = _send_file(path_or_fd,
                        mimetype=mimetype,
                        as_attachment=not inline,
                        attachment_filename=name,
                        conditional=conditional)
    except IOError:
        if not current_app.debug:
            raise
        raise NotFound('File not found: %s' % path_or_fd)
    if safe:
        rv.headers.add('Content-Security-Policy',
                       "script-src 'self'; object-src 'self'")
    if inline:
        # send_file does not add this header if as_attachment is False
        rv.headers.add('Content-Disposition', 'inline', filename=name)
    if last_modified:
        if not isinstance(last_modified, int):
            last_modified = int(time.mktime(last_modified.timetuple()))
        rv.last_modified = last_modified
    if no_cache:
        del rv.expires
        del rv.cache_control.max_age
        rv.cache_control.public = False
        rv.cache_control.private = True
        rv.cache_control.no_cache = True
    return rv
Exemplo n.º 14
0
    def normalize_url(self):
        """Performs URL normalization.

        This uses the :attr:`normalize_url_spec` to check if the URL
        params are what they should be and redirects or fails depending
        on the HTTP method used if it's not the case.

        :return: ``None`` or a redirect response
        """
        if current_app.debug and self.normalize_url_spec is RH.normalize_url_spec:
            # in case of ``class SomeRH(RH, MixinWithNormalization)``
            # the default value from `RH` overwrites the normalization
            # rule from ``MixinWithNormalization``.  this is never what
            # the developer wants so we fail if it happens.  the proper
            # solution is ``class SomeRH(MixinWithNormalization, RH)``
            cls = next((x for x in inspect.getmro(self.__class__)
                        if (x is not RH and x is not self.__class__
                            and hasattr(x, 'normalize_url_spec')
                            and getattr(x, 'normalize_url_spec',
                                        None) is not RH.normalize_url_spec)),
                       None)
            if cls is not None:
                raise Exception(
                    'Normalization rule of {} in {} is overwritten by base RH. Put mixins with class-level '
                    'attributes on the left of the base class'.format(
                        cls, self.__class__))
        if not self.normalize_url_spec or not any(
                self.normalize_url_spec.itervalues()):
            return
        spec = {
            'args': self.normalize_url_spec.get('args', {}),
            'locators': self.normalize_url_spec.get('locators', set()),
            'preserved_args':
            self.normalize_url_spec.get('preserved_args', set()),
            'endpoint': self.normalize_url_spec.get('endpoint', None)
        }
        # Initialize the new view args with preserved arguments (since those would be lost otherwise)
        new_view_args = {
            k: v
            for k, v in request.view_args.iteritems()
            if k in spec['preserved_args']
        }
        # Retrieve the expected values for all simple arguments (if they are currently present)
        for key, getter in spec['args'].iteritems():
            if key in request.view_args:
                new_view_args[key] = getter(self)
        # Retrieve the expected values from locators
        prev_locator_args = {}
        for getter in spec['locators']:
            value = getter(self)
            if value is None:
                raise NotFound(
                    'The URL contains invalid data. Please go to the previous page and refresh it.'
                )
            locator_args = get_locator(value)
            reused_keys = set(locator_args) & prev_locator_args.viewkeys()
            if any(locator_args[k] != prev_locator_args[k]
                   for k in reused_keys):
                raise NotFound(
                    'The URL contains invalid data. Please go to the previous page and refresh it.'
                )
            new_view_args.update(locator_args)
            prev_locator_args.update(locator_args)
        # Get all default values provided by the url map for the endpoint
        defaults = set(
            itertools.chain.from_iterable(
                r.defaults
                for r in current_app.url_map.iter_rules(request.endpoint)
                if r.defaults))

        def _convert(v):
            # some legacy code has numeric ids in the locator data, but still takes
            # string ids in the url rule (usually for confId)
            return unicode(v) if isinstance(v, (int, long)) else v

        provided = {
            k: _convert(v)
            for k, v in request.view_args.iteritems() if k not in defaults
        }
        new_view_args = {
            k: _convert(v)
            for k, v in new_view_args.iteritems() if v is not None
        }
        if new_view_args != provided:
            if request.method in {'GET', 'HEAD'}:
                endpoint = spec['endpoint'] or request.endpoint
                try:
                    return redirect(
                        url_for(
                            endpoint,
                            **dict(request.args.to_dict(), **new_view_args)))
                except BuildError as e:
                    if current_app.debug:
                        raise
                    logger.warn('BuildError during normalization: %s', e)
                    raise NotFound
            else:
                raise NotFound(
                    'The URL contains invalid data. Please go to the previous page and refresh it.'
                )
Exemplo n.º 15
0
 def shop(self, page=0, category=None, search='', ppg=False, **post):
     add_qty = int(post.get('add_qty', 1))
     product_category = request.env['product.public.category']
     if category:
         category = product_category.search([('id', '=', int(category))],
                                            limit=1)
         if not category or not category.can_access_from_current_website():
             raise NotFound()
     else:
         category = product_category
     if ppg:
         try:
             ppg = int(ppg)
             post['ppg'] = ppg
         except ValueError:
             ppg = False
     if not ppg:
         ppg = request.env['website'].get_current_website().shop_ppg or 20
     ppr = request.env['website'].get_current_website().shop_ppr or 4
     attrib_list = request.httprequest.args.getlist('attrib')
     attrib_values = [[int(x) for x in v.split("-")] for v in attrib_list
                      if v]
     attributes_ids = {v[0] for v in attrib_values}
     attrib_set = {v[1] for v in attrib_values}
     if not post.get('order') and not post.get(
             'price_min') and not post.get('price_max'):
         request.session['price_min'] = ''
         request.session['price_max'] = ''
         request.session['order'] = ''
     elif post.get('order') and not post.get('price_min') and not post.get(
             'price_max'):
         request.session['order'] = post.get('order')
     else:
         if post.get('price_min'):
             request.session['price_min'] = post.get('price_min')
             request.session['price_max'] = post.get('price_max')
         if post.get('price_max'):
             request.session['price_min'] = post.get('price_min')
             request.session['price_max'] = post.get('price_max')
     domain = self.new_search_domain(search, category, attrib_values, post)
     keep = QueryURL('/shop',
                     category=category and int(category),
                     search=search,
                     attrib=attrib_list,
                     order=post.get('order'))
     pricelist_context, pricelist = self._get_pricelist_context()
     request.context = dict(request.context,
                            pricelist=pricelist.id,
                            partner=request.env.user.partner_id)
     url = "/shop"
     if search:
         post["search"] = search
     if attrib_list:
         post['attrib'] = attrib_list
     products = request.env['product.template'].with_context(bin_size=True)
     search_product = products.search(domain,
                                      order=self._get_search_order(post))
     website_domain = request.website.website_domain()
     categs_domain = [('parent_id', '=', False)] + website_domain
     if search:
         search_categories = product_category.search(
             [('product_tmpl_ids', 'in', search_product.ids)] +
             website_domain).parents_and_self
         categs_domain.append(('id', 'in', search_categories.ids))
     else:
         search_categories = product_category
     categs = product_category.search(categs_domain)
     if category:
         url = "/shop/category/%s" % slug(category)
     product_count = len(search_product)
     pager = request.website.pager(url=url,
                                   total=product_count,
                                   page=page,
                                   step=ppg,
                                   scope=7,
                                   url_args=post)
     offset = pager['offset']
     products = search_product[offset:offset + ppg]
     product_attribute = request.env['product.attribute']
     if products:
         attributes = product_attribute.search([('product_tmpl_ids', 'in',
                                                 search_product.ids)])
     else:
         attributes = product_attribute.browse(attributes_ids)
     layout_mode = request.session.get('website_sale_shop_layout_mode')
     if not layout_mode:
         if request.website.viewref(
                 'website_sale.products_list_view').active:
             layout_mode = 'list'
         else:
             layout_mode = 'grid'
     values = {
         'search': search,
         'category': category,
         'attrib_values': attrib_values,
         'attrib_set': attrib_set,
         'pager': pager,
         'pricelist': pricelist,
         'add_qty': add_qty,
         'products': products,
         'search_count': product_count,
         'bins': TableCompute().process(products, ppg, ppr),
         'ppg': ppg,
         'ppr': ppr,
         'categories': categs,
         'attributes': attributes,
         'keep': keep,
         'search_categories_ids': search_categories.ids,
         'layout_mode': layout_mode,
         'price_min': request.session.get('price_min') or '',
         'price_max': request.session.get('price_max') or '',
         'order': request.session.get('order') or '',
     }
     if category:
         values['main_object'] = category
     return request.render("website_sale.products", values)
Exemplo n.º 16
0
    def post(self, mine_guid):
        mine = Mine.find_by_mine_guid(mine_guid)
        if not mine:
            raise NotFound('Mine not found')

        data = self.parser.parse_args()

        do_sub_codes = []
        if data['determination_type_code'] == 'DO':
            do_sub_codes = data['dangerous_occurrence_subparagraph_ids']
            if not do_sub_codes:
                raise BadRequest(
                    'Dangerous occurrences require one or more cited sections of HSRC code 1.7.3'
                )

        incident = MineIncident.create(
            mine,
            data['incident_timestamp'],
            data['incident_description'],
            determination_type_code=data['determination_type_code'],
            mine_determination_type_code=data['mine_determination_type_code'],
            mine_determination_representative=data[
                'mine_determination_representative'],
            followup_investigation_type_code=data[
                'followup_investigation_type_code'],
            reported_timestamp=data['reported_timestamp'],
            reported_by_name=data['reported_by_name'],
        )

        incident.reported_by_email = data.get('reported_by_email')
        incident.reported_by_phone_no = data.get('reported_by_phone_no')
        incident.reported_by_phone_ext = data.get('reported_by_phone_ext')
        incident.number_of_fatalities = data.get('number_of_fatalities')
        incident.number_of_injuries = data.get('number_of_injuries')
        incident.emergency_services_called = data.get(
            'emergency_services_called')
        incident.followup_inspection = data.get('followup_inspection')
        incident.followup_inspection_date = data.get(
            'followup_inspection_date')
        incident.status_code = data.get('status_code')
        incident.proponent_incident_no = data.get('proponent_incident_no')

        # lookup and validated inspector party relationships
        tmp_party = Party.query.filter_by(
            party_guid=data.get('reported_to_inspector_party_guid')).first()
        if tmp_party and 'INS' in tmp_party.business_roles_codes:
            incident.reported_to_inspector_party_guid = tmp_party.party_guid
        tmp_party = Party.query.filter_by(
            party_guid=data.get('responsible_inspector_party_guid')).first()
        if tmp_party and 'INS' in tmp_party.business_roles_codes:
            incident.responsible_inspector_party_guid = tmp_party.party_guid
        tmp_party = Party.query.filter_by(
            party_guid=data.get('determination_inspector_party_guid')).first()
        if tmp_party and 'INS' in tmp_party.business_roles_codes:
            incident.determination_inspector_party_guid = tmp_party.party_guid

        incident.determination_type_code = data.get('determination_type_code')
        incident.followup_investigation_type_code = data.get(
            'followup_investigation_type_code')

        for id in do_sub_codes:
            sub = ComplianceArticle.find_by_compliance_article_id(id)
            if not _compliance_article_is_do_subparagraph(sub):
                raise BadRequest(
                    'One of the provided compliance articles is not a sub-paragraph of section 1.7.3 (dangerous occurrences)'
                )
            incident.dangerous_occurrence_subparagraphs.append(sub)

        updated_documents = data.get('updated_documents')
        if updated_documents is not None:
            for updated_file in updated_documents:
                mine_doc = MineDocument(
                    mine_guid=mine.mine_guid,
                    document_name=updated_file['document_name'],
                    document_manager_guid=updated_file['document_manager_guid']
                )

                if not mine_doc:
                    raise BadRequest(
                        'Unable to register uploaded file as document')

                mine_doc.save()
                mine_incident_doc = MineIncidentDocumentXref(
                    mine_document_guid=mine_doc.mine_document_guid,
                    mine_incident_id=incident.mine_incident_id,
                    mine_incident_document_type_code=updated_file[
                        'mine_incident_document_type_code']
                    if updated_file['mine_incident_document_type_code'] else
                    'INI')

                incident.documents.append(mine_incident_doc)

        try:
            incident.save()
        except Exception as e:
            raise InternalServerError(f'Error when saving: {e}')

        recommendations = data.get('recommendations')
        if recommendations is not None:
            for recommendation in recommendations:
                rec_string = recommendation.get('recommendation')
                if rec_string is None:
                    continue
                new_recommendation = MineIncidentRecommendation.create(
                    rec_string, mine_incident_id=incident.mine_incident_id)
                new_recommendation.save()

        return incident, 201
Exemplo n.º 17
0
def profile(viewcode):
    """Patron Profile Page."""
    tab = request.args.get('tab', 'loans')
    allowed_tabs = [
        'loans', 'requests', 'fees', 'history', 'ill_request', 'personal'
    ]
    if tab not in allowed_tabs:
        abort(400)
    patron = Patron.get_patron_by_user(current_user)
    if patron is None:
        raise NotFound()
    if not patron.is_patron:
        abort(403)
    if request.method == 'POST':
        loan = Loan.get_record_by_pid(request.values.get('loan_pid'))
        item = Item.get_record_by_pid(loan.get('item_pid', {}).get('value'))
        if request.form.get('type') == 'cancel':
            tab = 'requests'
            cancel_params = {
                'pid': loan.pid,
                'transaction_location_pid': item.location_pid,
                'transaction_user_pid': patron.pid
            }
            try:
                item.cancel_item_request(**cancel_params)
                flash(
                    _('The request for item %(item_id)s has been canceled.',
                      item_id=item.pid), 'success')
            except Exception:
                flash(
                    _('Error during the cancellation of the request of \
                item %(item_id)s.',
                      item_id=item.pid), 'danger')
        elif request.form.get('type') == 'renew':
            data = {
                'item_pid': item.pid,
                'pid': request.values.get('loan_pid'),
                'transaction_location_pid': item.location_pid,
                'transaction_user_pid': patron.pid
            }
            try:
                item.extend_loan(**data)
                flash(
                    _('The item %(item_id)s has been renewed.',
                      item_id=item.pid), 'success')
            except Exception:
                flash(
                    _('Error during the renewal of the item %(item_id)s.',
                      item_id=item.pid), 'danger')
        return redirect(
            url_for('patrons.profile', viewcode=viewcode) +
            '?tab={0}'.format(tab))

    loans, requests, fees, history, ill_requests = patron_profile(patron)

    # patron messages list
    messages = patron.get_circulation_messages(True)
    if patron.get_pending_subscriptions():
        messages.append({
            'type': 'warning',
            'content': _('You have a pending subscription fee.')
        })
    bootstrap_alert_mapping = {'error': 'danger'}
    for message in messages:
        msg_type = message['type']
        message['type'] = bootstrap_alert_mapping.get(msg_type, msg_type)

    return render_template('rero_ils/patron_profile.html',
                           record=patron,
                           loans=loans,
                           requests=requests,
                           fees=fees,
                           history=history,
                           ill_requests=ill_requests,
                           messages=messages,
                           viewcode=viewcode,
                           tab=tab)
Exemplo n.º 18
0
 def get(self, mine_guid, mine_incident_guid):
     incident = MineIncident.find_by_mine_incident_guid(mine_incident_guid)
     if not incident:
         raise NotFound("Mine Incident not found")
     return incident
Exemplo n.º 19
0
def obj_or_404(obj):
    """Raise a 404 error if the given object is None."""
    if obj is None:
        raise NotFound()
    return obj
Exemplo n.º 20
0
    def put(self, mine_guid, mine_incident_guid):
        incident = MineIncident.find_by_mine_incident_guid(mine_incident_guid)
        if not incident or str(incident.mine_guid) != mine_guid:
            raise NotFound("Mine Incident not found")

        data = self.parser.parse_args()

        do_sub_codes = []
        if data['determination_type_code'] == 'DO':
            do_sub_codes = data['dangerous_occurrence_subparagraph_ids']
            if not do_sub_codes:
                raise BadRequest(
                    'Dangerous occurrences require one or more cited sections of HSRC code 1.7.3'
                )

        for key, value in data.items():
            if key in [
                    'dangerous_occurrence_subparagraph_ids', 'recommendations'
            ]:
                continue
            if key in [
                    'reported_to_inspector_party_guid',
                    'responsible_inspector_party_guid',
                    'determination_inspector_party_guid'
            ]:
                tmp_party = Party.query.filter_by(party_guid=value).first()
                if tmp_party and 'INS' in tmp_party.business_roles_codes:
                    setattr(incident, key, value)
            else:
                setattr(incident, key, value)

        recommendations = data.get('recommendations')
        if recommendations is not None:
            self._handle_recommendations(incident, recommendations)

        incident.dangerous_occurrence_subparagraphs = []
        for id in do_sub_codes:
            sub = ComplianceArticle.find_by_compliance_article_id(id)
            if not _compliance_article_is_do_subparagraph(sub):
                raise BadRequest(
                    'One of the provided compliance articles is not a sub-paragraph of section 1.7.3 (dangerous occurrences)'
                )
            incident.dangerous_occurrence_subparagraphs.append(sub)

        updated_documents = data.get('updated_documents')
        if updated_documents is not None:
            for updated_document in updated_documents:
                if not any(
                        str(doc.document_manager_guid) ==
                        updated_document['document_manager_guid']
                        for doc in incident.documents):
                    mine_doc = MineDocument(
                        mine_guid=mine_guid,
                        document_name=updated_document['document_name'],
                        document_manager_guid=updated_document[
                            'document_manager_guid'])

                    if not mine_doc:
                        raise BadRequest(
                            'Unable to register uploaded file as document')

                    mine_doc.save()
                    mine_incident_doc = MineIncidentDocumentXref(
                        mine_document_guid=mine_doc.mine_document_guid,
                        mine_incident_id=incident.mine_incident_id,
                        mine_incident_document_type_code=updated_document[
                            'mine_incident_document_type_code']
                        if updated_document['mine_incident_document_type_code']
                        else 'INI')

                    incident.documents.append(mine_incident_doc)
                    mine_incident_doc.save()

            for doc in incident.documents:
                if not any(updated_document['document_manager_guid'] == str(
                        doc.document_manager_guid)
                           for updated_document in updated_documents):
                    incident.documents.remove(doc)
                    db.session.delete(doc)
                    db.session.commit()

        incident.save()
        return incident
Exemplo n.º 21
0
 def is_whitelisted(self, method):
     fn = getattr(self, method, None)
     if not fn:
         raise NotFound("Method {0} not found".format(method))
     elif not getattr(fn, "whitelisted", False):
         raise Forbidden("Method {0} not whitelisted".format(method))
Exemplo n.º 22
0
 def get(self, mine_guid):
     mine = Mine.find_by_mine_guid(mine_guid)
     if not mine:
         raise NotFound("Mine not found")
     return mine.mine_incidents
Exemplo n.º 23
0
    def post(self, mine_guid):
        mine = Mine.find_by_mine_guid(mine_guid)
        if not mine:
            raise NotFound('Mine not found.')

        # see if this would be the first TSF
        mine_tsf_list = mine.mine_tailings_storage_facilities
        is_mine_first_tsf = len(mine_tsf_list) == 0

        data = self.parser.parse_args()
        mine_tsf = MineTailingsStorageFacility.create(
            mine,
            mine_tailings_storage_facility_name=data[
                'mine_tailings_storage_facility_name'])
        mine.mine_tailings_storage_facilities.append(mine_tsf)

        if is_mine_first_tsf:
            try:
                req_documents_url = get_documents_svc_url(
                    '/required?category=TSF&sub_category=INI')
                get_tsf_docs_resp = requests.get(
                    req_documents_url,
                    headers={
                        'Authorization': request.headers.get('Authorization')
                    })

                if get_tsf_docs_resp.status_code != 200:
                    raise Exception(
                        f'get_tsf_req_docs returned >> {get_tsf_docs_resp.status_code}'
                    )

                tsf_required_documents = get_tsf_docs_resp.json(
                )['required_documents']
                new_expected_documents = []

                for tsf_req_doc in tsf_required_documents:
                    new_expected_documents.append({
                        'req_document_guid':
                        tsf_req_doc['req_document_guid'],
                        'document_name':
                        tsf_req_doc['req_document_name'],
                        'document_description':
                        tsf_req_doc['description'],
                        'document_due_date_type':
                        tsf_req_doc['req_document_due_date_type'],
                        'document_due_date_period_months':
                        tsf_req_doc['req_document_due_date_period_months'],
                        'hsrc_code':
                        tsf_req_doc['hsrc_code']
                    })

                doc_assignment_response = requests.post(
                    get_documents_svc_url('/expected/mines/' + str(mine_guid)),
                    headers={
                        'Authorization': request.headers.get('Authorization')
                    },
                    json={'documents': new_expected_documents})
                if doc_assignment_response.status_code != 200:
                    raise Exception(
                        f"Error creating tsf expected documents >> {doc_assignment_response}"
                    )
            except Exception as e:
                db.session.rollback()
                current_app.logger.error(str(e))
                raise InternalServerError(str(e) + ", tsf not created")
        mine.save()
        return mine_tsf
Exemplo n.º 24
0
 def bp_registered_test():
     raise NotFound()
Exemplo n.º 25
0
    def create_schedule(self):
        """
        Create a new schedule for a given circuit.

        This service do no check if there are conflicts with another schedule.
        Payload example:
            {
              "circuit_id":"aa:bb:cc",
              "schedule": {
                "date": "2019-08-07T14:52:10.967Z",
                "interval": "string",
                "frequency": "1 * * * *",
                "action": "create"
              }
            }
        """
        log.debug('create_schedule /v2/evc/schedule/')

        json_data = self.json_from_request('create_schedule')
        try:
            circuit_id = json_data['circuit_id']
        except TypeError:
            result = 'The payload should have a dictionary.'
            log.debug('create_schedule result %s %s', result, 400)
            raise BadRequest(result)
        except KeyError:
            result = 'Missing circuit_id.'
            log.debug('create_schedule result %s %s', result, 400)
            raise BadRequest(result)

        try:
            schedule_data = json_data['schedule']
        except KeyError:
            result = 'Missing schedule data.'
            log.debug('create_schedule result %s %s', result, 400)
            raise BadRequest(result)

        # Get EVC from circuits buffer
        circuits = self._get_circuits_buffer()

        # get the circuit
        evc = circuits.get(circuit_id)

        # get the circuit
        if not evc:
            result = f'circuit_id {circuit_id} not found'
            log.debug('create_schedule result %s %s', result, 404)
            raise NotFound(result)
        # Can not modify circuits deleted and archived
        if evc.archived:
            result = f'Circuit {circuit_id} is archived. Update is forbidden.'
            log.debug('create_schedule result %s %s', result, 403)
            raise Forbidden(result)

        # new schedule from dict
        new_schedule = CircuitSchedule.from_dict(schedule_data)

        # If there is no schedule, create the list
        if not evc.circuit_scheduler:
            evc.circuit_scheduler = []

        # Add the new schedule
        evc.circuit_scheduler.append(new_schedule)

        # Add schedule job
        self.sched.add_circuit_job(evc, new_schedule)

        # save circuit to storehouse
        evc.sync()

        result = new_schedule.as_dict()
        status = 201

        log.debug('create_schedule result %s %s', result, status)
        return jsonify(result), status
Exemplo n.º 26
0
    def get(self, party_guid):
        party = Party.find_by_party_guid(party_guid)
        if not party:
            raise NotFound('Party not found')

        return party
Exemplo n.º 27
0
 def on_account_list(self, req):
     accounts = self.backend.list_account()
     if accounts is None:
         return NotFound('No account found')
     return Response(json.dumps(accounts), mimetype='text/json')
Exemplo n.º 28
0
 def get(self, hash):
     room = Room.query.filter_by(hash=hash).first()
     if not room:
         raise NotFound()
     return room
Exemplo n.º 29
0
 def _process_args(self):
     self._blocking = Blocking.get(request.view_args['blocking_id'])
     if not self._blocking:
         raise NotFound('A blocking with this ID does not exist.')
Exemplo n.º 30
0
from pathlib import Path

from werkzeug.exceptions import NotFound
from werkzeug.middleware.shared_data import SharedDataMiddleware
from werkzeug.middleware.dispatcher import DispatcherMiddleware
from werkzeug.wrappers import Request, Response

from api import create_app

frontend = SharedDataMiddleware(
    NotFound(), {
        '/js/': '../frontend/dist/js/',
        '/css/': '../frontend/dist/css/',
        '/img/': '../frontend/dist/img/',
        '/': '../frontend/dist/index.html'
    })

app = DispatcherMiddleware(frontend, {'/api': create_app()})

if __name__ == '__main__':
    from werkzeug.serving import run_simple
    run_simple('127.0.0.1', 5000, app, use_debugger=True, use_reloader=True)