Exemplo n.º 1
0
def user_register():
    form = RegisterForm(request.form)
    if request.method == 'POST' and form.validate():
        user = User()
        user.set_attrs(form.data)
        user.updatetime = time.strftime('%Y-%m-%d %H:%M:%S',
                                        time.localtime(
                                            (time.time())))  # 修改数据更新时间

        # 判断是否已经存在该公司,如不存在,则创建该公司的公司管理员账户,并创建相应数据表
        # 如果存在,则只能创建公司普通人员账户,不创建数据表
        if user.authority == 'com_person':
            db.session.add(user)
            db.session.commit()
        else:
            # 公司不存在,且注册时选择了公司管理员,则允许创建用户,并创建相关数据表
            company = Company()
            company.set_attrs(form.data)
            company.company_number = "%03d" % (Company.query.count() + 1)
            db.session.add(company)
            db.session.add(user)
            db.session.commit()
            # 创建报告保存文件夹,根据公司编号创建,如超级管理员为001,则文件夹名为001
            os.makedirs(
                os.path.join(current_app.config['DOCXFILE_DIR'],
                             company.company_number))
        return render_template('user/userRegister.html',
                               messages={'message': ['注册成功!']})
    else:
        return render_template('user/userRegister.html', messages=form.errors)
Exemplo n.º 2
0
def create_company(*, account: Account, name: str, website: str,
                   specialties: list, **kwargs) -> Company:
    company_account_check(account)
    if company_exist(account.id, raise_exception=False):
        raise InvalidInputFormat(
            "Account {} already has a company account.".format(account.id))
    c = Company(account=account, name=name, website=website, **kwargs)
    c.save()
    c.specialties.add(*specialties)
    return c
Exemplo n.º 3
0
def add_admin_user():
    admin_user = User()
    admin_user.email = '*****@*****.**'
    admin_user.password = '******'
    admin_user.company = 'nbtjy'
    admin_user.company_address = 'JNL1588A'
    admin_user.linkman = 'sky'
    admin_user.phone_number = '12345678901'
    admin_user.authority = 'super_admin'
    admin_user.updatetime = time.strftime('%Y-%m-%d %H:%M:%S',
                                          time.localtime(
                                              (time.time())))  # 修改数据更新时间
    admin_user.status = 1  # =0,该用户失效

    # 加入到公司库内
    admin_company = Company()
    admin_company.company = 'nbtjy'
    admin_company.company_number = '001'
    admin_company.company_address = 'JNL1588A'
    admin_company.linkman = 'sky'
    admin_company.phone_number = '12345678901'
    admin_company.status = 1

    try:
        db.session.add(admin_user)
        db.session.add(admin_company)
        db.session.commit()
        # 创建报告保存文件夹
        os.makedirs(os.path.join(current_app.config['DOCXFILE_DIR'], '001'))
    except:
        print('注册超级管理员账户失败!')
    else:
        print('注册超级管理员账户成功,请使用email=‘[email protected]’,password=‘123456’登录')
Exemplo n.º 4
0
def addcompany():
    '''
    add company
    '''
    if current_user.admin:
        form = CompanyForm()
        if form.validate_on_submit:
            exist = Company.query.filter_by(nit=form.nit.data).first()

            if not exist:
                company = Company(name=form.name.data,
                                  nit=form.nit.data,
                                  email_contact=form.email_contact.data)
                try:
                    db.session.add(company)
                    db.session.commit()
                    flash('Company added successfully!!')
                except Exception as e:
                    flash('Can´t added company {}'.format(e))

                return redirect(url_for('admin_bp.list_companies'))
        return render_template('/company.html',
                               form=form,
                               username=current_user.username)
    return redirect(url_for('auth_bp.login'))
Exemplo n.º 5
0
def edit(company_id: int = None):
    """Create, view or edit a company."""
    # Select company.
    if company_id:
        company = company_service.find_company_by_id(company_id)
    else:
        company = Company()

    form = init_form(CompanyForm, obj=company)

    # Add locations.
    locations = Location.query.order_by('address').order_by('city')
    form.location_id.choices = \
        [(l.id, l.address + ', ' + l.city) for l in locations]

    form.contact_id.choices = \
        [(c.id, c.name) for c in Contact.query.filter_by().order_by('name')]

    if form.validate_on_submit():
        if not company.id and Company.query.filter(
                Company.name == form.name.data).count():
            flash(_('Name "%s" is already in use.' % form.name.data),
                  'danger')
            return render_template('company/edit.htm', company=company,
                                   form=form)
        company.name = form.name.data
        company.description = form.description.data
        company.contract_start_date = form.contract_start_date.data
        company.contract_end_date = form.contract_end_date.data
        company.location = Location.query.get(form.location_id.data)
        company.contact = Contact.query.get(form.contact_id.data)
        company.website = form.website.data
        if request.files['file']:
            logo = request.files['file']
            _file = file_service.add_file(FileCategory.COMPANY_LOGO,
                                          logo, logo.filename)
            company.logo_file_id = _file.id

        db.session.add(company)
        db.session.commit()
        flash(_('Company "%s" saved.' % company.name), 'success')
        return redirect(url_for('company.view', company_id=company.id))

    return render_template('company/edit.htm', company=company, form=form)
Exemplo n.º 6
0
def snapshots_refresh(limit: int = 10, days: int = 7):
    symbols = all_nyse_symbols()
    random.shuffle(symbols)
    subset = []
    for symbol in symbols:
        # Find or Populate Companies from list
        company = Company.query.filter_by(symbol=symbol).first()
        if not company:
            company = Company.make(symbol)
            db.session.add(company)
            db.session.flush()
        # Check for latest snapshot
        latest_snapshot = (Snapshot.query.filter_by(
            company_id=company.id).order_by(
                Snapshot.creation_time.desc()).first())
        if not latest_snapshot or latest_snapshot.stale(days):
            subset.append(company)
        if len(subset) >= limit:
            break

    successes = []
    errors = []
    for company in subset:
        logger.info(f"Refreshing snapshot for {company.symbol}.")
        try:
            company.refresh_latest_snapshot()
            previous_failure = (SnapshotFailure.query.filter_by(
                symbol=company.symbol).first())
            if previous_failure:
                previous_failure.delete()
                db.session.commit()

            successes.append(company.symbol)

        except Exception as e:
            errors.append(company.symbol)
            failure = SnapshotFailure.make(company.symbol)
            db.session.add(failure)
            db.session.commit()

    out = {
        "name": "referrals:process_targets",
        "completed-at": str(datetime.now()),
        "args": args,
        "errors": errors,
        "successes": successes,
    }
    return out
Exemplo n.º 7
0
def admin_info_complete():
    if request.method == 'POST':
        company_name = request.form.get("company_name")
        owner = request.form.get("owner")
        address = request.form.get("address")
        tel = request.form.get("tel")
        email = request.form.get("email")
        contacts = request.form.get("contacts")
        contact_phone = request.form.get("contact_phone")
        company = Company(company_name, owner, contacts, contact_phone, email,
                          address, tel)
        current_user.is_userInfo_completed = 1
        current_user.fk_company_id = company.id
        db.session.add(company)
        db.session.add(current_user)
        db.session.commit()
        return render_template('user/wait_company_check.html')
    else:
        return redirect(url_for('main.home'))
Exemplo n.º 8
0
 def gen_ts_item(cls, company, timestamp):
     return Company.timescale_type(
         company_id=company.id,
         timestamp=timestamp,
         ## Train Counts
         num_train=company.num_train,
         num_lorry=company.num_lorry,
         num_plane=company.num_plane,
         num_ship=company.num_ship,
         ## Station Counts
         num_train_stations=company.num_train_stations,
         num_lorry_stations=company.num_lorry_stations,
         num_plane_stations=company.num_plane_stations,
         num_ship_stations=company.num_ship_stations,
         ## Economy Data
         money=company.money,
         current_loan=company.current_loan,
         income=company.income,
         delivered=company.delivered,
     )
Exemplo n.º 9
0
def api_company(symbol):
    auth_header = request.headers.get("Authorization", "").split(" ")
    if len(auth_header) != 2:
        abort(403)
    bearer = auth_header[0]
    token = auth_header[1]

    if not bearer == "Bearer":
        abort(403)

    if token not in app.config["API_BEARER_TOKENS"]:
        abort(403)

    if request.method == "GET":
        company = Company.query.filter_by(symbol=symbol).first()
        if not company:
            company = Company.make(symbol)
            db.session.add(company)
            db.session.flush()
        if not company:
            return json.dumps({})

        company = company.refresh_latest_snapshot()
        return json.dumps({"company": company.repr_dict()})
Exemplo n.º 10
0
def create(company_id=None):
    # Select company.
    if company_id:
        company = Company.query.get_or_404(company_id)
    else:
        company = Company()

    data = {}

    data["name"] = company.name
    data["description"] = company.description
    data["contract_start_date"] = company.contract_start_date
    data["contract_end_date"] = company.contract_end_date
    data["website"] = company.website

    # Select locations.
    if company.location_id:
        location = Location.query.get(company.location_id)
    else:
        location = Location()

    data['location_city'] = location.city
    data['location_country'] = location.country
    data['location_address'] = location.address
    data['location_zip'] = location.zip
    data['location_postoffice_box'] = location.postoffice_box
    data['location_email'] = location.email
    data['location_phone_nr'] = location.phone_nr

    if company.contact_id:
        contact = Contact.query.get(company.contact_id)
    else:
        contact = Contact()

    data['contact_name'] = contact.name
    data['contact_email'] = contact.email
    data['contact_phone_nr'] = contact.phone_nr

    form = init_form(NewCompanyForm, data=data)

    if form.validate_on_submit():

        if not contact.id and Contact.query.filter(
                Contact.name == form.contact_name.data).count():
            flash(_('Contact name "%s" is already in use.' %
                    form.contact_name.data), 'danger')
            return render_template('company/create.htm', company=company,
                                   form=form)
        if not contact.id and Contact.query.filter(
                Contact.email == form.contact_email.data).count():
            flash(_('Contact email "%s" is already in use.' %
                    form.contact_email.data), 'danger')
            return render_template('company/create.htm', company=company,
                                   form=form)
        contact.name = form.contact_name.data
        contact.email = form.contact_email.data
        contact.phone_nr = form.contact_phone_nr.data
        # Create or update to contact
        db.session.add(contact)
        db.session.commit()

        # Create or update to location
        location.city = form.location_city.data
        location.country = form.location_country.data
        location.address = form.location_address.data
        location.zip = form.location_zip.data
        location.postoffice_box = form.location_postoffice_box.data
        location.email = form.location_email.data
        location.phone_nr = form.location_phone_nr.data
        db.session.add(location)
        db.session.commit()

        #
        if not company.id and Company.query.filter(
                Company.name == form.name.data).count():
            flash(_('Name "%s" is already in use.' % form.name.data),
                  'danger')
            return render_template('company/edit.htm', company=company,
                                   form=form)
        company.name = form.name.data
        company.description = form.description.data
        company.contract_start_date = form.contract_start_date.data
        company.contract_end_date = form.contract_end_date.data
        company.location = location
        company.contact = contact
        company.website = form.website.data
        if request.files['file']:
            logo = request.files['file']
            _file = file_service.add_file(FileCategory.COMPANY_LOGO,
                                          logo, logo.filename)
            company.logo_file = _file

        db.session.add(company)
        db.session.commit()
        flash(_('Company "%s" saved.' % company.name), 'success')
        return redirect(url_for('company.view', company_id=company.id))
    else:
        flash_form_errors(form)

    return render_template('company/create.htm', company=company, form=form)
Exemplo n.º 11
0
 def test_add_company(self):
     with self.app.app_context():
         company = Company(name='Go hard or go home')
         check = company.save_company()
     self.assertTrue(check, "Company should be added")
Exemplo n.º 12
0
from app.models.product import Product
from app.models.company import Company
from unittest.mock import patch
from app import app
import unittest

company = Company('id', 1)
product = Product('id', 'company_id', 10.00)
product_dump = {
    'id': 'id',
    'company_id': 'company_id',
    'value': 10.00,
    'created': 'created',
    'updated': 'updated',
    'removed': 'removed'
}


def user_dump(id=1):
    user_dump = {
        'id': id,
        'access': 'access',
        'username': '******',
        'created': 'created',
        'updated': 'updated',
        'removed': 'removed'
    }
    return user_dump


class TestProductFind(unittest.TestCase):
Exemplo n.º 13
0
    def post(self):
        ''' Create a company '''
        arguments = request.get_json(force=True)
        name = arguments.get('name').strip()
        district = arguments.get('district').strip() or None
        postal = arguments.get('postal').strip() or None
        country = arguments.get('country').strip() or None
        tech_person_name_string = arguments.get(
            'techPersonName').strip() or None
        tech_person_email = arguments.get('techPersonEmail').strip() or None
        address_line_1 = arguments.get('address1').strip() or None
        address_line_2 = arguments.get('address2').strip() or None
        legal_person_name_str = arguments.get(
            'legalPersonName').strip() or None
        legal_person_email = arguments.get('legalPersonEmail').strip() or None
        tech_person_name = tech_person_name_string.split()
        legal_person_name = legal_person_name_str.split()

        if not name:
            return abort(400, 'Name cannot be empty!')
        try:
            address = Address(
                district=district,
                postal_code=postal,
                country=country,
                address_line_1=address_line_1,
                address_line_2=address_line_2
                )
            tech_person = Person(tech_person_name[0], tech_person_name[-1])
            legal_person = Person(legal_person_name[0], legal_person_name[-1])
            tech_contact = Contact(email=tech_person_email)
            legal_contact = Contact(email=legal_person_email)

            if not address.save_address():
                address = Address.query.filter_by(
                    address_line_1=address.address_line_1,
                    active=True).first()
            if not tech_person.save_person():
                tech_person = Person.query.filter_by(
                    full_name=tech_person_name_string).first()
            if not legal_person.save_person():
                legal_person = Person.query.filter_by(
                    full_name=legal_person_name_str).first()
            if not tech_contact.save_contact():
                tech_contact = Contact.query.filter_by(
                    email=tech_person_email).first()
            if not legal_contact.save_contact():
                legal_contact = Contact.query.filter_by(
                    email=legal_person_email).first()
            tech_contact_person = ContactPerson(
                person=tech_person,
                contact=tech_contact)
            legal_contact_person = ContactPerson(
                person=legal_person,
                contact=legal_contact)
            if not tech_contact_person.save_contact_person():
                tech_contact_person = ContactPerson.query.filter_by(
                    person=tech_person,
                    contact=tech_contact).first()
            if not legal_contact_person.save_contact_person():
                legal_contact_person = ContactPerson.query.filter_by(
                    person=legal_person,
                    contact=legal_contact).first()

            company = Company(
                name=name,
                address=address,
                legal_person=legal_contact_person,
                tech_person=tech_contact_person
                )
            if company.save_company():
                return {'message': 'Company created successfully!'}, 201
            return abort(409, message='Company already exists!')
        except Exception as e:
            abort(400, message='Failed to create new company -> {}'.format(e))
Exemplo n.º 14
0
from werkzeug.exceptions import InternalServerError, Conflict
from app.models.company import Company
from schema import Schema, Or, Use
from unittest.mock import patch
from app.views.company import (find_by_company_id, logical_restore,
                               logical_delete, create, update, find)
from random import randrange
from sqlalchemy.exc import (NotSupportedError, OperationalError,
                            ProgrammingError, IntegrityError, InternalError,
                            DataError)
import unittest

company = Company('id', user_id=1)
integrity_error = IntegrityError('Mock', 'mock', Exception('mock', 'mock'))
aleatory_errors = [
    DataError('Mock', 'mock', Exception('mock', 'mock')),
    OperationalError('Mock', 'mock', Exception('mock', 'mock')),
    InternalError('Mock', 'mock', Exception('mock', 'mock')),
    ProgrammingError('Mock', 'mock', Exception('mock', 'mock')),
    NotSupportedError('Mock', 'mock', Exception('mock', 'mock'))
]

company_validate = Schema({
    'id': Use(str),
    'user_id': Use(int),
    'created': Or(str, None),
    'updated': Or(str, None),
    'removed': Or(str, None)
})

company_list_validate = Schema([{
Exemplo n.º 15
0
def __process_nasdaq_public_data_market(phile, market):
    f = open(phile, 'rb')
    reader = csv.reader(f)
    count = 0
    for row in reader:
        count += 1
        if count == 1:
            continue
        vals = {
            'symbol': row[0],
            'name': row[1],
            'last_sale': row[2],
            'market_cap': row[3],
            'ipo_year': row[5],
            'sector': row[6],
            'industry': row[7],
            'exchange': market,
        }
        c = Company.query.filter(
            Company.symbol == vals['symbol'], Company.exchange == market).all()
        if c:
            app.logger.info('Already Have Data for %s' % c[0].name)
            continue
        c = Company()
        c.symbol = vals['symbol']
        c.name = vals['name']
        if vals['last_sale'] != "n/a":
            c.price = vals['last_sale']
        else:
            c.price = 0
        c.market_cap = vals['market_cap']
        c.ipo_year = vals['ipo_year']
        c.sector = vals['sector']
        c.industry = vals['industry']
        c.exchange = vals['exchange']
        c.save()
        app.logger.info('Saved: %s' % c.name)
Exemplo n.º 16
0
def create_company(company:CompanySerializerIn, db:Session=Depends(get_db)):
    company_obj = Company(**company.dict())
    db.add(company_obj)
    db.commit()
    db.refresh(company_obj)
    return company_obj
Exemplo n.º 17
0
@company_routes.response(CompanySchema(), code=HTTPStatus.OK)
def get_by_id(company_id):
    """
    Gets a company's details by id
    ---
    :param company_id:
    :return:
    """
    return Company.query.filter_by(id=company_id).first_or_404(), HTTPStatus.OK


@company_routes.route("/timescale_data")
@company_routes.arguments(TimeScaleRequestSchema,
                          location="query",
                          as_kwargs=True)
@company_routes.response(Company.timescale_schema()(many=True),
                         code=HTTPStatus.OK)
def all_companies_timescale(**kwargs):
    """
    Gets the timescale data of all companies
    ---
    :return:
    """
    query = Company.timescale_type.query

    if "start" in kwargs:
        query = query.filter(
            Company.timescale_type.timestamp >= kwargs["start"])
    if "end" in kwargs:
        query = query.filter(Company.timescale_type.timestamp <= kwargs["end"])
Exemplo n.º 18
0
def dashboard():
    if request.method == "POST":
        _list = current_user.lists.first()
        if not _list:
            _list = List.make(current_user)
            db.session.add(_list)
            db.session.flush()

        symbol = request.form.to_dict().get("symbol")
        # TODO: check if valid symbol here, capitalization too
        company = Company.query.filter_by(symbol=symbol).first()
        if not company:
            company = Company.make(symbol)
            db.session.add(company)
            db.session.flush()

        _list.add_company(company)

        snapshot = (Snapshot.query.filter_by(company_id=company.id).order_by(
            Snapshot.creation_time.desc()).first())
        if not snapshot:
            snapshot = Snapshot.make(symbol, company)
            if snapshot:
                db.session.add(snapshot)
                db.session.commit()
            else:
                db.session.rollback()

        db.session.commit()
        companies = []
        if _list:
            companies = _list.companies()
        return Company.repr_card_grid(_list.companies())

    if request.method == "DELETE":
        target = request.form.get("target")

        _list = current_user.lists.first()
        if not _list:
            return ""  # should not happen

        company = Company.query.filter_by(id=target).first()
        _list.remove_company(company)
        db.session.commit()
        return ""

    if request.method == "PUT":
        target = request.form.get("target")
        company = Company.query.filter_by(id=target).first()
        if not company:
            return ""

        latest_snapshot = (Snapshot.query.filter_by(
            company_id=company.id).order_by(
                Snapshot.creation_time.desc()).first())
        if not latest_snapshot.stale():
            return company.repr_card()

        snapshot = Snapshot.make(company.symbol, company)
        if snapshot:
            db.session.add(snapshot)
            db.session.commit()
        else:
            db.session.rollback()

        return company.repr_card()

    _list = current_user.lists.first()
    if not _list:
        _list = List.make(current_user)
        db.session.add(_list)
        db.session.commit()
    card_grid = Company.repr_card_grid(_list.companies())
    return render_template("dashboard.html", card_grid=card_grid)
Exemplo n.º 19
0
def populate(populate):
    """
	Populate the database
	"""
    skills = ["Javascript", "HTML", "CSS", "SASS", "PHP", "Python"]

    for name in skills:
        skill = Skill(name=name)
        db.session.add(skill)

    student_1 = Student(name="Lucia",
                        last_name="Cardenas",
                        age=18,
                        email="*****@*****.**")

    student_2 = Student(name="Maria Gracia",
                        last_name="Silva",
                        age=22,
                        email="*****@*****.**")
    db.session.add_all([student_1, student_2])
    company = Company(name="Athelas",
                      address="Recavarren esquina con pardo",
                      phone="+51961738608",
                      website="https://www.athelas.pe")
    db.session.add(company)
    company2 = Company(name=u"Lucuma Labs",
                       address="Cerca al faro de miraflores",
                       phone="+511 681 0041",
                       website="https://lucumalabs.com/")
    db.session.add(company2)
    company3 = Company(name=u"Codepicnic",
                       address="Por todo el mundo",
                       phone="+48652689522",
                       website="https://codepicnic.com/")
    db.session.add(company3)

    db.session.commit()

    skills = db.session.query(Skill).all()
    company.skills.append(skills[0])
    company.skills.append(skills[1])
    company.skills.append(skills[2])
    company.skills.append(skills[3])

    company2.skills.append(skills[4])
    company2.skills.append(skills[5])
    company2.skills.append(skills[1])

    company3.skills.append(skills[3])
    company3.skills.append(skills[5])
    company3.skills.append(skills[1])

    student_1.skills.append(skills[0])
    student_1.skills.append(skills[1])
    student_1.skills.append(skills[2])

    student_2.skills.append(skills[0])
    student_2.skills.append(skills[1])
    student_2.skills.append(skills[2])
    student_2.skills.append(skills[3])

    db.session.commit()
Exemplo n.º 20
0
def create_company():
    '''新建公司'''
    company_name = CreateCompanyValidator().validate_for_api(
    ).company_name.data
    res = Company.create(company_name=company_name)
    return Success()