示例#1
0
def register_garbage_can():
    """route: /garbage/register
                POST: Register a company garbage bin
                params:
                    id: company_id, req_id, latitude, longitude, volume
        """
    company_id = str(request.data.get('company_id', ''))
    req_id = str(request.data.get('req_id', ''))
    volume = str(request.data.get('volume', ''))
    latitude = (request.data.get('latitude', ''))
    longitude = str(request.data.get('longitude', ''))

    if len(company_id) > 0 and Company.check_if_exists(company_id):

        can = GarbageCanRequest.objects(req_id=req_id).first()

        if can:
            can.delete()
            Company.add_garbage_can(company_id, req_id, volume, latitude, longitude)
            return common.to_json({}, "Can successfully added", 200)
        else:
            return common.to_json({}, "No such can addition request", 400)

    else:
        return common.to_json({}, "No such company", 400)
示例#2
0
 def __init__(self, name, email, password, contact_number, company_name):
     self.name = name
     self.password = password
     self.email = email
     self.contact_number = contact_number
     self.company = Company(company_name)
     self.public_id = str(uuid.uuid4())
示例#3
0
 def post(self):
     name = self.request.get('name')
     if Company.query(Company.name == name).count() > 0:
         response = {'success': False, 'error_message': "A company already exists with the name {0}".format(name)}
         self.response.write(json.dumps(response))
         return
     new_company = Company.create_company(name)
     _ = CompanyAccount.create_company_account(company=new_company, user_account=self.user_account)
     response = {'success': True, 'goto_url': '/account/company/{0}'.format(new_company.key.id())}
     self.response.write(json.dumps(response))
示例#4
0
 def put(self, company_id):
     company = Company.get_by_id(int(company_id))
     name = self.request.get('name')
     if Company.query(Company.name == name).count() > 0:
         response = {'success': False, 'error_message': "A company already exists with the name {0}".format(name)}
         self.response.write(json.dumps(response))
         return
     company.edit_company(name=name)
     response = {'success': True, 'goto_url': '/account/company/{0}'.format(company.key.id())}
     self.response.write(json.dumps(response))
示例#5
0
文件: vip.py 项目: isaced/ComSay
def comSub():
    name=request.form["name"]
    description=request.form["description"]
    
    if name==None or description==None:
        abort(404)
    
    company=Company(name,description,time.strftime("%Y-%m-%d %T"),None)
    Company.add(company)
    
    return redirect(url_for("vip.index"))
示例#6
0
def update_garbage_can_contents():
    """route: /garbage/update
                    POST: Update existing garbage bin details
                    params:
                         company_id, req_id, latitude, longitude, percentage_filled, predict_full, volume
            """
    company_id = str(request.data.get('company_id', ''))
    req_id = str(request.data.get('req_id', ''))
    percentage_filled = str(request.data.get('percentage_filled', '0.0'))
    latitude = str(request.data.get('latitude', ''))
    longitude = str(request.data.get('longitude', ''))
    volume = str(request.data.get('volume', ''))
    predict_full = str(request.data.get('predict_full', '0'))
    print("check: "+str(Company.check_if_exists(company_id)))
    print("check: "+company_id)
    print(request.data)


    if company_id and req_id and percentage_filled and latitude and longitude and volume and Company.check_if_exists(company_id):
        grbg_status = GarbageStatus()
        grbg_status.company_id = company_id
        grbg_status.garbage_can_id = req_id
        grbg_status.volume = volume
        grbg_status.completion = float(percentage_filled)
        if grbg_status.completion >= 0.8:
            grbg_status.is_full = True
        grbg_status.location = [float(latitude), float(longitude)]
        if predict_full == '1' and grbg_status.completion < 0.8:
            grbg_status.predict_full = True
        else:
            grbg_status.predict_full = False
        grbg_status.save()
        return common.to_json({}, "Can update successfully submitted", 200)
    else:
        return common.to_json({}, "Can update is bad. Check your parameters.", 400)
示例#7
0
    async def render_put(self, request):
        company_id = str(request.data.get('company_id', ''))
        req_id = str(request.data.get('req_id', ''))
        percentage_filled = str(request.data.get('percentage_filled', '0.0'))
        latitude = str(request.data.get('latitude', ''))
        longitude = str(request.data.get('longitude', ''))
        volume = str(request.data.get('volume', ''))
        predict_full = str(request.data.get('predict_full', '0'))
        print("check: " + str(Company.check_if_exists(company_id)))
        print("check: " + company_id)
        print(request.data)

        if company_id and req_id and percentage_filled and latitude and longitude and volume and Company.check_if_exists(
                company_id):
            grbg_status = GarbageStatus()
            grbg_status.company_id = company_id
            grbg_status.garbage_can_id = req_id
            grbg_status.volume = volume
            grbg_status.completion = float(percentage_filled)
            if grbg_status.completion >= 0.8:
                grbg_status.is_full = True
            grbg_status.location = [float(latitude), float(longitude)]
            if predict_full == '1' and grbg_status.completion < 0.8:
                grbg_status.predict_full = True
            else:
                grbg_status.predict_full = False
            grbg_status.save()
        return aiocoap.Message(code=aiocoap.CHANGED, payload=self.content)
示例#8
0
    async def render_put(self, request):
        print('PUT payload: %s' % request.payload)
        company_id = str(request.data.get('company_id', ''))
        req_id = str(request.data.get('req_id', ''))
        volume = str(request.data.get('volume', ''))
        latitude = (request.data.get('latitude', ''))
        longitude = str(request.data.get('longitude', ''))

        if len(company_id) > 0 and Company.check_if_exists(company_id):

            can = GarbageCanRequest.objects(req_id=req_id).first()

            if can:
                can.delete()
                Company.add_garbage_can(company_id, req_id, volume, latitude,
                                        longitude)

        self.set_content(request.payload)
        return aiocoap.Message(code=aiocoap.CHANGED, payload=self.content)
示例#9
0
def get_company(company_id):
    """route: /company/<company_id>
                POST: get company for user,
                 params: name, country, truck_count, truck_volume
        """
    company = Company.get_company(company_id=company_id, public=True)

    if company:
        return common.to_json(company.json_serialize(), "Company edited!", 200)
    else:
        return common.to_json({}, "Company not found!", 400)
示例#10
0
 def post(self):
     company_id = int(self.request.get('company-id'))
     location_kwargs = {
         'company': Company.get_by_id(company_id),
         'name': self.request.get('name'),
         'country': self.request.get('country'),
         'state': self.request.get('state'),
         'city': self.request.get('city'),
         'location_type': self.request.get('location-type'),
         'adult_ads_restricted': bool(int(self.request.get('adult-ads-restricted'))),
         'adult_oriented': bool(int(self.request.get('adult-oriented')))
     }
     new_location = Location.create_location(**location_kwargs)
示例#11
0
 def __generateCompanyDetail(self, result):
     # ossInfo = {}
     # ossInfo['bucket'] = 'sjtender'
     # directory = 'company'
     # res = {}
     # imgInfo = {'imgPathList': []}
     # for result in allResult:
     #     company = result.Company
     #     img = result.ImgPath
     #
     #     res.update(Company.generate(company))
     #     imgInfo['imgPathList'].append(ImgPath.generate(img, ossInfo, directory))
     # res.update(imgInfo)
     res = {}
     res.update(Company.generate(c=result))
     return res
示例#12
0
    def post(self):
        json_data = request.get_json(force=True)
        if not json_data:
            return {'message': 'Input data not provided/not in json'}, 400
        # Validate and deserialize input
        data, errors = company_schema.load(json_data)
        if errors:
            return errors, 422
        company = Company.query.filter_by(symbol=data['symbol']).first()
        if company:
            return {'message': 'Company already exists, try to update'}, 400
        company = Company(json_data)

        db.session.add(company)
        db.session.commit()

        result = company_schema.dump(company).data

        return {"status": 'success', 'data': result}, 201
示例#13
0
 def getCompanyListByIDTuple(self, info):
     foreignIDTuple = info['foreignIDTuple']
     startIndex = info['startIndex']
     pageCount = info['pageCount']
     query = db.session.query(Company).filter(
         Company.companyID.in_(foreignIDTuple)
     )
     info['query'] = query
     query = query.offset(startIndex).limit(pageCount)
     allResult = query.all()
     companyList = [Company.generateBrief(result) for result in allResult]
     countQuery = db.session.query(func.count(Company.companyID)).filter(
         Company.companyID.in_(foreignIDTuple)
     )
     count = countQuery.first()
     count = count[0]
     result = {}
     result['dataList'] = companyList
     result['count'] = count
     return (True, result)
示例#14
0
    def getCompanyList(self, jsonInfo):
        info = json.loads(jsonInfo)
        startIndex = info['startIndex']
        pageCount = info['pageCount']
        # 获取company列表
        try:
            query = db.session.query(Company)
            allResult = query.offset(startIndex).limit(pageCount).all()
            companyList = [Company.generateBrief(result) for result in allResult]
            # count
            countQuery = db.session.query(func.count(Company.companyID))
            count = countQuery.first()
            count = count[0]
            callBackInfo = {}
            callBackInfo['dataList'] = companyList
            callBackInfo['count'] = count
            return (True, callBackInfo)

        except Exception as e:
            print e
            errorInfo = ErrorInfo['TENDER_02']
            errorInfo['detail'] = str(e)
            db.session.rollback()
            return (False, errorInfo)
示例#15
0
    def createCompany(self, jsonInfo):
        info = json.loads(jsonInfo)
        companyName = info['companyName'].replace('\'', '\\\'').replace('\"', '\\\"')
        newArchiveID = info['newArchiveID'].replace('\'', '\\\'').replace('\"', '\\\"')
        registerArea = info['registerArea'].replace('\'', '\\\'').replace('\"', '\\\"')
        companyAreaType = info['companyAreaType'].replace('\'', '\\\'').replace('\"', '\\\"')
        certificateID = info['certificateID'].replace('\'', '\\\'').replace('\"', '\\\"')
        certificationAuthority = info['certificationAuthority'].replace('\'', '\\\'').replace('\"', '\\\"')
        legalRepresentative = info['legalRepresentative'].replace('\'', '\\\'').replace('\"', '\\\"')
        enterprisePrincipal = info['enterprisePrincipal'].replace('\'', '\\\'').replace('\"', '\\\"')
        technologyDirector = info['technologyDirector'].replace('\'', '\\\'').replace('\"', '\\\"')
        remarks = info['remarks'].replace('\'', '\\\'').replace('\"', '\\\"')
        licenseID = info['licenseID'].replace('\'', '\\\'').replace('\"', '\\\"')
        registeredCapital = info['registeredCapital']
        companyType = info['companyType'].replace('\'', '\\\'').replace('\"', '\\\"')
        foundingTime = info['foundingTime']
        businessTermFrom = info['businessTermFrom'].replace('\'', '\\\'').replace('\"', '\\\"')
        safetyProductionPermitID = info['safetyProductionPermitID'].replace('\'', '\\\'').replace('\"', '\\\"')
        safePrincipal = info['safePrincipal'].replace('\'', '\\\'').replace('\"', '\\\"')
        businessScope = info['businessScope'].replace('\'', '\\\'').replace('\"', '\\\"')
        safeAuthority = info['safeAuthority'].replace('\'', '\\\'').replace('\"', '\\\"')
        safeFromDate = info['safeFromDate']
        safeEndDate = info['safeEndDate']
        creditBookID = info['creditBookID'].replace('\'', '\\\'').replace('\"', '\\\"')
        creditScore1 = info['creditScore1']
        creditScore2 = info['creditScore2']
        creditEndDate = info['creditEndDate']
        creditAuthority = info['creditAuthority'].replace('\'', '\\\'').replace('\"', '\\\"')
        creditAddress = info['creditAddress'].replace('\'', '\\\'').replace('\"', '\\\"')
        creditWebSet = info['creditWebSet'].replace('\'', '\\\'').replace('\"', '\\\"')
        creditContact = info['creditContact'].replace('\'', '\\\'').replace('\"', '\\\"')
        creditNjAddress = info['creditNjAddress'].replace('\'', '\\\'').replace('\"', '\\\"')
        creditNjPrincipal = info['creditNjPrincipal'].replace('\'', '\\\'').replace('\"', '\\\"')
        creditNjTech = info['creditNjTech'].replace('\'', '\\\'').replace('\"', '\\\"')
        creditFinancialStaff = info['creditFinancialStaff'].replace('\'', '\\\'').replace('\"', '\\\"')
        companyBrief = info['companyBrief'].replace('\'', '\\\'').replace('\"', '\\\"')


        companyID = self.generateID(companyName)
        (status, reason) = self.doesCompanyExists(info=info)
        if status is True:
            errorInfo = ErrorInfo['TENDER_18']
            errorInfo['detail'] = reason
            return (False, errorInfo)

        if creditScore1 == '':
            creditScore1 = 0

        if creditScore2 == '':
            creditScore2 = 0

        if safeEndDate == '':
            safeEndDate = None

        if safeFromDate == '':
            safeFromDate = None

        if foundingTime == '':
            foundingTime = None

        if businessTermFrom == '':
            businessTermFrom = None

        if creditEndDate == '':
            creditEndDate = None

        company = Company(companyID=companyID, companyName=companyName, newArchiveID=newArchiveID,
                          registerArea=registerArea, companyAreaType=companyAreaType,
                          certificateID=certificateID, certificationAuthority=certificationAuthority,
                          legalRepresentative=legalRepresentative, enterprisePrincipal=enterprisePrincipal,
                          technologyDirector=technologyDirector, remarks=remarks, licenseID=licenseID,
                          registeredCapital=registeredCapital, companyType=companyType, foundingTime=foundingTime,
                          businessTermFrom=businessTermFrom, safetyProductionPermitID=safetyProductionPermitID,
                          safePrincipal=safePrincipal, businessScope=businessScope, safeAuthority=safeAuthority,
                          safeFromDate=safeFromDate, safeEndDate=safeEndDate, creditBookID=creditBookID,
                          creditScore1=creditScore1, creditScore2=creditScore2, creditEndDate=creditEndDate,
                          creditAuthority=creditAuthority, creditAddress=creditAddress, creditWebSet=creditWebSet,
                          creditContact=creditContact, creditNjAddress=creditNjAddress, creditNjPrincipal=creditNjPrincipal,
                          creditNjTech=creditNjTech, creditFinancialStaff=creditFinancialStaff, companyBrief=companyBrief)
        companyAssistant = CompanyAssistant(companyID=companyID, companyName=companyName, foreignCompanyID=companyID)
        try:
            db.session.add(company)
            db.session.add(companyAssistant)
            #添加搜索记录
            searchInfo = {}
            searchInfo['searchName'] = info['companyName']
            searchInfo['foreignID'] = companyID
            searchInfo['tag'] = SEARCH_KEY_TAG_COMPANY
            now = datetime.now()
            searchInfo['createTime'] = str(now)
            searchInfo['joinID'] = self.generateID(info['companyName'])
            SearchKey.createSearchInfo(info=searchInfo)
            db.session.commit()
        except Exception as e:
            # traceback.print_stack()
            db.session.rollback()
            print e
            errorInfo = ErrorInfo['TENDER_02']
            errorInfo['detail'] = str(e)
            return (False, errorInfo)
        return (True, companyID)
示例#16
0
 def get(self, company_id):
     company = Company.get_by_id(int(company_id))
     self.template_values['company'] = company
     self.render_template('account/company/caucus_new_edit.html')
示例#17
0
class User(db.Model):
    """This Class represents the user table"""

    __tablename__ = 'user'

    id = db.Column(db.Integer, primary_key=True)
    public_id = db.Column(db.String(50), unique=True)
    name = db.Column(db.String(255))
    password = db.Column(db.String(255))
    email = db.Column(db.String(255))
    contact_number = db.Column(db.String(255))
    is_individual = db.Column(db.Boolean)
    date_created = db.Column(db.DateTime, default=db.func.current_timestamp())
    date_modified = db.Column(
        db.DateTime, default=db.func.current_timestamp(),
        onupdate=db.func.current_timestamp())
    company_id = db.Column(db.Integer, db.ForeignKey('company.id'))
    company = db.relationship("Company", backref="user", uselist=False) # one to one. child must be defined in parent

    def __init__(self, name, email, password, contact_number, company_name):
        self.name = name
        self.password = password
        self.email = email
        self.contact_number = contact_number
        self.company = Company(company_name)
        self.public_id = str(uuid.uuid4())

# INSTANCE-LEVEL METHODS

    def save(self):
        db.session.add(self)
        db.session.commit()

    def delete(self):
        db.session.delete(self)
        db.session.commit()

# STATIC METHODS

    @staticmethod
    def get_user(user_id):
        """Get a user record by user public id"""
        if id and id != -1:
            return User.query.filter_by(public_id=user_id).first()
        else:
            return User.query.all()

    @staticmethod
    def token_required(f):
        @wraps(f)
        def decorated(*args, **kwargs):
            token = None

            if 'x-access-token' in request.headers:
                token = request.headers['x-access-token']
                token = token[2:-1]  # strip from string chars

            if not token:
                return jsonify({'message': 'Token is missing!'}), 401

            try:
                data = jwt.decode(token, Config.SECRET, algorithms=['HS256'])
                current_user = User.query.filter_by(public_id=data['public_id']).first()
            except Exception as ex:
                print(ex)
                return jsonify({'message': 'Token is invalid!'}), 401

            return f(current_user, *args, **kwargs)

        return decorated

    @staticmethod
    def authorize_by_name(name, password):
        current_user = User.query.filter_by(name=name, password=password).first()

        if current_user:
            return {'token': str(jwt.encode({'public_id': current_user.public_id}, Config.SECRET, algorithm='HS256')),
                    'user': current_user.json_serialize()}

    @staticmethod
    def authorize_by_email(email, password):
        current_user = User.query.filter_by(email=email, password=password).first()

        if current_user:
            return {'token': str(jwt.encode({'public_id': current_user.public_id}, Config.SECRET, algorithm='HS256')),
                    'user': current_user.json_serialize()}

    @staticmethod
    def signup(name, email, password, contact_number, company_name):
        current_user = User.query.filter_by(name=name, email=email).first()

        if current_user is None:
            user = User(name, email, password, contact_number, company_name)
            user.save()

            logged_in= User.query.filter_by(email=email, password=password).first()
            return {'token': str(jwt.encode({'public_id': logged_in.public_id}, Config.SECRET, algorithm='HS256')),
                    'user': logged_in.json_serialize()}

# JSON SERIALIZATION METHODS

    def json_serialize(self):
        return {
            'public_id': self.public_id,
            'name': self.name,
            'email': self.email,
            'contact_number': self.contact_number,
            'type': 'Individual' if self.is_individual else 'Company',
            'company': self.company.json_serialize()
        }
示例#18
0
 def get(self, company_id):
     company = Company.get_by_id(int(company_id))
     self.response.write(company.name)