示例#1
0
    def post(self):
        if g.current_role in schemas.schedule:
            validate_schema(g.body, schemas.schedule[g.current_role])

        schedule = self.model()
        schedule.patch(g.body)

        if 'copy_params' in g.body and g.body['copy_params']:
            # Copy tests and other info from old schedule
            print(g.body['copy_params'])
            copy_schedule = Schedule.query.filter_by(
                date=g.body['copy_params']).first()
            if copy_schedule:
                print(copy_schedule)
                schedule.timeofday = copy_schedule.timeofday
                schedule.starttime = copy_schedule.starttime
                schedule.endtime = copy_schedule.endtime
                schedule.typeofactivity = copy_schedule.typeofactivity
                schedule.release_number = copy_schedule.release_number
                schedule.frequency_association = copy_schedule.frequency_association
                schedule.test_ids = copy_schedule.test_ids
                schedule.tests = copy_schedule.tests
                schedule.schedule_well_tests = copy_schedule.schedule_well_tests
                schedule.gauged_wells = copy_schedule.gauged_wells
                schedule.skipped_wells = copy_schedule.skipped_wells

        schedule.save_or_error()

        res = schedule.json()
        return jsonify(res)
示例#2
0
def reset():
    validate_schema(g.body, schemas.reset)

    if 'email' in g.body:
        user = User.query.filter_by(lab=g.current_lab,
                                    email=g.body['email']).first()

        if user:
            user.reset_code = id_generator()
            user.save_or_error()

            reset_password(user)

            return jsonify(success=True)
    elif 'reset_code' in g.body and 'password' in g.body:
        user = User.query.filter_by(lab=g.current_lab,
                                    reset_code=g.body['reset_code']).first()

        if user:
            user.reset_code = None
            user.password = bcrypt.generate_password_hash(g.body['password'])
            user.save_or_error()
            login_user(user)
            return jsonify(success=True)

    return jsonify(success=False)
示例#3
0
def signin():
    validate_schema(g.body, schemas.signin)

    user = User.query.filter_by(lab=g.current_lab,
                                email=g.body['email']).first()
    if user and bcrypt.check_password_hash(user.password, g.body['password']):
        login_user(user)
        return jsonify(success=True)

    return jsonify(success=False)
示例#4
0
    def patch(self, id):
        validate_schema(g.body, schemas.patch_site)

        site = self.model.query.get(id)
        site.patch(g.body)

        if 'state_id' in g.body:
            state = State.query.get(g.body['state_id'])
            site.state = state.title

        site.save_or_error()
        res = site.json()
        return jsonify(res)
示例#5
0
    def patch(self, id):
        if g.current_role not in ['Admin', 'Anonymous'
                                  ] and current_user.id == id:
            g.current_role = 'Own'

        print("g.current_role", g.current_role)
        if g.current_role in schemas.user:
            validate_schema(g.body, schemas.user[g.current_role])

        user = self.model.role_query.filter_by(id=id).first_or_404()

        if 'email' in g.body and g.body['email'] != user.email:
            if self.model.query.filter_by(lab=g.current_lab,
                                          email=g.body['email']).first():
                # Raise error if email already exist
                raise IntegrityError(
                    'email', message="Email already exists for this lab")
            if not user.active and current_user.id != user.id:
                # User is not active and email is changing, lets send them a new invite
                # Make sure current_user is authorized:
                if g.current_role not in ['Admin', 'LabAdmin', 'LabAssociate']:
                    abort(httplib.UNAUTHORIZED)
                user.invitee = current_user
                invite_user(user=user)

        # If the user is a company admin, create the first client.
        if user.role_id == 4:
            company = user.companies.first()
            # Check to see if there are any clients
            if not Client.query.filter_by(company_id=company.id).count():
                client = Client(company_id=company.id, name="My Client")
                client.save_or_error()

        user.patch(g.body)

        if 'password' in g.body:
            user.password = bcrypt.generate_password_hash(g.body['password'])
            user.pending = False
            user.active = True
            # Trigger accepted invitiation email
            accepted_invite(user=user)

        if 'active' in g.body and g.body['active']:
            # User is getting patched to Active, lets make sure the password is set
            if not user.password:
                abort(httplib.UNAUTHORIZED)

        user.save_or_error()
        res = user.json()
        return jsonify(res)
示例#6
0
    def patch(self, id):
        if g.current_role not in ['Admin', 'Anonymous'
                                  ] and current_user.id == id:
            g.current_role = 'Own'

        if g.current_role in schemas.schedule:
            validate_schema(g.body, schemas.schedule[g.current_role])

        schedule = self.model.query.get(id)
        schedule.patch(g.body)
        schedule.save_or_error()

        res = schedule.json()
        return jsonify(res)
示例#7
0
def download_analytical_boxmap(lab_id):
    r = request.json
    # Ensure the URL was posted
    post_schema = {
        "$schema": schema,
        "type": "object",
        "properties": {
            "url": string,
        },
        "required": [
            "url",
        ]
    }
    validate_schema(r, post_schema)

    return jsonify(dict(ok=True))
示例#8
0
    def post(self):
        validate_schema(g.body, schemas.post_site)

        site = self.model()
        site.patch(g.body)

        if 'state_id' in g.body:
            state = State.query.get(g.body['state_id'])
            site.state = state.title

        # Client is required
        client = Client.query.filter_by(id=g.body['client_id']).first()
        if not client:
            raise IntegrityError(dict(client="Client not found"))
        site.company_id = client.company_id
        site.lab_id = g.current_lab.id

        site.save_or_error()
        res = site.json()

        return jsonify(res)
示例#9
0
def get_well_data(lab_id):
    r = request.json
    post_schema = {
        "$schema": schema,
        "properties": {
            "date_collected": date,
            "date_collected_range_end": date,
            "site_id": integer,
            "sitemap_id": integer,
            "substance_ids": array,
        },
        "required":
        ["date_collected", "site_id", "sitemap_id", "substance_ids"]
    }
    validate_schema(r, post_schema)

    # convert to ints for the lookup function
    date_collected = r['date_collected']
    date_collected_range_end = r[
        'date_collected_range_end'] if 'date_collected_range_end' in r else None
    site_id = r['site_id']
    site_map_id = r['sitemap_id']
    substance_ids = r['substance_ids']

    # if type(r.get('substance_ids')) is list:
    #     substance_ids = [int(substance_id) for substance_id in r.get('substance')]
    # else:
    #     substance_ids = [-1]

    # fetch the well results from the wellSubstanceDataBySite function
    well_results = wellSubstanceDataBySite(
        site_id=site_id,
        site_map_id=site_map_id,
        date_collected=date_collected,
        substance_ids=substance_ids,
        date_collected_range_end=date_collected_range_end)

    # return json to updateMarks ajax javascript function
    return jsonify(well_results)
示例#10
0
    def post(self):
        # Validate the company
        if g.current_role in schemas.company:
            validate_schema(g.body, schemas.company[g.current_role])

        if self.model.query.filter_by(lab_id=g.current_lab.id,
                                      title=g.body['title']).first():
            raise IntegrityError('title',
                                 message="This company already exists.")

        company = self.model()
        company.patch(g.body)

        # Check to see if a primary_user object has been passed
        if 'primary_user' in g.body:
            # Validate the user
            if g.current_role in schemas.user:
                validate_schema(g.body['primary_user'],
                                schemas.user[g.current_role])
            # Check for existing user email
            if User.query.filter_by(
                    lab=g.current_lab,
                    email=g.body['primary_user']['email']).first():
                raise IntegrityError('email')

            # Everything has passed, save the user and the company together
            user = User()
            user.patch(g.body['primary_user'])
            user.invitee = current_user
            user.invite_code = id_generator()
            company.users.append(user)
            # Send the user invitation
            invite_user(user=user)

        company.save_or_error()
        res = company.json()
        return jsonify(res)
示例#11
0
    def post(self):
        """POST /model

        Creates a new object of model, returning it as JSON with an `id` key.
        """
        if hasattr(self, 'post_roles'):
            if current_user.is_anonymous or not current_user.role:
                abort(httplib.UNAUTHORIZED)
            if current_user.role.name not in self.post_roles:
                abort(httplib.UNAUTHORIZED)

        r = request.json
        post_schema = {
            "$schema": schema,
            "properties": {
                "site_id": integer,
                "active": boolean,
                "title": string,
                "top_of_casing": number,
                "xpos": integer,
                "ypos": integer,
                "xpos_fields": integer,
                "ypos_fields": integer,
            },
            "required": [
                "site_id",
                "title",
            ]
        }
        validate_schema(r, post_schema)

        instance = self.model()
        instance.patch(g.body)
        instance.save_or_error()
        res = instance.json()
        return jsonify(res)
 def test_invalid_length(self):
     invalid = {'email': '*****@*****.**', 'password': '******'}
     with self.assertRaises(UnprocessableEntity):
         validate_schema(invalid, users_schemas.signup)
 def test_invalid_email(self):
     invalid = {'email': 'guat', 'password': '******'}
     with self.assertRaises(UnprocessableEntity):
         validate_schema(invalid, users_schemas.signup)
 def test_valid_signin(self):
     valid = {'email': '*****@*****.**', 'password': '******'}
     validate_schema(valid, users_schemas.signin)
示例#15
0
    def post(self):
        if g.current_role in schemas.user:
            validate_schema(g.body, schemas.user[g.current_role])

        if 'email' not in g.body or not g.body['email'].strip():
            print("The issue is here")
            raise UnprocessableEntity('Invalid email')

        existing_user = self.model.query.filter_by(
            lab=g.current_lab, email=g.body['email']).first()
        if existing_user:
            # User already exists, add the permissions to their existing account
            # User cannot change roles, they cannot be a CompanyAdmin on one company but a CompanyAssociate on another.
            # They cannot be a CompanyAdmin and a ClientManager
            # The cannot be on multiple companies
            # This is because the role_id is set on the user object, and the role is used to determine whether to show LabApp, CompanyApp, ClientApp, or Siteapp.
            # A ClientManager can have many clients, a Technician can have many sites

            # Make sure the role_id matches the user's current role
            if 'role_id' in g.body and existing_user.role.id != g.body[
                    'role_id']:
                raise BadInvite('User role cannot be changed from %s' %
                                existing_user.role.name)

            # User cannot currently belong to more than one company, so let's just give the invitee a nice error message
            if 'companies' in g.body:
                for company_id in g.body['companies']['add']:
                    if company_id in existing_user.company_ids:
                        raise BadInvite(
                            'Email already exists with this company.')
                    else:
                        raise BadInvite(
                            'Email is already associated with another company.'
                        )

            # Add clients to a ClientManager
            if 'clients' in g.body:
                for client_id in g.body['clients']['add']:
                    if existing_user.clients.filter_by(id=client_id).count():
                        raise BadInvite(
                            'Email is already associated with this client.')
                    else:
                        existing_user.patch(g.body)
                        existing_user.save_or_error()
                        res = existing_user.json()
                        return jsonify(res)

            # Add sites to a Technician
            if 'sites' in g.body:
                for site_id in g.body['sites']['add']:
                    if existing_user.sites.filter_by(id=site_id).count():
                        raise BadInvite(
                            'Email is already associated with this site.')
                    else:
                        existing_user.patch(g.body)
                        existing_user.save_or_error()
                        res = existing_user.json()
                        return jsonify(res)

            # Catchall Integrity Error
            raise IntegrityError('email')

        user = self.model()
        user.patch(g.body)

        # Check if sampleserve admin, override the role.
        if current_user.role_id != 1:
            user.lab = g.current_lab

        if 'password' in g.body:
            user.password = bcrypt.generate_password_hash(g.body['password'])
            user.pending = False
            user.active = True  # switch to false once email confirmation is working
            user.save_or_error()
            res = user.json()
            return jsonify(res)

        if current_user.is_anonymous:
            abort(httplib.UNAUTHORIZED)

        user.invitee = current_user
        user.pending = True
        user.active = False
        user.invite_code = id_generator()
        user.save_or_error()

        # Send email invite to the user
        invite_user(user=user)

        res = user.json()
        return jsonify(res)
示例#16
0
def create_contours(lab_id):
    r = request.json
    post_schema = {
        "$schema":
        schema,
        "type":
        "object",
        "properties": {
            "site_id": integer,
            "sitemap_id": integer,
            "date_collected": date,
            "substance_ids": array,
            "date_collected_range_end": date,
            "wells": {
                "type":
                "array",
                "items": [{
                    "type":
                    "object",
                    "properties": {
                        "well_id": integer,
                        "xpos": number,
                        "ypos": number,
                        "substance_sum": number,
                    },
                    "required": [
                        "well_id",
                        "xpos",
                        "ypos",
                        "substance_sum",
                    ]
                }]
            },
            "title_wildcard": string,
            "label_over_well": boolean,
            "crop_contours": boolean,
            "groundwater_contours": boolean,
            "flow_lines": boolean,
            "site_image_alpha": number,
            "remove_zero_contour": boolean,
            "logarithmic_contours": boolean,
            "heatmap": boolean,
        },
        "required": [
            "site_id",
            "sitemap_id",
            "date_collected",
            "substance_ids",
            "wells",
        ]
    }
    validate_schema(r, post_schema)
    pprint(r)
    # return jsonify(dict(ok=True))
    site_map = SiteMap.query.get(r['sitemap_id'])
    site = site_map.site
    image = loadImage(site_map_id=site_map.id,
                      url=site_map.url,
                      target_width=site_map.width,
                      target_height=site_map.height)
    pprint(image)

    resp = generateContours(
        date_collected=r['date_collected'],
        substance_name=getSubstanceNames(r['substance_ids']),
        well_arr=r['wells'],
        site_title=site.title,
        site_map=site_map,
        image=image,
        date_collected_range_end=r['date_collected_range_end']
        if 'date_collected_range_end' in r else False,
        title_wildcard=r['title_wildcard'] if 'title_wildcard' in r else '',
        label_over_well=True
        if 'label_over_well' in r and r['label_over_well'] is True else False,
        crop_contours=True
        if 'crop_contours' in r and r['crop_contours'] is True else False,
        groundwater_contours=True if 'groundwater_contours' in r
        and r['groundwater_contours'] is True else False,
        flow_lines=True
        if 'flow_lines' in r and r['flow_lines'] is True else False,
        site_image_alpha=r['site_image_alpha']
        if 'site_image_alpha' in r else 0.5,
        remove_zero_contour=True if 'remove_zero_contour' in r
        and r['remove_zero_contour'] is True else False,
        logarithmic_contours=True if 'contour_type' in r
        and r['contour_type'] == 'logarithmic' else False,
        heatmap=True if 'heatmap' in r and r['heatmap'] is True else False,
    )
    pprint(resp)
    return jsonify(resp)
 def test_valid_email(self):
     invalid = {'email': '*****@*****.**', 'password': '******'}
     validate_schema(invalid, users_schemas.signup)
示例#18
0
def preview_analytical_tables(lab_id):
    if request.method == "GET":
        # Convert these params to JSON
        r = dict(
            criteria_id=int(request.args.get('criteria_id')),
            site_id=int(request.args.get('site_id')),
            date_collected=request.args.get('date_collected'),
            substance_ids=json.loads(
                request.args.get('substance_ids').replace('List ', '')),
        )
        if request.args.get('date_collected_range_end'):
            r['date_collected_range_end'] = request.args.get(
                'date_collected_range_end')
        pprint(r)
    else:
        r = request.json

    # Validate the input
    post_schema = {
        "$schema": schema,
        "type": "object",
        "properties": {
            "criteria_id": integer,
            "site_id": integer,
            "date_collected": date,
            "substance_ids": array,
            "date_collected_range_end": date,
        },
        "required": [
            "site_id",
            "date_collected",
            "substance_ids",
        ]
    }
    validate_schema(r, post_schema)

    # Validated, lets get the data needed to make the report
    date_collected = r['date_collected']
    date_collected_range_end = r[
        'date_collected_range_end'] if 'date_collected_range_end' in r else None
    site_id = r['site_id']
    substance_ids = r['substance_ids']
    criteria_id = r['criteria_id']

    # fetch the well results from the getBoxmapData function
    well_results = getAnalyticalData(
        site_id=site_id,
        date_collected=date_collected,
        substance_ids=substance_ids,
        date_collected_range_end=date_collected_range_end,
        criteria_id=criteria_id,
    )

    site = Site.query.get_or_404(site_id)
    substances = []
    for substance_id in substance_ids:
        substance = Substance.query.get(substance_id)
        substances.append(substance)
    if criteria_id:
        criteria = Criteria.query.get(criteria_id)
    else:
        criteria = None

    html = render_template('/reports/analytical-tables.html',
                           site=site,
                           date_collected=date_collected,
                           substance_ids=substance_ids,
                           substances=substances,
                           date_collected_range_end=date_collected_range_end,
                           criteria=criteria,
                           well_results=well_results)

    if request.method == "POST":
        # Return a file
        filename = slugify(site.title) + "-analytical-tables-" + str(
            int(time.time())) + ".pdf"
        pdf_details = create_pdf_from_document_content(document_content=html,
                                                       filename=filename)
        return jsonify(
            dict(path="/static/reports/" + pdf_details['filename'],
                 filename=pdf_details['filename']))
    # Just return the preview
    return html
 def test_invalid_multiple_additional_keys(self):
     invalid = {'password': '******', 'active': True, 'test': True}
     with self.assertRaises(UnprocessableEntity):
         validate_schema(invalid, users_schemas.signup)
示例#20
0
def preview_analytical_boxmap(lab_id):
    if request.method == "GET":
        # Convert these params to JSON
        r = dict(
            criteria_id=int(request.args.get('criteria_id')),
            site_id=int(request.args.get('site_id')),
            sitemap_id=int(request.args.get('sitemap_id')),
            date_collected=request.args.get('date_collected'),
            substance_ids=json.loads(
                request.args.get('substance_ids').replace('List ', '')),
        )
        if request.args.get('date_collected_range_end'):
            r['date_collected_range_end'] = request.args.get(
                'date_collected_range_end')
        pprint(r)
    else:
        r = request.json

    # Validate the input
    post_schema = {
        "$schema": schema,
        "type": "object",
        "properties": {
            "criteria_id": integer,
            "site_id": integer,
            "sitemap_id": integer,
            "date_collected": date,
            "substance_ids": array,
            "date_collected_range_end": date,
        },
        "required": [
            "site_id",
            "sitemap_id",
            "date_collected",
            "substance_ids",
        ]
    }
    validate_schema(r, post_schema)

    # Validated, lets get the data needed to make the report
    date_collected = r['date_collected']
    date_collected_range_end = r[
        'date_collected_range_end'] if 'date_collected_range_end' in r else None
    site_id = r['site_id']
    site_map_id = r['sitemap_id']
    substance_ids = r['substance_ids']
    criteria_id = r['criteria_id']

    # fetch the well results from the getBoxmapData function
    well_results = getBoxmapData(
        site_id=site_id,
        site_map_id=site_map_id,
        date_collected=date_collected,
        substance_ids=substance_ids,
        date_collected_range_end=date_collected_range_end,
        criteria_id=criteria_id,
    )

    site = Site.query.get_or_404(site_id)
    sitemap = SiteMap.query.get_or_404(site_map_id)
    substances = []
    for substance_id in substance_ids:
        substance = Substance.query.get(substance_id)
        substances.append(substance)

    # get all the data required by aj's clipping detection script
    site_map = SiteMap.query.get(site_map_id)
    box = calculateBoxDimensions(
        substances=substances,
        num_sample_dates=well_results['num_sample_dates'])
    sm_wells = SiteMapWell.query.filter_by(site_map_id=site_map_id).all()
    if criteria_id:
        criteria = Criteria.query.get(criteria_id)
    else:
        criteria = None

    # If not all the wells have xpos_fields and ypos_fields set, lets use the algo to place them automatically.
    if not hasLocations(sm_wells):
        autoPlaceBoxes(site_map=site_map, box=box, sm_wells=sm_wells)
        # We need to refresh the well_results as well
        well_results = getBoxmapData(
            site_id=site_id,
            site_map_id=site_map_id,
            date_collected=date_collected,
            substance_ids=substance_ids,
            date_collected_range_end=date_collected_range_end,
            criteria_id=criteria_id,
        )

    html = render_template('/reports/analytical-boxmap.html',
                           site=site,
                           sitemap=sitemap,
                           date_collected=date_collected,
                           substance_ids=substance_ids,
                           substances=substances,
                           box=box,
                           date_collected_range_end=date_collected_range_end,
                           criteria=criteria,
                           well_results=well_results)

    if request.method == "POST":
        # Return a file
        filename = slugify(site.title) + str(int(time.time())) + ".pdf"
        pdf_details = create_pdf_from_document_content(document_content=html,
                                                       filename=filename)
        return jsonify(
            dict(path="/static/reports/" + pdf_details['filename'],
                 filename=pdf_details['filename']))
        # return make_response(send_file(
        #     os.path.join('frontend/static/reports', pdf_details['filename']), mimetype='application/pdf', as_attachment=True, attachment_filename=filename))

    # Just return the preview
    return html