예제 #1
0
def api_create_activities(request,*,activity_name):
    check_admin(request)
    if not activity_name or not activity_name.strip():
        raise APIValueError('name', 'activity_name cannot be empty.')
    
    activity = Activities(creator=request.__user__.id, creator_name=request.__user__.name, name = activity_name.strip())
    yield from activity.save()
    return activity
예제 #2
0
 def post(self):
     content = request.json
     person = People.query.filter_by(name=content['person']).first()
     activity = Activities(name=content['name'], person=person)
     activity.save()
     response = {
         'pessoa': activity.person.name,
         'name': activity.name,
         'id': activity.id
     }
     return response
예제 #3
0
 def post(self):
     data = request.json
     people = People.query.filter_by(name=data['people']).first()
     activity = Activities(name=data['name'], people=people)
     activity.save()
     response = {
         'people': activity.people.name,
         'name': activity.name,
         'id': activity.id
     }
     return response
예제 #4
0
def index(*, page='1'):
    page_index = get_page_index(page)
    num = yield from Activities.findNumber('count(id)',where="state = '1'")
    page = Page(num)
    if num == 0:
        activities = []
    else:
        activities = yield from Activities.findAll(where="state='1'", orderBy='created_at desc', limit=(page.offset, page.limit))
    return {
        '__template__': 'activities_index.html',
        'page': page,
        'activities': activities
    }
예제 #5
0
def manage_activites(request,*,page='1'):
    page_index = get_page_index(page)
    num = yield from Activities.findNumber('count(id)')
    page = Page(num,page_index)
    if num == 0:
        activities = []
    else:
        activities = yield from Activities.findAll(orderBy='created_at desc', limit=(page.offset, page.limit))
    return {
        '__template__': 'manage_activities.html',
        'page':page,
        'activities':activities
    }    
예제 #6
0
    def post(self):
        dates = request.json
        person = Person.query.filter_by(name=dates['person']).first()
        activity = Activities(name=dates['name'],
                              description=dates['description'],
                              person=person)
        activity.save()
        response = {
            'person': activity.person.name,
            'name': activity.name,
            'description': activity.description
        }

        return response
예제 #7
0
    def post(self):
        data = request.json
        person = People.query.filter_by(name=data['person']).first()
        try:
            activitie = Activities(name=data['name'], person=person)
            activitie.save()
            response = {
                'id': activitie.id,
                'person': activitie.person.name,
                'name': activitie.name
            }
        except AttributeError:
            response = {'status': 'error', 'message': 'Person not found'}

        return response
예제 #8
0
def activities(request,*,id):
    user = request.__user__
    activity = yield from Activities.find(id)
    if not activity:
        return {
            '__template__': 'errpage.html',
            'errmsg': '活动id不存在'
        }

    if activity.state != "1":
        return {
            '__template__': 'errpage.html',
            'errmsg': '活动已停止'
        }               

    gifts = yield from Gifts.findAll('activity_id = ?',[id])
    if user is not None:
        user_gifts = yield from UserGifts.findAll('user_id=? and activity_id=?',[user.id,activity.id])
    else:
        user_gifts = []

    return {
        '__template__': 'activities.html',
        'activity':activity,
        'gifts':gifts,
        'user_gifts':user_gifts
    }
예제 #9
0
def api_activity_gift_select(request,*,id):
    user = request.__user__
    if user is None:
        raise APIPermissionError('Please signin first.')

    gift = yield from Gifts.find(id)
    if gift is None:
        raise APIResourceNotFoundError('Gift')

    activity = yield from Activities.find(gift.activity_id)
    if activity is None:
        raise APIResourceNotFoundError('Activity')
    if activity.state != "1":
        raise APIError('活动已停止')   

    user_gifts = yield from UserGifts.findAll('user_id=? and activity_id = ?',[user.id,activity.id])
    if len(user_gifts) == 0:    
        user_gift = UserGifts(user_id = user.id,activity_id = activity.id,
            gift_id = gift.id,user_name=user.name,gift_name=gift.name,gift_image=gift.image,user_email=user.email)
        yield from user_gift.save()
    else:
        user_gift = user_gifts[0]
        user_gift.gift_id = gift.id
        user_gift.gift_name = gift.name
        user_gift.gift_image = gift.image
        user_gift.user_name = user.name
        user_gift.user_email = user.email
# 
        user_gift.created_at = time.time()
        # print("------------------------------------",time.time())
        yield from user_gift.update()
    

    return dict(gift=gift)  
예제 #10
0
def edit_user_activity(token_info: dict, activity_id: str) -> Tuple[Response, int]:

    data = request.get_json()

    category = Categories.get_specific_category(data.pop("category_id"))

    start = _parse_to_utc_iso8610(data["activity_start"])
    end = _parse_to_utc_iso8610(data["activity_end"])

    data.update(category=category)

    data.update(
        duration=_calculate_duration_in_mins(
            start,
            end
        )
    )

    data["activity_start"] = start
    data["activity_end"] = end

    updated_activity = Activities.edit_specific_activity(activity_id, **data)

    print(updated_activity)

    return jsonify({"message": f"Activity {activity_id} successfully updated."}), 200
예제 #11
0
def manage_activity_gifts(request,*,activity_id):
    activity = yield from Activities.find(activity_id)
    gifts = yield from Gifts.findAll('activity_id = ?',[activity_id])
    return{
        '__template__': 'manage_activity_gifts.html',
        'activity':activity,
        'gifts':gifts
    }
예제 #12
0
def _calculate_category_duration(user_id: str, category_id: str) -> float:
    category = Categories.get_specific_category(category_id=category_id)

    activities = Activities.objects(user_id=user_id, category=category).exclude("id")

    sum_duration = sum([activity.duration for activity in activities])

    return sum_duration
예제 #13
0
def manage_activity_report(request,*,id):
    user_gifts = yield from UserGifts.findAll('activity_id=?',[id],orderBy='created_at desc')
    activity = yield from Activities.find(id)
    return{
        '__template__':'manage_activity_report.html',
        'user_gifts':user_gifts,
        'activity':activity

    }
예제 #14
0
def api_activity_state(request,*,id):
    check_admin(request)
    activity = yield from Activities.find(id)
    if activity.state == '1':
        activity.state = '0'
    else:
        activity.state = '1'
    yield from activity.update()    
    return activity
예제 #15
0
    def create(self, validated_data):
        activity = Activities(
            name=validated_data['name'],
            venue=validated_data['venue'],
            postcode=validated_data['postcode'],
            agesLower=validated_data['agesLower'],
            agesUpper=validated_data['agesUpper'],
            contactName=validated_data['contactName'],
            contactEmail=validated_data['contactEmail'],
            number=validated_data['number'],
            special=validated_data['special'],
            )
        activity.save()

        if validated_data['owner']:
            usr = User.objects.get(username = validated_data['owner']['username'])
            activity.owner = usr
            activity.save()
            

        for item in validated_data['days']:
            print 'entering day associtaion'
            newDay = act_day(act=activity, day=item['day'], startTime=item['startTime'], endTime=item['endTime'])
            newDay.save()

        for item in validated_data['cats']:
            print 'entering cat associtaion'
            newCat = Categories.objects.get(name=item['cat']['name'])
            newEventCat = act_cat(act=activity, cat=newCat)
            newEventCat.save()                       

        print activity

        return activity
예제 #16
0
def data_socket(ws):
    name = socket_name(ws)
    # log.debug("socket {} OPEN".format(name))
    while not ws.closed:
        msg = receiveObj(ws)
        if msg:
            if "query" in msg:
                # log.debug("Received query: {}".format(msg["query"]))
                # sendObj(ws, {"msg": "sending query {}...".format(msg["query"])})
                for a in Activities.query(msg["query"]):
                    sendObj(ws, a)
            else:
                log.debug("{} says {}".format(name, msg))
예제 #17
0
def update(request):
    content = xmlparser.getNews()

    counter = 0
    for activity in content:
        counter += 1
        new_entry = Activities(id=counter,
                    title=activity['title'],
                    eventType=activity['tipo'].split("/")[3],
                    price=getPrice(activity),
                    time=getTime(activity),
                    duration=getDuratrion(getTime(activity), 
                        datetime.strptime(activity['final'].split('.')[0],'%Y-%m-%d %H:%M:%S')),
                    longDuration=longDuration(activity),
                    description=activity['url'],
                    )
        new_entry.save()

    update = lastUpdate(id=1, time=localTime())
    update.save()

    if request is not None:
        return HttpResponseRedirect("/todas")
예제 #18
0
def new_activities(person_id):
    p = PersonInfo.query.get(person_id)
    if request.method == 'POST':
        if request.form['date']:
            ac_date = datetime.strptime(request.form['date'], '%m/%d/%Y')
        else:
            ac_date = None
        ac_content = request.form['activity'].replace('\r\n', '<br/>')
        actv = Activities(ac_date, ac_content)
        print('----------------------------------')
        print(ac_date, request.form['activity'])
        p.activities.append(actv)
        db.session.add(actv)
        db.session.commit()
        return render_template('activities.html', p=p)
    else:
        return render_template('new_activities.html', p=p)
예제 #19
0
def manage_activity_gift_add_post(request,*,activity_id,gift_name,image):
    errmsg = ''
    if image.filename.endswith(('jpg','jpeg','png')):
        suffix = os.path.splitext(image.filename)[1]
        fn = uuid.uuid4().hex + suffix
        open('static/img/' + fn, 'wb').write(image.file.read())
        gift = Gifts(activity_id = activity_id,name = gift_name,image = 'static/img/%s'%fn)
        yield from gift.save()
    else:
        errmsg = '图片文件格式不正确'

    activity = yield from Activities.find(activity_id)
    return  {
        '__template__':'manage_activity_gift_add.html',
        'activity':activity,
        'errmsg':errmsg
    }     
예제 #20
0
def get_user_activities(token_info: dict) -> Tuple[Response, int]:

    activities = Activities.objects(user_id=token_info["public_id"]).exclude("id")

    parsed_activities = [
        {
            "activity_id": activity.activity_id,
            "user_id": activity.user_id,
            "name": activity.name,
            "category": activity.category.public_id,
            "activity_start": _convert_unix_to_iso8610(activity.activity_start),
            "activity_end": _convert_unix_to_iso8610(activity.activity_end),
        }
        for activity in activities
    ]

    return jsonify({"activities": parsed_activities}), 200
예제 #21
0
def get_rolling_meter(
    token_info: dict, include_unassigned: bool = True
) -> Tuple[Response, int]:
    activities = Activities.objects(user_id=token_info["public_id"]).exclude("id")

    if include_unassigned:
        time_window = _calculate_time_window(activities)
    else:
        time_window = sum([activity.duration for activity in activities])

    share_response = _build_shared_json(time_window, token_info["public_id"])

    average_response = _build_averages_json(time_window, token_info["public_id"])

    share_response.update(average_response)

    return jsonify(share_response)
예제 #22
0
def create_activity(token_info):

    data = request.get_json()

    start = dp.isoparse(data["activity_start"]).astimezone(tz.UTC)
    end = dp.isoparse(data["activity_end"]).astimezone(tz.UTC)

    new_activities = Activities(
        name=data["name"],
        user_id=token_info["public_id"],
        activity_start=start,
        activity_end=end,
        category_id=data["category_id"],
    )
    database.db_session.add(new_activities)
    database.db_session.commit()

    return jsonify({"message": "new activity record created"})
예제 #23
0
def create_activity(token_info: dict) -> Tuple[Response, int]:

    data = request.get_json()

    start = _parse_to_utc_iso8610(data["activity_start"])
    end = _parse_to_utc_iso8610(data["activity_end"])
    activity_id = str(uuid.uuid4())

    category = Categories.get_specific_category(data["category_id"])

    duration = _calculate_duration_in_mins(start, end)

    Activities(
        activity_id=activity_id,
        name=data["name"],
        user_id=token_info["public_id"],
        activity_start=start,
        activity_end=end,
        category=category,
        duration=duration,
    ).save()

    return jsonify({"activity_id": activity_id}), 200
예제 #24
0
    def create(self, validated_data):
        activity = Activities(
            name=validated_data['name'],
            venue=validated_data['venue'],
            postcode=validated_data['postcode'],
            agesLower=validated_data['agesLower'],
            agesUpper=validated_data['agesUpper'],
            contactName=validated_data['contactName'],
            contactEmail=validated_data['contactEmail'],
            number=validated_data['number'],
            special=validated_data['special'],
        )
        activity.save()

        if validated_data['owner']:
            usr = User.objects.get(
                username=validated_data['owner']['username'])
            activity.owner = usr
            activity.save()

        for item in validated_data['days']:
            print 'entering day associtaion'
            newDay = act_day(act=activity,
                             day=item['day'],
                             startTime=item['startTime'],
                             endTime=item['endTime'])
            newDay.save()

        for item in validated_data['cats']:
            print 'entering cat associtaion'
            newCat = Categories.objects.get(name=item['cat']['name'])
            newEventCat = act_cat(act=activity, cat=newCat)
            newEventCat.save()

        print activity

        return activity
예제 #25
0
STREAMS_TO_CACHE = ["polyline", "time"]

sslify = SSLify(app, skips=["webhook_callback"])

# models depend app so we import them afterwards
from models import (Users, Activities, EventLogger, Utility, Webhooks, Index,
                    Payments, db_sql, mongodb, redis)

# initialize MongoDB collections if necessary
collections = mongodb.collection_names()

if "history" not in collections:
    EventLogger.init()

if Activities.name not in collections:
    Activities.init_db()
else:
    Activities.update_ttl()

if Index.name not in collections:
    Index.init_db()
else:
    Index.update_ttl()

if Payments.name not in collections:
    Payments.init_db()

Analytics(app)


def parseInt(s):
예제 #26
0
def api_delete_activity(request,*,id):
    check_admin(request)
    activity = yield from Activities.find(id)
    yield from activity.remove()
    return dict(id=id)
예제 #27
0
def manage_activity_gift_add(request,*,activity_id):
    activity = yield from Activities.find(activity_id)
    return  {
        '__template__':'manage_activity_gift_add.html',
        'activity':activity
    } 
예제 #28
0
def delete_user_activity(token_info: dict, activity_id: str) -> Tuple[Response, int]:

    Activities.delete_specific_activity(activity_id)

    return jsonify({"message": f"Activity {activity_id} successfully deleted."}), 200
예제 #29
0
def app_init():
    info = {Activities.init_db(), Index.init_db(), Payments.init_db()}
    return "Activities, Index, Payments databases re-initialized"
예제 #30
0
def app_init():
    info = {Activities.init(), Indexes.init()}
    return "Activities and Indexes databases re-initialized"