Ejemplo n.º 1
0
def SavePostionFormJson():
    data = {'Tag': 0, "Message": "", "Data": ""}
    form = position_form.PositionForm()
    if form.validate_on_submit():
        data["Tag"] = 1
        data["Message"] = "操作成功"
        if form.Id.data > 0:
            menu = Position.query.get(form.Id.data)
            menu.PositionName = form.PositionName.data
            menu.PositionSort = form.PositionSort.data
            menu.Status = form.PositionStatus.data
            menu.Remark = form.Remark.data
            menu.ModifyTime = datetime.now()

        else:
            menu = Position(CreateUserid=1,
                            CreateTime=datetime.now(),
                            ModifyTime=datetime.now(),
                            ModifyUserid=1,
                            Status=form.PositionStatus.data,
                            BaseIsDelete=0,
                            BaseCreatorId=1,
                            BaseModifierId=1,
                            BaseVersion=1,
                            PositionName=form.PositionName.data,
                            PositionSort=form.PositionSort.data,
                            Remark=form.Remark.data)
            db.session.add(menu)
        db.session.commit()
    return jsonify(data)
Ejemplo n.º 2
0
def createInvoice(inv_data, supplier_id, user):
    groups = defaultdict(lambda: defaultdict(lambda: defaultdict(list)))
    for c in inv_data:
        if c.amount > 0:
            groups[c.product][c.price]['+'].append(c)
        else:
            groups[c.product][c.price]['-'].append(c)

    invoice = Invoice(user=user,
                      sent=(user.id == supplier_id),
                      paid=(user.id == supplier_id),
                      date=datetime.datetime.utcnow(),
                      positions=[],
                      supplier_id=supplier_id)

    for product, pricedict in groups.items():
        for price, consumptions in pricedict.items():
            if len(consumptions['+']) > 0:
                summe = sum((c.price * c.amount) for c in consumptions['+'])
                amount = sum(c.amount for c in consumptions['+'])
                p = Position(amount=amount,
                             price=price,
                             sum=summe,
                             invoice=invoice,
                             product=product)
                invoice.positions.append(p)
            if len(consumptions['-']) > 0:
                summe = sum((c.price * c.amount) for c in consumptions['-'])
                amount = sum(c.amount for c in consumptions['-'])
                p = Position(amount=amount,
                             price=price,
                             sum=summe,
                             invoice=invoice,
                             product=product)
                invoice.positions.append(p)

    for c in inv_data:
        c.invoice = invoice
        c.billed = True

    invsum = float("{0:.2f}".format(sum(p.sum for p in invoice.positions)))
    invoice.sum = invsum
    db.session.add(invoice)
Ejemplo n.º 3
0
def position(ship):
    """A dummy position fixture."""

    position = Position(latitude='17.9850006103516',
                        longitude='-63.1359672546387',
                        ship=ship,
                        timestamp='2019-01-15 09:43:13+00')
    position.save()

    return position
Ejemplo n.º 4
0
 def initModel(self, obj):
     if obj == 'calendar':
         return Calendar()
     elif obj == 'file':
         return File()
     elif obj == 'position':
         return Position()
     elif obj == 'client' or obj == 'user':
         return Client()
     else:
         return 0
Ejemplo n.º 5
0
def positions():
    positions = Position.query.all()
    form = PositionForm()

    if form.validate_on_submit():
        position = Position(name=form.name.data, description=form.description.data)
        db.session.add(position)
        db.session.commit()
        return redirect(url_for('positions'))

    flash_errors(form)
    return render_template('positions.html', form=form, positions=positions)
Ejemplo n.º 6
0
 def create(self, validated_data):
     status = Position(**validated_data)
     request = self.context['request']
     if status.name == 'Director':
         status.access_level = '5'
     elif status.name == 'Project meneger':
         status.access_level = '4'
     elif status.name == 'Programmer':
         status.access_level = '3'
     else:
         status.access_level = '0'
     status.save()
     return status
def upgrade():
    op.execute('COMMIT')
    with open('data/cities.csv', mode='r') as file:
        reader = DictReader(file)
        for row in reader:
            city = City(id=row['id'], name=row['name'], param=row['param'])
            db.session.add(city)
    with open('data/positions.csv', mode='r') as file:
        reader = DictReader(file)
        for row in reader:
            position = Position(id=row['id'], name=row['name'], param=row['param'])
            db.session.add(position)

    db.session.commit()
Ejemplo n.º 8
0
def create():
    form = PositionForm()
    if form.validate_on_submit():
        print("validated\n")
        print(form.pos_name, form.pos_summary, form.pos_location,
              current_user.get_id())
        new_Pos = Position(pos_name=form.pos_name.data,
                           pos_summary=form.pos_summary.data,
                           pos_location=form.pos_location.data,
                           org_id=current_user.get_id())
        new_Pos.id = Position.query.count() + 1
        db.session.add(new_Pos)
        db.session.commit()
        return redirect(url_for('orgprofile', org_id=current_user.id))
    return render_template('create.html', form=form)
Ejemplo n.º 9
0
def RandomPosition(faker):
    position = Position()

    latln = faker.location_on_land(coords_only=False)

    position.location = latln[0]+','+latln[1]
    position.save()

    positioninfo = PositionInfo()
    positioninfo.city = latln[2]
    positioninfo.country = latln[3]
    positioninfo.state = latln[4].split('/')[1]
    positioninfo.created = faker.date_object()
    positioninfo.position_id = position
    positioninfo.save()
Ejemplo n.º 10
0
def handle_pet_location_update(event, context):
    try:
        for record in event['Records']:
            payload = json.loads(record['body'])
            pets = Pet.query(payload['owner'], Pet.name == payload['name'])
            for pet in pets:
                pet.update(actions=[
                    Pet.location.set(
                        PetLocation(at=payload['at'],
                                    position=Position(
                                        lat=payload['position']['lat'],
                                        lng=payload['position']['lng'])))
                ])
                print('save location for : {0}'.format(pet.name))

    except Exception as ex:
        print(ex)
Ejemplo n.º 11
0
def show_account():
    if not current_user.is_authenticated or not current_user.profile:
        # TODO: error-handling
        return redirect(url_for('login.login'))

    profile = current_user.profile[0]
    positions = profile.positions
    courses = profile.courses
    form = EditProfileForm()
    if form.validate_on_submit():
        if form.edit_preferred_name.data:
            profile.preferred_name = form.edit_preferred_name.data
        if form.edit_contact_email.data:
            profile.contact_email = form.edit_contact_email.data
        if form.edit_phone.data:
            profile.phone = form.edit_phone.data
        if form.edit_notes:
            profile.notes = form.edit_notes.data

        edit_positions = deserialize(form.edit_positions.data)
        if edit_positions:
            for position in positions:
                db.session.delete(position)
        for position in edit_positions:
            db.session.add(
                Position(profile_id=profile.id, position_name=position))

        edit_courses = deserialize(form.edit_courses.data)
        if edit_courses:
            for course in courses:
                db.session.delete(course)
        for course in edit_courses:
            db.session.add(Course(profile_id=profile.id, course_name=course))
        db.session.commit()
        flash('Your profile has been updated. ')
        return redirect(url_for('index'))
    #TODO: Add error-handling
    return render_template("account.html",
                           title="Edit Profile",
                           user=current_user,
                           profile=profile,
                           positions=serialize_positions(positions),
                           courses=serialize_courses(courses),
                           form=form)
Ejemplo n.º 12
0
def upload(eobj):
    id = int()
    for data in eobj.storm_data:
        try:
            name = data[0]
            year = data[1]
            lat = data[2]
            longi = data[3]
            cat = data[4]
            pressure = data[5]
            st = Storm(name=name, year=year, cat=cat)
            if not Storm.query.filter(Storm.name == name).filter(
                    Storm.year == year).first():
                db.session.add(st)
                db.session.commit()
                id = st.id
            p = Position(lat=lat, longi=longi, pressure=pressure, storm_id=id)
            db.session.add(p)
        except Exception as err:
            db.session.rollback()
            print(err)
    db.session.commit()
Ejemplo n.º 13
0
def postexecution():
    request_data = request.get_json()
    logged_user = request_data["user"]
    symbol = request_data["symbol"]
    shares = request_data["shares"]
    price = request_data["price"]
    side = request_data["side"]
    exec_id = request_data["exec_id"]
    reported_time = json.loads(request_data['time'])
    time = datetime.fromisoformat(reported_time)

    user = User.query.filter_by(email=logged_user).first()
    if user is not None:
        position = Position()
        position.ticker = symbol
        position.email = logged_user
        position.stocks = shares
        position.last_exec_side = side
        if side == 'BOT':
            position.open_price = price
            position.opened = time
            position.exec_id_buy = str(exec_id)
        else:
            position.close_price = price
            position.closed = time
            position.exec_id_sld = str(exec_id)

        result, np = position.update_position()

        if result == "new_sell":
            # check_if_market_fall(logged_user)
            notify_closed(np, logged_user)
        elif result == "new_buy":
            notify_open(np, logged_user)

        return "Execution for " + logged_user + " stored at server."
    else:
        return "The user configured is not found on Server the execution is not logged"
Ejemplo n.º 14
0
def fake_data():
    """
    flask fake-data
    """

    # if not Role.query.first():
    #     create_role()

    r_a = db.session.query(Role).filter(Role.name == 'admin').first()
    r_m = db.session.query(Role).filter(Role.name == 'moderator').first()
    r_u = db.session.query(Role).filter(Role.name == 'user').first()

    desc = 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. '\
           'Cum sociis natoque penatibus et'

    o = Organization(name='OOO Organization of Project', description=desc)

    d = Department(name='Group of accountants', description=desc)
    d.organization = o

    d1 = Department(name='Group of lawyers', description=desc)
    d1.organization = o

    d2 = Department(name='Administrators', description=desc)
    d2.organization = o

    admin_user = User(name='Pety',
                      second_name='Petrovich',
                      last_name='Petrov',
                      username='******',
                      email='*****@*****.**',
                      description='it is admin')
    admin_user.set_password('pass')
    admin_user.department = d2
    admin_user.role = r_a

    p = Position(name='Accountant', description=desc)
    p1 = Position(name='Lawyer', description=desc)

    u = User(name='Ivan',
             second_name='Ivanovich',
             last_name='Ivanov',
             username='******',
             email='*****@*****.**',
             description=desc)
    u.set_password('pass')
    u.department = d
    u.position = p
    u.role = r_u

    u1 = User(name='Vladimir',
              second_name='Vladimirovich',
              last_name='Ivanov',
              username='******',
              email='*****@*****.**',
              description=desc)
    u1.set_password('pass')
    u1.department = d1
    u1.position = p1
    u1.role = r_m

    ord_ = Order(name='Problems with access to the Internet', description=desc)
    ord_.user = u
    ord1 = Order(name='The printer is not working', description=desc)
    ord1.user = u1

    db.session.add_all([ord_, ord1])
    db.session.commit()

    g = GroupOrder(name='General problem', description=desc)
    g.user_performer = admin_user

    ord_.group_order = g
    ord1.group_order = g

    db.session.add_all([ord_, ord1])
    db.session.commit()

    s = Service(name='The Internet', description=desc)
    s1 = Service(name='Copying and copying equipment', description=desc)
    g.services.append(s)
    g.services.append(s1)

    db.session.add_all([g, g])
    db.session.commit()

    r = Result(name='Performance of equipment', description='it is ok')
    g.results.append(r)
    r1 = Result(name='A small salary for a system administrator',
                description='It is necessary to increase the salary '
                'of the system administrator')
    r1.positive = True
    g.results.append(r1)

    db.session.add_all([g, g])
    db.session.commit()

    n = Note(name='some note')
    n1 = Note(name='some note 1')
    n2 = Note(
        name=
        'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the'
        ' industry\'s standard dummy text ever since the 1500s, when an unknown printer took a galley of '
        'type and scrambled it to make a type specimen book.')

    c = Consultation(
        name=
        'Lorem Ipsum is simply dummy text of the printing and typesetting industry',
        description=
        'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem '
        'Ipsum has been the industry\'s standard dummy text ever since the 1500s, when an '
        'unknown printer took a galley of type and scrambled it to make a type specimen bok.',
        organization='Some Organization')

    admin_user.notes.append(n)
    admin_user.notes.append(n1)
    admin_user.notes.append(n2)
    admin_user.consultations.append(c)

    db.session.add_all([admin_user])
    db.session.commit()
Ejemplo n.º 15
0
# add Department
dep1 = Department(id=1, department_name='Admin')
db.session.add(dep1)
dep2 = Department(id=2, department_name='Business')
db.session.add(dep2)
dep3 = Department(id=3, department_name='Support')
db.session.add(dep3)
dep4 = Department(id=4, department_name='Devs')
db.session.add(dep4)
dep5 = Department(id=5, department_name='HR')
db.session.add(dep5)
dep6 = Department(id=6, department_name='Test')
db.session.add(dep6)

# add Position
pos1 = Position(id=1, position_name='Intern')
db.session.add(pos1)
pos2 = Position(id=2, position_name='Junior')
db.session.add(pos2)
pos3 = Department(id=3, position_name='Regular')
db.session.add(pos3)
pos4 = Position(id=4, position_name='Senior')
db.session.add(pos4)
pos5 = Department(id=5, position_name='Specialist')
db.session.add(pos5)
pos6 = Position(id=6, position_name='Team Leader')
db.session.add(pos6)
pos7 = Department(id=7, position_name='Boss')
db.session.add(pos7)
pos8 = Position(id=8, position_name='CEO')
db.session.add(pos8)
Ejemplo n.º 16
0
    def sync(self, db: Session, api: ServerSession):

        hue_lights = api.get('/lights')
        hue_groups = api.get('/groups')

        lights = {light.id: light for light in crud_light.get_multi(db)}
        groups = {groups.id: groups for groups in crud_group.get_multi(db)}

        for light_id, hue_light in hue_lights.items():
            light = lights.get(int(light_id))
            if not light:
                light = crud_light.create(db, obj_in={
                    'id': int(light_id),
                    'position': Position(),
                    'name': hue_light.get('name'),
                    'type': hue_light.get('type'),
                    'modelid': hue_light.get('modelid'),
                    'manufacturername': hue_light.get('manufacturername'),
                    'productname': hue_light.get('productname'),
                    'on': False
                })
            else:
                light = crud_light.update(db, api, light=light, light_in={
                    'name': hue_light.get('name'),
                    'type': hue_light.get('type'),
                    'modelid': hue_light.get('modelid'),
                    'manufacturername': hue_light.get('manufacturername'),
                    'productname': hue_light.get('productname')
                })

        for light_id, light in lights.items():
            if str(light_id) not in hue_lights:
                crud_light.remove(db, id=light.id)

        for group_id, hue_group in hue_groups.items():
            group = groups.get(int(group_id))
            if not group:
                group = crud_group.create(db, obj_in={
                    'id': int(group_id),
                    'position': Position(),
                    'name': hue_group.get('name'),
                    'type': hue_group.get('type'),
                    'lights': (
                        [crud_light.get(db, id=int(id))
                            for id in hue_group['lights']]
                    )}
                )
            else:
                group = crud_group.update(db, db_obj=group, obj_in={
                    'name': hue_group.get('name'),
                    'type': hue_group.get('type'),
                    'lights': (
                        [crud_light.get(db, id=int(id))
                            for id in hue_group['lights']]
                    )}
                )

        for group_id, group in groups.items():
            if str(group_id) not in hue_groups:
                crud_group.remove(db, id=group.id)

        return {
            'lights': crud_light.count(db),
            'groups': crud_group.count(db)
        }
Ejemplo n.º 17
0
def investments():
   new_inv_form = NewInvestmentForm()
   if new_inv_form.submit3.data and new_inv_form.validate():
      new_investment = Investment(title=new_inv_form.title.data, category=new_inv_form.category.data)
      db.session.add(new_investment)
      db.session.commit()

      flash('New investment created!')
      return redirect(url_for('investments'))

   form = UploadFormInvestments()
   investments = Investment.query.all()
   form.investment.choices = [(inv.id, inv.title) for inv in investments]
   if form.submit1.data and form.validate():
      new_position = Position(investment=form.investment.data, date=form.date.data, net_amount=form.net_amount.data, gross_amount=form.gross_amount.data)
      db.session.add(new_position)
      db.session.commit()

      flash('New position inserted!')
      return redirect(url_for('investments'))

   goalForm = GoalForm()
   if goalForm.submit.data and goalForm.validate():
      new_goal= InvestmentGoal(amount=goalForm.amount.data, year=date.today().year)
      db.session.add(new_goal)
      db.session.commit()

      flash('New investment goal set!')
      return redirect(url_for('investments'))

   goal = InvestmentGoal.query.filter(InvestmentGoal.year == date.today().year).first()
   if goal:
      goalForm = None   

   #Using session to store the dates used from the last 
   if "init_date_inv" not in session:
      session["init_date_inv"] = date.today().replace(day=1, month=1).strftime("%d%m%Y")
      session["end_date_inv"] = date.today().strftime("%d%m%Y")

   form_date = DatesForm(session["init_date_inv"], session["end_date_inv"])
   if form_date.submit2.data and form_date.validate():
      form_date.initial_date.data = form_date.initial_date.data
      form_date.end_date.data = form_date.end_date.data
      session["init_date_inv"] = form_date.initial_date.data.strftime("%d%m%Y")
      session["end_date_inv"] = form_date.end_date.data.strftime("%d%m%Y")
   elif request.method == 'GET':
      form_date.initial_date.data = datetime.strptime(session["init_date_inv"], "%d%m%Y").date()
      form_date.end_date.data = datetime.strptime(session["end_date_inv"], "%d%m%Y").date()

   try:
      positions_df = pd.read_sql(Position.query.filter((Position.date >= datetime.strptime(session["init_date_inv"], "%d%m%Y")) & (Position.date <= datetime.strptime(session["end_date_inv"], "%d%m%Y"))).statement, db.session.bind) 
      investments_df = pd.read_sql(Investment.query.statement, db.session.bind) 
      investments_df = pd.merge(positions_df, investments_df, how = 'left', left_on = 'investment', right_on = 'id')
      views = get_views_investment(investments_df)
   except:
      views = None

   return render_template('investments.html', 
                           new_inv_form=new_inv_form, 
                           form=form, 
                           form_date=form_date, 
                           goalForm=goalForm,
                           active_page = 'investments',
                           views = views)