Exemplo n.º 1
0
def create_tables():
    # delete old records
    Base.metadata.drop_all(engine)
    #
    Base.metadata.create_all(engine)
    #
    for agency in agencies:
        a = Agency(abbreviation=agency, full_name=agencies[agency])
        session.add(a)
        session.commit()
Exemplo n.º 2
0
def signup(username, password) -> Tuple[Agency, Signer_Impl]:
    try:
        signer = create_account(username, password)

        agency = Agency(username = username, password = password)

        contract_addr = deploy_contract("Agency", signer = signer)
        agency.contract_addr = contract_addr
        agency.account_addr = str(signer.keypair.address)
        agency.account_pub = str(signer.keypair.public_key)
        agency.account_priv = str(signer.keypair.private_key)

        privkey, pubkey = gen_rsakey()
        agency.envelope_pub = pubkey
        agency.envelope_priv = privkey

        managementAddr = db.session.query(Contracts).filter(Contracts.name == "Management").first().addr
        EngineerListAddr = db.session.query(Contracts).filter(Contracts.name == "EngineerList").first().addr
        creditAddr = db.session.query(Contracts).filter(Contracts.name == "Credit").first().addr

        call_contract(contract_addr, "Agency", "setEngListAddr", args = [to_checksum_address(EngineerListAddr)], signer = signer)
        call_contract(contract_addr, "Agency", "setCreditAddr", args = [to_checksum_address(creditAddr)], signer = signer)
        agency.engineer_list_addr = EngineerListAddr

        # call_contract2(managementAddr, "Management", "addAgency", 
        #     args = [
        #         username, 
        #         to_checksum_address(agency.account_addr),
        #         to_checksum_address(agency.contract_addr),
        #         agency.envelope_pub, "" ], signer = signer)

    
        call_contract(managementAddr, "Management", "addAgency", 
            args = [
                username, 
                to_checksum_address(agency.account_addr),
                to_checksum_address(agency.contract_addr),
                agency.envelope_pub, ""], signer = signer)

        db.session.add(agency)
        db.session.commit()
    except Exception:
        traceback.print_exc()
        db.session.rollback()
        return None, None
    return agency, signer
Exemplo n.º 3
0
def load_agencies(request, indexfile=""):

    #Open summary excelfile
    wbin = xlrd.open_workbook(indexfile)

    #Agencies
    sh_source = wbin.sheet_by_name(u'Agencies')
    for rownum in range(1, sh_source.nrows):
        row = sh_source.row_values(rownum)
        shortname = row[0]
        fullname = row[1]
        parentname = row[2]
        website = row[3]
        scraped = True
        newagency = Agency(shortname=shortname,
                           name=fullname,
                           parentname=parentname,
                           website=website,
                           notes="",
                           scraped=scraped)
        newagency.save()
    return HttpResponse("Agency details loaded from file.")
Exemplo n.º 4
0
def create(request):
    try:
        json_obj = commonHttp.get_json(request.body)

        req_attrs = [
            expectedAttr["NAME"], expectedAttr["DESCRIPTION"],
            expectedAttr["SMS_CONTACT_NO"]
        ]

        commonHttp.check_keys(json_obj, req_attrs)

        new_agency = Agency(
            name=json_obj[expectedAttr["NAME"]],
            description=json_obj[expectedAttr["DESCRIPTION"]],
            sms_contact_no=json_obj[expectedAttr["SMS_CONTACT_NO"]])

        commonHttp.save_model_obj(new_agency)

        response = JsonResponse({"id": new_agency.id, "success": True})

        return response

    except commonHttp.HttpBadRequestException as e:
        return HttpResponseBadRequest(e.reason_phrase)
Exemplo n.º 5
0
def load_indicator_spreadsheet(request, indexfile=""):

    #Open summary excelfile
    wbin = xlrd.open_workbook(indexfile)

    #Agencies
    sh_source = wbin.sheet_by_name(u'Agencies')
    for rownum in range(1, sh_source.nrows):
        row = sh_source.row_values(rownum)
        shortname = row[0]
        fullname = row[1]
        parentname = row[2]
        website = row[3]
        scraped = True
        newagency = Agency(shortname=shortname,
                           name=fullname,
                           parentname=parentname,
                           website=website,
                           notes="",
                           scraped=scraped)
        newagency.save()

    #Datasources
    sh_source = wbin.sheet_by_name(u'Datasources Used')
    for rownum in range(1, sh_source.nrows):
        row = sh_source.row_values(rownum)
        shortname = row[0]
        fullname = row[1]
        sourceagency = row[2]
        sourcefile = row[5]
        sourceurl = row[7]
        #FIXIT: should be the times when scrapers were run, not the date the file
        #was uploaded
        todaysdate = datetime.now()
        newsource = Datasource(shortname=shortname,
                               name=fullname,
                               notes="",
                               url=sourceurl,
                               dateadded=todaysdate,
                               datechecked=todaysdate,
                               scraper=True,
                               localfile=sourcefile)
        newsource.save()

    sh_source = wbin.sheet_by_name(u'Suggested Sources')
    for rownum in range(1, sh_source.nrows):
        row = sh_source.row_values(rownum)
        shortname = row[0]
        fullname = row[1]
        sourceagency = row[2]
        sourceurl = row[3]
        newsource = Datasource(shortname=shortname,
                               name=fullname,
                               notes="",
                               url=sourceurl,
                               dateadded=todaysdate,
                               datechecked=todaysdate,
                               scraper=False,
                               localfile="")
        newsource.save()

    #Indicators
    indicators = {}
    sh_ind = wbin.sheet_by_name(u'Indicators Needed')
    for rownum in range(1, sh_ind.nrows):
        row = sh_ind.row_values(rownum)
        indcode = row[0]
        indname = row[1]
        indicators[indcode] = indname
##        newindicator = Indicator()
##        newindicator.save()

#Indicators in sources
    found = {}
    sh_found = wbin.sheet_by_name(u'Indicators Found')
    for rownum in range(1, sh_found.nrows):
        row = sh_found.row_values(rownum)
        sourcecode = row[0]
        indcode = row[1]
        csvheading = row[4]
        #Only process indicators that we have data for
        if not (csvheading == ""):
            if not (found.has_key(sourcecode)):
                found[sourcecode] = {}
            found[sourcecode][csvheading] = indcode
##        newfound = foundIndicator(indicator=, datasource=,
##                                  csvfile=, csvindname=,
##                                  datasourceindname=,
##                                  datasourcedesc=, notes=)
##        newfound.save()

    return HttpResponse("Indicator details loaded from file.")
Exemplo n.º 6
0
def construct_Agency():
   agency_list =  [Agency(name = u_agency) for u_agency in list(set([row['agency'] for index, row in complete_data2.iterrows()]))]
   db.session.add_all(agency_list)
   db.session.commit()
Exemplo n.º 7
0
def employeeAgencyController(action=None, resourceId=None):

    #keep non-logged users outside

    if ('employee' not in session) or (session['employee']['superAdmin']
                                       is not True):
        return redirect(url_for('backoffice_auth'))

    #check resourceId validity
    agencyData = None

    if resourceId is not None:
        if ObjectId.is_valid(str(resourceId)):
            agencyData = Agency.objects(id=ObjectId(str(resourceId))).first()
            if not agencyData:
                return render_template(
                    '404.html', errorString="This Agency does not exist")
        else:
            return render_template('404.html',
                                   errorString="This AgencyID is not valid")

    errorString = ''
    agencyList = []
    validationErrors = []
    pageTitle = ""

    #switch action cases (add,edit,delete,list)

    if action == 'add' or action == 'edit':

        pageTitle = "Add Agency" if action == "add" else "Edit Agency"
        templatePath = 'agencies/add.html'

        if request.method == 'POST' and ('submit' in request.form):
            #validate username

            if 'email' in request.form:
                if not request.form['email']:
                    validationErrors.append("Field email is empty")
                else:
                    if not request.form['email'].find("@"):
                        validationErrors.append(
                            "Email field should contain at least one @")
                    if action == 'add':
                        if len(Agency.objects(
                                email=request.form['email'])) > 0:
                            validationErrors.append(
                                "The email you've choose already exists")
                    else:
                        if len(
                                Agency.objects(
                                    email=request.form['email'],
                                    email__ne=agencyData.email)) > 0:
                            validationErrors.append(
                                "The email you've choose already exists")
            else:
                validationErrors.append("Missing field email in request")

            #validate companyName
            if 'companyName' in request.form:
                if not request.form['companyName']:
                    validationErrors.append("Field companyName is empty")
            else:
                validationErrors.append("Missing field companyName in request")

            #validate phone
            if 'phone' in request.form:
                if not request.form['phone']:
                    validationErrors.append("Field phone is empty")
            else:
                validationErrors.append("Missing field phone in request")

            #validate phone
            if 'VAT' in request.form:
                if not request.form['VAT']:
                    validationErrors.append("Field VAT is empty")
            else:
                validationErrors.append("Missing field VAT in request")

            city = ''
            district = ''
            address = ''

            if 'city' in request.form:
                city = request.form['city']
            if 'district' in request.form:
                district = request.form['district']
            if 'address' in request.form:
                address = request.form['address']

            #validate password

            if 'password' in request.form:
                if not request.form['password']:
                    if (action == 'edit'):
                        hash = agencyData.password  #keep old password
                    else:
                        validationErrors.append("Field password is empty")
                else:
                    if len(request.form['password']) < 8:
                        validationErrors.append(
                            "Password field should be min. 8 chars")
                    else:
                        hash = hashlib.sha256(request.form['password'].encode(
                        )).hexdigest().upper()  #make new hash
            else:
                validationErrors.append("Missing field password in request")

            #validate active

            if len(validationErrors) == 0:
                #save

                if action == 'add':
                    result = Agency(
                        companyName=str(request.form['companyName']),
                        city=str(city),
                        district=str(district),
                        address=str(address),
                        email=str(request.form['email']),
                        phone=str(request.form['phone']),
                        profitRate=float(request.form['profitRate']),
                        VAT=str(request.form['VAT']),
                        password=hash,
                        active=(True if int(request.form['active']) == 1 else
                                False)).save()
                    if result:
                        lastAgency = Agency.objects(
                            email=request.form['email']).first()
                        return redirect(
                            url_for('agencies',
                                    action='edit',
                                    resourceId=lastAgency.id))
                    else:
                        validationErrors.append("Unable to write this record")

                else:
                    result = Agency.objects(email=agencyData['email']).update(
                        companyName=str(request.form['companyName']),
                        city=str(city),
                        district=str(district),
                        address=str(address),
                        email=str(request.form['email']),
                        phone=str(request.form['phone']),
                        profitRate=float(request.form['profitRate']),
                        VAT=str(request.form['VAT']),
                        password=hash,
                        active=(True if int(request.form['active']) == 1 else
                                False))
                    return redirect(
                        url_for('agencies',
                                action='edit',
                                resourceId=resourceId))

            else:
                errorString = '|'.join(validationErrors)

    elif action == 'delete':
        pageTitle = "Agencies"
        templatePath = 'agencies/list.html'
        Agency.objects(id=ObjectId(str(resourceId))).delete()
        agencyList = Agency.objects().order_by('companyName')

    else:
        pageTitle = "Agencies"
        templatePath = 'agencies/list.html'
        agencyList = Agency.objects().order_by('companyName')

    return render_template(templatePath,
                           pageTitle=pageTitle,
                           employee=session['employee'],
                           userType='employee',
                           errorString=errorString,
                           agencyList=agencyList,
                           agencyData=agencyData,
                           action=action,
                           resourceId=resourceId)