예제 #1
0
    def post(self):
        # create a new plan
        data = request.get_json()
        if not data:
            ret = {
                'message': 'Provide data.',
            }
            return jsonify(ret), 422
        plan = Plan(name=data['name'])
        if data.get('clients'):
            clients = [
                Client.get(each_client) for each_client in data.get('clients')
            ]
            plan.clients = filter(None, clients)

        if data.get('days'):
            days = [Day.query.get(each_day) for each_day in data.get('days')]
            plan.days = filter(None, days)

        db.session.add(plan)
        db.session.commit()
        db.session.refresh(plan)
        ret = {
            'id': plan.id,
            'message': 'Plan created successfully.',
            'name': data['name']
        }
        return jsonify(ret), 200
예제 #2
0
def manipulate_plan(conn, cursor, fmr, plan_fmt):

    if plan_fmt['plan_name'] != fmr.plan_name:
        if is_duplicate_plan(mysql, fmr.plan_name):
            return short_error(err_list=['This plan is already exists'])

    if plan_fmt['is_active']:
        return short_error(err_list=['This plan is currently active'])

    if is_expired_plan(mysql, fmr.plan_name):
        return short_error(err_list=['This plan is expired and is read-only.'])

    p = Plan(cursor, conn=conn)
    p.update(fmr, plan_fmt['id'])

    q_del = """DELETE FROM employee_plan WHERE ep_employee_FK = %s AND ep_plan_FK = %s"""
    q_ins = """INSERT INTO employee_plan(ep_employee_FK, ep_plan_FK) VALUES (%s, %s)"""
    uq = get_unique_employees(plan_fmt['employees_list'], fmr.employees_list)

    if uq['operation'] == OperationType.DELETE_EMPLOYEE:
        [
            cursor.execute(q_del, (record['id'], plan_fmt['id']))
            for record in uq['diff_list']
        ]
    else:
        [
            cursor.execute(q_ins, (record['id'], plan_fmt['id']))
            for record in uq['diff_list']
        ]

    conn.commit()
    conn.close()
    return short_success(ManipulationType.UPDATED)
예제 #3
0
파일: auth.py 프로젝트: dargonar/Ultraprop
    def get(self, **kwargs):
        if self.is_logged:
            return self.redirect_to('property/list')

        kwargs['form'] = self.form
        no_promo = True
        if 'promo' in kwargs:
            plan = Plan.all().filter('slug', kwargs['promo']).get()
            if plan and plan.enabled == 1:
                kwargs['promo'] = plan
                kwargs['default_plan'] = str(plan.key())
                kwargs['planes'] = None
                no_promo = False

        if no_promo:
            planes = Plan.all().filter('online = ',
                                       1).filter('enabled = ',
                                                 1).order('amount').fetch(3)
            kwargs['planes'] = planes
            kwargs['promo'] = None
            kwargs['default_plan'] = str(planes[1].key())

        kwargs['selected_plan'] = None

        return self.render_response('backend/signup.html', **kwargs)
예제 #4
0
def add_plans(db):

    # Single, 1 website, $49
    plan_1 = Plan.create_and_add(
        id=keys.plan_id_1,
        name="single",
        price=49,
        site_allowance=1,
    )

    # Plus, 3 websites $99
    plan_2 = Plan.create_and_add(
        id=keys.plan_id_2,
        name="plus",
        price=99,
        site_allowance=3,
    )

    # Infinite, unlimited websites $249
    plan_3 = Plan.create_and_add(
        id=keys.plan_id_3,
        name="infinite",
        price=249,
        site_allowance=0,
    )

    keys.add("plan_1_id", plan_1.id)
    keys.add("plan_2_id", plan_2.id)
    keys.add("plan_3_id", plan_3.id)
예제 #5
0
def create_plan():
    form = forms.NewPlanForm(request.form)
    if not form.validate():
        flash("Error, all fields are required")
        return render_template("new_plan.html")

    if form.end_date.data < form.start_date.data:
        flash("Error, end date can't be earlier than start date")
        return render_template("new_plan.html")

    url = generate_hash()
    plan = Plan(name=form.name.data,
                start_date=form.start_date.data,
                end_date=form.end_date.data,
                hashed_url=url)
    if len(plan.date_range()) > 14:
        flash("Error, this trip is too log. You can choose maximum 14 days")
        return render_template("new_plan.html")

    current_user.plans.append(plan)

    for day in plan.date_range():
        timeline = Timeline(date=day)
        plan.timelines.append(timeline)

    db.session.commit()
    db.session.refresh(plan)

    return redirect(url_for("view_plan", id=plan.id))
예제 #6
0
 def update(self):
     try:
         get_plan = Plan.get(name=self.name)
         plan = Plan.update(
             name=self.name, price=self.price,
             quantity=self.quantity).where(Plan.name == get_plan.name)
         plan.execute()
         return {"message": "Plan updated successfully"}
     except Plan.DoesNotExist:
         if Plan.DoesNotExist:
             return {"message": "Plan does not exist"}
예제 #7
0
    def test_pre_expiration_email(self):
        resp_register = register_user_from_wp()
        profile = ClientProfile.objects.all()[0]
        plan1 = Plan(user=profile.user,
                     type=plans.TRIAL,
                     end_at=datetime.now() + timedelta(days=11),
                     status='active')
        plan1.save()
        c = Command()
        c.handle()
        subjects = [m.subject for m in mail.outbox]

        self.assertTrue("It's almost that time" in subjects)
예제 #8
0
def get_plan(pid):
    if request.method == 'GET':
        result = {'data': []}
        pid = unhash_id(pid)
        p = Plan.select().where(Plan.id == pid)
        for row in p:
            row['id'] = hash_id(row['id'])
            result['data'].append(row)
        return jsonify(result)
    elif request.method == 'DELETE':
        payload = request.get_json(force=True)
        pid = unhash_id(payload['id'])
        p = Plan.delete().where(Plan.id == pid).execute()
        return jsonify(payload)
예제 #9
0
 def delete(self):
     try:
         plan = Plan.delete().where(Plan.name == self.name)
         plan.execute()
         return {"message": "Plan deleted successfully"}
     except DoesNotExist:
         return {"message": "Plan does not exist"}
예제 #10
0
파일: app.py 프로젝트: jie/sportsapp
def finish_plan_api():
    pk = flask.request.form.get('pk')
    user_id = flask.session['user_id']
    plan = Plan.fetchone(pk=pk)
    if not plan:
        raise error.PlanNoteFound()

    plan_log = PlanLog()
    plan_log.user_id = user_id
    plan_log.plan_id = plan.pk
    plan_log.create_at = datetime.now()
    plan_log.update_at = datetime.now()
    plan_log.is_enable = 1
    plan_log.save(commit=False)

    for item in plan.plan_items:
        note = Note()
        note.kind_id = item.kind.pk
        note.user_id = user_id
        note.quantity = item.quantity
        note.plan_log_id = plan_log.pk
        note.create_at = datetime.now()
        note.update_at = datetime.now()
        note.save()

    return {'pk': pk}
예제 #11
0
파일: app.py 프로젝트: jie/sportsapp
def create_plan_api():
    title = flask.request.form.get('title')
    content = flask.request.form.get('content')
    user_id = flask.session['user_id']
    record = Plan()
    record.title = title
    record.content = content
    record.user_id = user_id
    record.create_at = datetime.now()
    record.update_at = datetime.now()
    record.is_enable = 1
    record.save()
    return {'pk': record.pk}
예제 #12
0
파일: app.py 프로젝트: jie/sportsapp
def set_plan_item(pk):
    user_id = flask.session['user_id']
    plan = Plan.fetchone(pk=pk, user_id=user_id, is_enable=1)
    if not plan:
        raise error.PlanNoteFound()
    kinds = NoteKind.fetchall(
        user_id=user_id, is_enable=1, order=NoteKind.create_at.desc())
    return flask.render_template('plan_set_item.html', plan=plan, kinds=kinds)
예제 #13
0
파일: views.py 프로젝트: cap/cheqed
def proof_start(request):
    goal_text = request.POST['goal']
    goal_term = env.parse(str(goal_text).strip())
    goal_seq = sequent.Sequent([], [goal_term])

    p = Plan()
    assumption = env.rules['assumption']()
    p.text = env.print_proof(assumption)
    p.save()
    
    proof = Proof()
    proof.plan = p
    proof.goal = env.printer.print_term(goal_term)
    proof.save()

    return HttpResponseRedirect(reverse(proof_detail,
                                        args=[proof.id]))
예제 #14
0
    def plan(self, existing_events: Dict[Event, int],
             desired_events: Set[Event]) -> Plan:
        existing_event_set = set(existing_events.keys())
        events_to_remove = existing_event_set - desired_events
        events_to_add = desired_events - existing_event_set

        ids_to_remove = {existing_events[event] for event in events_to_remove}

        return Plan(to_remove=ids_to_remove, to_add=events_to_add)
예제 #15
0
 def create(self):
     try:
         plan = Plan.create(name=self.name,
                            price=self.price,
                            quantity=self.quantity)
         plan.save()
         return {"message": "Plan created successfully"}
     except IntegrityError:
         return {"message": "Plan already exist"}
예제 #16
0
def register_user():
    """ register a new user, 
        required body fields:
        {
	        "email":"<email here>",
	        "mobile":"<israeli mobile phone number>",
	        "password":"******"
        }
        
        returned 
        {
        "email": "<email address",
        "verification_id": "<verification id>"
        }
    """

    # simple input validation using marshmallow schemas
    json_data = request.get_json()
    if not json_data:
        return make_response(jsonify({'message': 'No input data provided'}), 400)
    try:
        data = user_schema.load(json_data)
    except ValidationError as err:
        return make_response(jsonify({'errors': err.messages}), 422)

    # check to see if user already exist, if so return
    user = User.select().where(User.email == data['email']).first()
    if user:
        return make_response(jsonify({"message": "error registering, user already exist"}), 403)

    try:
        # setting up the user...
        # get the default plan for credit and message cost
        plan, created = Plan.get_or_create(title="regular")
        data['plan'] = plan
        # set the initial plan balance as the neww user current balance
        data['current_balance'] = plan.initial_balance

        # get a verfication code from nexmo, and store the trans id in the users table (or redis...)
        # the api request for nexmo is using a 4 digit default code, and i've configured it for IL for convenience (shorter numbers...)
        response = client.start_verification(number=data["mobile"], brand="kin", country="IL", )
        if response["status"] == "0":
            logger.info("Started verification request_id is {}".format(response["request_id"]))
        else:
            logger.error(response["error_text"])
            return make_response(jsonify({"message": "could not send verification code, please contact admin"}), 500)

        # set the trans id in the users table
        data["verification_id"]=response["request_id"]
        # set the password as hashed
        data["password"] = User.set_password(data["password"])
        # create the user using the values given above
        User.create(**data)
        return make_response(jsonify({"email": data["email"], "verification_id": response["request_id"]}), 200)
    except peewee.IntegrityError:
        return make_response(jsonify({"message": "error registering user"}), 403)
예제 #17
0
파일: app.py 프로젝트: jie/sportsapp
def set_plan_item_quantity(plan_id, kind_id):
    user_id = flask.session['user_id']
    plan = Plan.fetchone(pk=plan_id, user_id=user_id, is_enable=1)
    if not plan:
        raise error.PlanNoteFound()

    kind = NoteKind.fetchone(pk=kind_id, user_id=user_id, is_enable=1)
    if not kind:
        raise error.KindNotExistError()
    return flask.render_template('plan_set_quantity.html', plan=plan, kind=kind)
예제 #18
0
파일: plan.py 프로젝트: jiffies/aip
def create_plan():
    with DBSession() as session:
        new = Plan(name=request.get_json().get("name"), content={})
        session.add(new)
    db_session().refresh(new)
    return jsonify({
        k: v
        for k, v in new.__dict__.items()
        if k in new._sa_instance_state.attrs.keys()
    })
예제 #19
0
    def get(self, **kwargs):

        if self.is_logged:
            return self.redirect_to('property/list')

        #kwargs['planes']        = Plan.all().filter('online = ',1).order('amount').fetch(3)
        kwargs['plan'] = Plan.all().filter('online = ',
                                           1).filter('amount =', 0).get()
        kwargs['form'] = self.form

        return self.render_response('backend/signup.html', **kwargs)
예제 #20
0
def create_plan_execution(conn, cursor, fmr: Forminator):
    if is_duplicate_plan(mysql, fmr.plan_name):
        return short_error(err_list=[
            'This plan already exists. Go to Manage Plan to learn more.'
        ])

    if fmr.disbursement_type == fmr.raw_form.DISB_ALL:
        employees = find_all_employees(cursor, session['manager_dept'])

        if employees is None:
            return short_error(
                err_list=['No employees were found in the department'])
        fmr.employees_list = employees['data']

    p = Plan(cursor, conn=conn)
    p.insert(fmr)
    conn.close()

    execute_orders()
    return short_success(ManipulationType.CREATED)
def open_pay(id):
	if 'plan' not in request.args:
		abort(400, {'message': PLAN_INVALID_OR_NOT_PROVIDED })

	lead = _get_lead(int(id))
	plan = Plan.find_by_slug(request.args['plan'])
	payment = Payment.find_last(lead.key, plan.key)

	if payment is not None:
		return jsonify(data=payment.to_json()), 200
	else:
		abort(404, {'message': 'Payment not found'})
예제 #22
0
def get_plans(nick):
    if request.method == 'GET':
        result = {'data': []}
        p = Plan.select().where(Plan.nick == nick).dicts()
        for row in p:
            row['id'] = hash_id(row['id'])
            result['data'].append(row)
        return jsonify(result)
    elif request.method == 'POST':
        payload = request.get_json(force=True)
        p = Plan.create(**payload)
        return jsonify(payload)
    elif request.method == 'DELETE':
        payload = request.get_json(force=True)
        p = (
            Plan.delete()
            .where(
                (Plan.name == payload['name']) &
                (Plan.nick == payload['nick'])
            )
            .execute()
        )
        return jsonify(payload)
예제 #23
0
    def create(self):
        try:
            plan = Plan.get(id=self.plan)
            customer = Customer.create(name=self.name,
                                       password=self.password,
                                       email_address=self.email,
                                       plan=plan.id,
                                       renewal_date=self.renewal_date)
            customer.save()
        except IntegrityError:

            return {"message": "Customer already exist"}
        else:
            return {"message": "Account created successfully"}
예제 #24
0
파일: app.py 프로젝트: jie/sportsapp
def remove_plan_item_api():
    pk = flask.request.form.get('pk')
    user_id = flask.session['user_id']

    plan = Plan.fetchone(pk=pk, user_id=user_id)
    if not plan:
        raise error.PlanNoteFound()

    item = PlanItem.fetchone(pk=pk)
    if not item:
        raise error.PlanItemNoteFound()

    item.is_enable = 0
    item.save()
    return {'pk': item.pk}
예제 #25
0
 def upgrade(self):
     try:
         customer = Customer.get(email_address=self.email)
         plan = Plan.get(id=self.plan)
     except (
             Customer.DoesNotExist,
             Plan.DoesNotExist,
     ):
         if Customer.DoesNotExist:
             return {"message": "Customer does not exist"}
         if Plan.DoesNotExist:
             return {"message": "Plan does not exist"}
     else:
         customer = Customer.update(
             plan=plan.id, renewal_date=self.renewal_date).where(
                 Customer.email_address == self.email)
         customer.execute()
         return {"message": "Your plan has been upgraded Successfully"}
def _create_or_replace_payment(lead, plan_slug, instalments):
	plan = Plan.find_by_slug(plan_slug)
	payment = Payment.find_open(lead.key, plan.key)

	if payment is None:
		payment = Payment()

	payment.lead = lead.key
	payment.plan = plan.key
	payment.status = 'PENDING'
	payment.message = 'Pending processing'
	payment.instalments = instalments
	payment.iframe_url = ''
	payment.put()

	_enqueue_payment_message(lead, payment)

	return payment
예제 #27
0
def init_db(Meal, Plan, User):
    db.create_all()
    user = User.query.filter_by(email='*****@*****.**').first()
    if not user:
        user = User(
            alt_id=generate_alt_id(size=64),
            alias='dummy',
            email='*****@*****.**',
            password=hash_password('password'),
        )
        plan = Plan(name='dummy plan', users=[user])
        meal = Meal(
            name='dummy meal',
            created_date=datetime.datetime.utcnow(),
            planned_date=to_date_int(datetime.date.today()),
            plan=plan,
        )
        db.session.add(user)
        db.session.add(meal)
        db.session.commit()
예제 #28
0
파일: app.py 프로젝트: jie/sportsapp
def create_plan_item_api():
    plan_id = flask.request.form.get('plan_id')
    kind_id = flask.request.form.get('kind_id')
    quantity = flask.request.form.get('quantity')
    user_id = flask.session['user_id']
    plan = Plan.fetchone(pk=plan_id)

    if not plan:
        raise error.PlanNoteFound()

    item = PlanItem()
    item.kind_id = kind_id
    item.user_id = user_id
    item.plan_id = plan_id
    item.quantity = quantity
    item.create_at = datetime.now()
    item.update_at = datetime.now()
    item.is_enable = 1
    item.save()
    return {'pk': item.pk}
예제 #29
0
파일: app.py 프로젝트: jie/sportsapp
def get_plans():
    user_id = int(flask.session['user_id'])
    records = Plan.fetchall(user_id=user_id, order=Plan.create_at.desc())
    return {'plans': records}
def create():

	# get the post data
	post_data = get_post_data()

	sender_broker = None
	owner = None
	agency = None
	listing = None

	# validates required parameters
	_validates_required_parameters(post_data)

	# creates or find the property owner
	if 'property_owner' in post_data:
		owner = _create_property_owner(post_data['property_owner'])

	# creates or find the agency
	if 'agency' in post_data:
		agency = _create_agency(post_data['agency'], post_data['source_application'])

	# creates or find the property
	if 'listing' in post_data:
		listing = _create_listing(post_data['listing'])

	# if broker is sent
	if 'sender' in post_data:
		# creates or find the broker
		sender_broker = _create_broker(post_data['sender'], agency)

	# defines the buyer type and creates the lead
	buyer_type = ''

	if 'sender' in post_data and owner is not None:
		buyer_type = 'PROPERTY_OWNER'
	else:
		buyer_type = 'PROPERTY_OWNER_FROM_GAIAFLIX'


	# check if the plan is valid
	plan = None
	if 'plan' in post_data:
		plan = Plan.find_by_slug(post_data['plan'])
		if plan is None:
			abort(400, {'message': PLAN_INVALID_OR_NOT_PROVIDED })
	else:
		abort(400, {'message': PLAN_INVALID_OR_NOT_PROVIDED })

	# creates the lead
	lead = Lead()

	lead.sender_broker = sender_broker.key if sender_broker is not None else None
	lead.property_owner = owner.key if owner is not None else None
	lead.listing = listing.key if listing is not None else None
	lead.plan = plan.key
	lead.buyer_type = buyer_type
	lead.status = 'SENT'

	if lead.put():
		json_lead = lead.to_json()

		if lead.property_owner is not None:
			_enqueue_lead_message(json_lead)
			create_activity('LEAD_SENT', lead=lead)

		return jsonify(data=json_lead), 201
	else:
		return jsonify({'error': 'Error creating Lead'})
예제 #31
0
 def clean(self):
     metered_features = self.cleaned_data.get('metered_features')
     Plan.validate_metered_features(metered_features)
     return self.cleaned_data
예제 #32
0
def seed():
    # Users
    user1 = User()
    user1.name = 'Daniel'
    user1.chest_pain = ''
    user1.eck_result = ''
    user1.blood_sugar = False
    user1.angina = False
    user1.age = 21
    db.session.add(user1)

    user2 = User()
    user2.name = 'Bernd'
    user2.chest_pain = ''
    user2.eck_result = ''
    user2.blood_sugar = True
    user2.angina = False
    user2.age = 67
    db.session.add(user2)

    # Plans
    plan1 = Plan()
    plan1.user = user1
    db.session.add(plan1)

    plan2 = Plan()
    plan2.user = user2
    db.session.add(plan2)

    # Plan entries
    for _ in range(10):
        entry1 = PlanEntry()
        entry1.timestamp = datetime.time(random.randint(0, 23), random.randint(0, 59))
        entry1.mandatory = random.randint(0, 1) == 0
        entry1.plan = plan1
        db.session.add(entry1)

        entry2 = PlanEntry()
        entry2.timestamp = datetime.time(random.randint(0, 23), random.randint(0, 59))
        entry2.mandatory = random.randint(0, 1) == 0
        entry2.plan = plan2
        db.session.add(entry1)

    # Measurements
    for _ in range(100):
        measurement = Measurement()
        measurement.user = user1 if random.randint(0, 1) == 0 else user2
        measurement.pulse = random.randint(60, 120)
        measurement.systolic = random.randint(100, 130)
        measurement.diastolic = random.randint(60, 100)
        measurement.timestamp = datetime.datetime(
            2016,
            1,                      # Monat
            random.randint(1, 31),  # Tag (vereinfacht)
            random.randint(0, 23),  # Stunde
            random.randint(0, 59)   # Minute
        )
        db.session.add(measurement)

    # Frequency Measurements
    for _ in range(1000):
        measurement = FrequencyMeasurement()
        measurement.user = user1 if random.randint(0, 1) == 0 else user2
        measurement.rate = random.randint(60, 120)
        measurement.timestamp = datetime.datetime(
            2016,
            1,                      # Monat
            random.randint(1, 31),  # Tag (vereinfacht)
            random.randint(0, 23),  # Stunde
            random.randint(0, 59)   # Minute
        )
        db.session.add(measurement)

    db.session.commit()
예제 #33
0
from models import Plan
from pydantic import BaseModel, ValidationError, validator, PydanticValueError

try:
    Plan()
except ValidationError as e:
    print("JSON representation")
    print("-------------------")
    print(e.json(), end="\n\n")

    print("Python representation")
    print("---------------------")
    print(e.errors(), end="\n\n")

    print("Human readable")
    print("--------------")
    print(str(e))
"""
JSON representation
-------------------
[
  {
    "loc": [
      "base"
    ],
    "msg": "field required",
    "type": "value_error.missing"
  },
  {
    "loc": [
      "usage"
예제 #34
0
def submit_make(request):
    if os.environ.get("TEST", None):
        request.session["userId"] = request.GET["userId"]
    if not "userId" in request.session:
        return HttpResponseRedirect("/static/not_bind.html")
    if not "userId" in request.POST:
        return HttpResponseRedirect("/static/404.html")
    if not request.POST["userId"] == request.session["userId"]:
        return HttpResponseRedirect("/static/404.html")
    try:
        userId = request.POST["userId"]
        user = User.objects.get(openId=userId)
        now = basic_tools.getNow()
        plan = Plan(name=request.POST["plan_name"],
                    description=request.POST["comment"],
                    createTime=now,
                    startTime=basic_tools.DateToInt(
                        "%s:00:00" % request.POST["begintime"][:13]),
                    endTime=basic_tools.DateToInt(
                        "%s:00:00" % request.POST["endtime"][:13]),
                    owner=user)
        if request.POST["goal"] == "":
            goal = 0
        else:
            goal = int(request.POST["goal"])
        plan.goal = goal
        plan.save()
        if goal > 0:
            progress = PlanProgress(plan=plan, user=user)
            progress.save()
        tags = []
        tag = request.POST["tags"]
        if not tag == "":
            item = PTag.objects.filter(name=tag)
            if len(item) == 0:
                item = PTag(name=tag)
                item.save()
            else:
                item = item[0]
            if not item.plans.filter(id=plan.id).exists():
                tags.append(tag)
                item.plans.add(plan)
        i = 0
        while ("tag%d" % i) in request.POST:
            tag = request.POST["tag%d" % i]
            i += 1
            if not tag == "":
                item = PTag.objects.filter(name=tag)
                if len(item) == 0:
                    item = PTag(name=tag)
                    item.save()
                else:
                    item = item[0]
                if not item.plans.filter(id=plan.id).exists():
                    tags.append(tag)
                    item.plans.add(plan)
        if len(tags) == 0 and goal > 0:
            tag = "%d步" % goal
            item = PTag.objects.filter(name=tag)
            if len(item) == 0:
                item = PTag(name=tag)
                item.save()
            else:
                item = item[0]
            if not item.plans.filter(id=plan.id).exists():
                tags.append(tag)
                item.plans.add(plan)
        prefix = os.environ.get("WRIST_HOME")
        path = "/media/plan/"
        if not os.path.exists(prefix + path):
            os.mkdir(prefix + path)
        if "image" in request.FILES:
            file = request.FILES["image"]
            file_name = "%s%s_%s_%s" % (path, plan.name.encode("utf-8"),
                                        str(now), file.name.encode("utf-8"))
            des = open(prefix + file_name, "wb")
            for chunk in file.chunks():
                des.write(chunk)
            des.close()
        else:
            file_name = tools.getDefaultImageByTag(tags)
        plan.image = file_name
        plan.save()
        plan.members.add(user)
        i = 0
        while ("friend%d" % i) in request.POST:
            tools.sendInvite(user, plan.id, request.POST["friend%d" % i])
            i += 1
        return HttpResponseRedirect("/plan/redirect/profile?page=4&id=%d" %
                                    plan.id)
    except:
        return HttpResponseRedirect("/static/404.html")
예제 #35
0
파일: api.py 프로젝트: sunghoonma/Dream
    def post(self, id):
        u = User.query.filter_by(id=id).first()
        if u.id != g.user.id:
            return {'status':'error',
                    'description':'Unauthorized'}, 401

        if request.json:
            params = request.json
        elif request.form:
            params = {}
            for key in request.form:
                params[key] = request.form[key]
        else:
            return {'status':'error','description':'Request Failed'}, 400

        # Replace blank value to None(null) in params
        for key in params:
            params[key] = None if params[key] == "" else params[key]

            if key in ['id', 'user_id', 'reg_dt', 'language']:
                return {'error': key + ' cannot be entered manually.'}, 401

        # Bucket Title required
        if not 'title' in params:
            return {'error':'Bucket title required'}, 401

        # Check ParentID is Valid & set level based on ParentID
        if not 'parent_id' in params or params['parent_id'] == None:
            level = 0
        else:
            b = Bucket.query.filter_by(id=params['parent_id']).first()
            if b is None:
                return {'error':'Invalid ParentID'}, 401
            elif b.user_id != g.user.id:
                return {'error':'Cannot make sub_bucket with other user\'s Bucket'}, 401
            else:
                level = int(b.level) + 1

        if 'rpt_cndt' in params:
            dayOfWeek = datetime.date.today().weekday()
            if params['rpt_type'] == 'WKRP':
                if params['rpt_cndt'][dayOfWeek] == '1':
                    p = Plan(date=datetime.date.today().strftime("%Y%m%d"),
                             user_id=g.user.id,
                             bucket_id=None,
                             status=0,
                             lst_mod_dt=datetime.datetime.now())
                    db.session.add(p)

        if 'photo' in request.files:
            upload_type = 'photo'

            if len(request.files[upload_type].filename) > 64:
                return {'status':'error','description':'Filename is too long (Max 64bytes include extensions)'}, 403
            upload_files = UploadSet('photos',IMAGES)
            configure_uploads(app, upload_files)

            filename = upload_files.save(request.files[upload_type])
            splits = []

            for item in filename.split('.'):
                splits.append(item)
            extension = filename.split('.')[len(splits) -1]

            f = File(filename=filename, user_id=g.user.id, extension=extension, type=upload_type)
            db.session.add(f)
            db.session.flush()
            db.session.refresh(f)


        bkt = Bucket(title=params['title'],
                     user_id=g.user.id,
                     level=str(level),
                     status= params['status'] if 'status' in params else True,
                     private=params['private'] if 'private' in params else False,
                     reg_dt=datetime.datetime.now(),
                     lst_mod_dt=datetime.datetime.now(),
                     deadline=datetime.datetime.strptime(params['deadline'],'%Y-%m-%d').date() if 'deadline' in params \
                                                                                      else datetime.datetime.now(),
                     description=params['description'] if 'description' in params else None,
                     parent_id=params['parent_id'] if 'parent_id' in params else None,
                     scope=params['scope'] if 'scope' in params else None,
                     range=params['range'] if 'range' in params else None,
                     rpt_type=params['rpt_type'] if 'rpt_type' in params else None,
                     rpt_cndt=params['rpt_cndt'] if 'rpt_cndt' in params else None,
                     cvr_img_id=f.id if 'photo' in request.files else None)
                     # cvr_img_id=f.id if 'cvr_img' in params and params['cvr_img'] == 'true' else None)
        db.session.add(bkt)
        db.session.flush()
        db.session.refresh(bkt)

        if 'rpt_cndt' in params:
            if params['rpt_type'] == 'WKRP' and params['rpt_cndt'][dayOfWeek] == '1':
                p.bucket_id = bkt.id

        if 'fb_share' in params:
            social_user = UserSocial.query.filter_by(user_id=u.id).first()
            graph = facebook.GraphAPI(social_user.access_token)
            resp = graph.put_object("me","feed",
                         message= g.user.username + " Posted " + params['title'].encode('utf-8'),
                         link="http://masunghoon.iptime.org:5001",
                         picture=photos.url(File.query.filter_by(id=bkt.cvr_img_id).first().name) if 'photo' in request.files else None,
                         caption="Dream Proj.",
                         description=None if bkt.description is None else bkt.description.encode('utf-8'),
                         name=bkt.title.encode('utf-8'),
                         privacy={'value':params['fb_share'].encode('utf-8')})

            bkt.fb_feed_id = resp['id']

        db.session.commit()

        data={
            'id': bkt.id,
            'user_id': bkt.user_id,
            'title': bkt.title,
            'description': bkt.description,
            'level': bkt.level,
            'status': bkt.status,
            'private': bkt.private,
            'parent_id': bkt.parent_id,
            'reg_dt': bkt.reg_dt.strftime("%Y-%m-%d %H:%M:%S"),
            'deadline': bkt.deadline.strftime("%Y-%m-%d"),
            'scope': bkt.scope,
            'range': bkt.range,
            'rpt_type': bkt.rpt_type,
            'rpt_cndt': bkt.rpt_cndt,
            'lst_mod_dt': None if bkt.lst_mod_dt is None else bkt.lst_mod_dt.strftime("%Y-%m-%d %H:%M:%S"),
            'cvr_img_url': None if bkt.cvr_img_id is None else photos.url(File.query.filter_by(id=bkt.cvr_img_id).first().name),
            'fb_feed_id':None if bkt.fb_feed_id is None else bkt.fb_feed_id
        }

        return {'status':'success',
                'description':'Bucket posted successfully.',
                'data':data}, 201
예제 #36
0
            {
                "tier": Inf,
                "price": 26.41
            },
        ]
    },
}

tmp = Path(gettempdir()) / "pydantic-playground.pkl"

with open(tmp, "wb") as f:
    pickle.dump(plan_dict, f)

# https://pydantic-docs.helpmanual.io/usage/models/#helper-functions
plan = Plan.parse_file(tmp,
                       content_type="application/pickle",
                       allow_pickle=True)
print(plan.json())
"""
{
    "base": [
        {"tier": 30.0, "price": 858.0},
        {"tier": 40.0, "price": 1144.0},
        {"tier": 50.0, "price": 1430.0},
        {"tier": 60.0, "price": 1716.0}
    ],
    "usage": {
        "flat": [
            {"tier": 140.0, "price": 23.67},
            {"tier": 350.0, "price": 23.88},
            {"tier": Infinity, "price": 26.41}
예제 #37
0
def submit_make(request):
    if os.environ.get("TEST", None):
        request.session["userId"] = request.GET["userId"]
    if not "userId" in request.session:
        return HttpResponseRedirect("/static/not_bind.html")
    if not "userId" in request.POST:
        return HttpResponseRedirect("/static/404.html")
    if not request.POST["userId"] == request.session["userId"]:
        return HttpResponseRedirect("/static/404.html")
    try:
        userId = request.POST["userId"]
        user = User.objects.get(openId=userId)
        now = basic_tools.getNow()
        plan = Plan(name=request.POST["plan_name"],description=request.POST["comment"],createTime=now,startTime=basic_tools.DateToInt("%s:00:00" % request.POST["begintime"][:13]),endTime=basic_tools.DateToInt("%s:00:00" % request.POST["endtime"][:13]),owner=user)
        if request.POST["goal"] == "":
            goal = 0
        else:
            goal = int(request.POST["goal"])
        plan.goal=goal
        plan.save()
        if goal > 0:
            progress = PlanProgress(plan=plan,user=user)
            progress.save()
        tags = []
        tag = request.POST["tags"]
        if not tag == "":
            item = PTag.objects.filter(name=tag)
            if len(item) == 0:
                item = PTag(name=tag)
                item.save()
            else:
                item = item[0]
            if not item.plans.filter(id=plan.id).exists():
                tags.append(tag)
                item.plans.add(plan)
        i = 0
        while ("tag%d" % i) in request.POST:
            tag = request.POST["tag%d" % i]
            i += 1
            if not tag == "":
                item = PTag.objects.filter(name=tag)
                if len(item) == 0:
                    item = PTag(name=tag)
                    item.save()
                else:
                    item = item[0]
                if not item.plans.filter(id=plan.id).exists():
                    tags.append(tag)
                    item.plans.add(plan)
        if len(tags) == 0 and goal > 0:
            tag = "%d步" % goal
            item = PTag.objects.filter(name=tag)
            if len(item) == 0:
                item = PTag(name=tag)
                item.save()
            else:
                item = item[0]
            if not item.plans.filter(id=plan.id).exists():
                tags.append(tag)
                item.plans.add(plan)
        prefix = os.environ.get("WRIST_HOME")
        path = "/media/plan/"
        if not os.path.exists(prefix+path):
            os.mkdir(prefix+path)
        if "image" in request.FILES:
            file = request.FILES["image"]
            file_name = "%s%s_%s_%s" % (path, plan.name.encode("utf-8"), str(now), file.name.encode("utf-8"))
            des = open(prefix+file_name, "wb")
            for chunk in file.chunks():
                des.write(chunk)
            des.close()
        else:
            file_name = tools.getDefaultImageByTag(tags)
        plan.image = file_name
        plan.save()
        plan.members.add(user)
        i = 0
        while ("friend%d" % i) in request.POST:
            tools.sendInvite(user, plan.id, request.POST["friend%d" % i])
            i += 1
        return HttpResponseRedirect("/plan/redirect/profile?page=4&id=%d" % plan.id)
    except:
        return HttpResponseRedirect("/static/404.html")
예제 #38
0
파일: admin.py 프로젝트: MaxMorais/silver
 def clean(self):
     metered_features = self.cleaned_data.get('metered_features')
     Plan.validate_metered_features(metered_features)
     return self.cleaned_data
예제 #39
0
파일: auth.py 프로젝트: dargonar/Ultraprop
    def post(self, **kwargs):
        self.request.charset = 'utf-8'

        kwargs['planes'] = Plan.all().filter('online = ', 1).filter(
            'enabled = ', 1).order('amount').fetch(3)
        kwargs['selected_plan'] = None

        plan = get_or_404(self.request.POST.get('plan'))
        # if not plan:
        # kwargs['form']       = self.form
        # kwargs['flash']      = self.build_error('Seleccione un plan vigente.')
        # return self.render_response('backend/signup.html', **kwargs)

        form_validated = self.form.validate()
        if not form_validated:
            kwargs['form'] = self.form
            if self.form.errors:
                kwargs['flash'] = self.build_error(
                    'Verifique los datos ingresados.')
            kwargs['default_plan'] = str(plan.key())
            return self.render_response('backend/signup.html', **kwargs)

        # Generamos la inmo en estado TRIAL y le ponemos el Plan
        realEstate = RealEstate.new()
        realEstate.telephone_number = self.form.telephone_number.data
        realEstate.name = self.form.name.data
        realEstate.email = self.form.email.data
        realEstate.plan = plan
        # realEstate.status           = RealEstate._REGISTERED
        realEstate.status = RealEstate._ENABLED if plan.is_free else RealEstate._REGISTERED
        realEstate.email_image = None
        realEstate.email_image_url = ''
        # Ya tenemos registrado ese domain_id
        realEstate.domain_id = do_slugify(realEstate.name)
        tmp = validate_domain_id(realEstate.domain_id)
        if tmp['result'] != 'free':
            realEstate.domain_id = realEstate.domain_id + datetime.now(
            ).strftime('%Y%m%d%H%M')

        realEstate.put()

        # Generamos la primer factura con fecha hoy+dias_gratis
        # Utilizamos el indicador I para indicar 'id' en vez de 'name'
        first_date = (datetime.utcnow() +
                      timedelta(days=plan.free_days)).date()
        if first_date.day > 28:
            first_date = date(first_date.year, first_date.month, 28)

        invoice = Invoice()
        invoice.realestate = realEstate
        invoice.trx_id = '%sI%d' % (first_date.strftime('%Y%m'),
                                    realEstate.key().id())
        invoice.amount = plan.amount
        #invoice.state      = Invoice._NOT_PAID if plan.amount > 0 else Invoice._INBANK
        invoice.state = Invoice._NOT_PAID if not plan.is_free else Invoice._INBANK
        invoice.date = first_date
        invoice.put()

        # Volvemos a guardar el realEstate con los datos nuevos
        realEstate.last_invoice = invoice.date
        realEstate.save()

        # Generamos el usuario y le asignamos la realestate
        user = User.new()
        user.email = self.form.email.data
        user.password = self.form.password.data
        user.rol = 'owner'
        user.realestate = realEstate
        user.put()

        # Mando Correo de bienvenida y validación de eMail.
        # Armo el contexto dado que lo utilizo para mail plano y mail HTML.
        context = {
            'server_url':
            'http://' + self.request.headers.get('host', 'no host'),
            'realestate_name':
            realEstate.name,
            'validate_user_link':
            self.url_for('backend/validate/user',
                         key=str(user.key()),
                         _full=True),
            'support_url':
            'http://' + self.request.headers.get('host', 'no host')
        }

        # Armo el body en plain text.
        body = self.render_template(
            'email/' + self.config['ultraprop']['mail']['signup']['template'] +
            '.txt', **context)
        # Armo el body en HTML.
        html = self.render_template(
            'email/' + self.config['ultraprop']['mail']['signup']['template'] +
            '.html', **context)

        # Envío el correo.
        mail.send_mail(sender="www.ultraprop.com.ar <%s>" %
                       self.config['ultraprop']['mail']['signup']['sender'],
                       to=user.email,
                       subject="ULTRAPROP - Bienvenido",
                       body=body,
                       html=html)

        self.set_ok(
            u'Un correo ha sido enviado a su casilla de email. Ingrese a ULTRAPROP a través del enlace recibido.'
        )

        return self.redirect_to('backend/auth/login')
예제 #40
0
파일: app.py 프로젝트: jie/sportsapp
def plan_item(pk):
    user_id = flask.session['user_id']
    plan = Plan.fetchone(pk=pk, user_id=user_id, is_enable=1)
    return flask.render_template('plan_item.html', plan=plan)