Ejemplo n.º 1
0
def likeGoodPost():

	# 일일한도 체크
	todayCount = myTodayCounts(request.form['userId'], "GoodLike");
	if todayCount["Like"] >= 10 :
		return jsonify({ "code": 313, "result": "Limit today's like good thing" })

	try:
		like = GoodLike(request.form['postId'], request.form['userId'])
		db_session.add(like)
		db_session.commit()
		result = { "code": 200, "result": "Success" }

		# 포인트 적립
		point_result = putPointFunc(request.form['userId'], 10, "GoodLike", request.form['postId'])
		if point_result!=False :
			result["pointId"] = point_result["pointId"]
			result["point"] = point_result["point"]
		# 글쓴이 적립
		putPointFunc(request.form['pUserId'], 10, "GoodLikeRcv", request.form['postId'])

		# 푸쉬알림.
		push_result = sendPush(request.form['pUserId'], 3, "작성한 게시물이 \'좋아요\'를 받았습니다.")
		result["push"] = push_result

	except exc.IntegrityError as e:
		db_session.rollback()
		result = { "code": 402, "result": "Duplicate entry or No such entry" }

	return jsonify(result)
Ejemplo n.º 2
0
 def mutate(self, info, files, item_id, id_from_token):
     item = db.query(Item).filter_by(id=item_id).first()
     if item is None:
         raise Exception("No item was found with this ID!")
     if item.owner_id != id_from_token:
         return AddPictures(ok=False, message="Access denied!")
     # TODO maybe change names for pictures?
     i = 0
     for pic in files:
         if check_format(pic):
             i += 1
             name = 'items/item_' + str(item.id) + '_' + str(i)
             if upload_file(pic, Config.bucket, name):
                 try:
                     db.add(
                         ItemPicture(item_id=item.id, path_to_picture=name))
                     commit_with_check(db)
                 except:
                     db.rollback()
             else:
                 return AddPictures(
                     ok=False, message="Pictures haven't been uploaded!")
         else:
             return AddPictures(
                 ok=False,
                 message=
                 "Only pictures (.png, .jpeg, .bmp) can be downloaded!")
     return AddPictures(ok=True, messages="Pictures have been uploaded!")
Ejemplo n.º 3
0
def add():
    if request.method == 'GET':
        output = render_template("user/add.html")
    else:
        output = {
            'error': None,
            'error_message': None,
            'redirect_url': None,
        }
        try:
            if request.json:
                form_data = request.json
            else:
                form_data = request.form
            name = form_data["user_name"]
            phone = form_data["user_phone"]
            mac_address = form_data["user_mac_address"]
            user = RegisteredUser(name, mac_address, phone)
            db_session.add(user)
            db_session.commit()
            output['redirect_url'] = url_for('mod_user.show')
        except Exception as e:
            output['error'] = True
            output['error_message'] = str(e)
            db_session.rollback()
        finally:
            output = Response(json.dumps(output), mimetype='application/json')

    return output
Ejemplo n.º 4
0
def command_add(message_text, room_id, person_id):
    post_text = 'Command not valid... Usage = add user/asset name MAC_address phone[optional]'
    try:
        message_pieces = message_text.split(' ')
        second_word = message_pieces[1].lower()
        if second_word in ['user', 'asset', 'user/asset']:
            name = message_pieces[2]
            mac_address = message_pieces[3]
            phone = None
            if len(message_pieces) > 4:
                phone = message_pieces[3]

            try:
                user = RegisteredUser(name, mac_address, phone)
                db_session.add(user)
                db_session.commit()
                post_text = 'Item created successfully'
            except Exception as e:
                if 'duplicate key value violates unique constraint "registered_user_mac_address_key"' in str(
                        e):
                    post_text = 'MAC Address already registered. Try a different value'
                else:
                    post_text = str(e)
                db_session.rollback()
    except:
        pass

    finally:
        print('Posting on Spark... {}'.format(post_text))
        write_to_spark(room_id, None, None, post_text, None, None)

    return post_text
Ejemplo n.º 5
0
    def mutate(self, info, group_id, user_id, id_from_token):
        group_id = int(group_id)
        user_id = int(user_id)
        group = db.query(Group).filter_by(id=group_id).first()
        if group is None:
            raise Exception("No group with this ID found!")
        admin_role = db.query(GroupUser.role_in_group).filter_by(
            user_id=group.admin_id, group_id=group_id).first()
        user_role = db.query(GroupUser.role_in_group).filter_by(
            user_id=id_from_token, group_id=group_id).first()
        if admin_role.role_in_group == RoleEnum.ORGANIZER:
            if user_role is not None and user_role.role_in_group == RoleEnum.ORGANIZER:
                try:
                    db.add(
                        GroupUser(group_id=group_id,
                                  user_id=user_id,
                                  role_in_group=RoleEnum.ORGANIZER))
                    commit_with_check(db)
                except:
                    db.rollback()
                return AddOrganizer(ok=True, message="Users have been added!")

        return AddOrganizer(
            ok=True,
            message="Only admin with role ORGANIZER can add ORGANIZER!")
Ejemplo n.º 6
0
def add():
    """
    {
        "name":"Egg Burger",
        "price":10.00,
        "category":"hamburguer"
    }
    :return: {"result": "product has been created","status_code": 201}
    """
    try:
        data = request.get_json(force=True)
        if not data or not data.get("name") or not data.get("price"):
            return json_response(
                status_=StatusCodeEnum.HTTP_400_BAD_REQUEST,
                result=get_messages("PRODUCT_REQUIRED_FIELDS"),
            )
        product = Product(data)
        db_session.add(product)
        db_session.commit()
        return json_response(
            status_=StatusCodeEnum.HTTP_201_CREATED,
            result=get_messages("PRODUCT_CREATED"),
        )
    except ValueError as ex:
        db_session.rollback()
        raise ex
    finally:
        db_session.close()
Ejemplo n.º 7
0
 def mutate(self, info, data, id_from_token):
     a_level = GroupAccessEnum(data.access_level)
     role = RoleEnum(data.admin_role)
     new_group = Group(title=data.title,
                       about=data.about,
                       access_level=a_level,
                       date_creation=datetime.utcnow(),
                       date=data.date,
                       admin_id=id_from_token)
     try:
         db.add(new_group)
         commit_with_check(db)
     except:
         db.rollback()
     db.refresh(new_group)
     try:
         db.add(
             GroupUser(group_id=new_group.id,
                       user_id=id_from_token,
                       role_in_group=role))
         commit_with_check(db)
     except:
         db.rollback()
     return AddGroup(ok=True,
                     message="Group has been added!",
                     ID=new_group.id)
Ejemplo n.º 8
0
 def mutate(root, info, data, id_from_token):
     degree = DegreeEnum.NOTSTATED
     a_level = AccessLevelEnum(data.access_level)
     if data.degree is not None:
         degree = DegreeEnum(data.degree)
     new_item = Item(title=data.title,
                     owner_id=id_from_token,
                     about=data.about,
                     access_level=a_level,
                     list_id=data.list_id,
                     degree=degree,
                     status='FREE',
                     date_for_status=datetime.utcnow(),
                     date_creation=datetime.utcnow())
     try:
         db.add(new_item)
         commit_with_check(db)
     except:
         db.rollback()
     db.refresh(new_item)
     try:
         db.add(
             ItemPicture(item_id=new_item.id,
                         path_to_picture='items/item_0.png'))
         commit_with_check(db)
     except:
         db.rollback()
     return AddItem(ok=True, message="Item added!", ID=new_item.id)
Ejemplo n.º 9
0
def changeAccountPW():
	accountId = request.form['accountId']
	befPW = request.form['befPW']
	newPW = request.form['newPW']
	
	account_row = db_session.query(Account).filter_by(accountId=accountId).filter_by(isValid=1)\
					.with_entities(Account, func.password(befPW), func.password(newPW)).first()

	account = None
	if account_row:
		account, pw, nPW = account_row

	result = dict()
	if(account):
		print pw, account.password, nPW
		if len(befPW)>0 and pw != account.password :
			return jsonify({ "code": 302, "result": "Wrong password" })

		update_result = db_session.query(Account).filter_by(accountId=accountId)\
						.filter(Account.isValid>0).update({'password': nPW})
		try:
			db_session.commit()
		except exc.IntegrityError as e:
			db_session.rollback()
			return jsonify({ "code": 400, "result": "DB Error" })

		if(update_result==0):
			result = { "code": 401, "result": "No affected rows" }
		else:
			result = { "code": 200, "result": "Success" }	
	else :
		result["code"] = 301
		result["result"] = "No Such User"

	return jsonify(result)
Ejemplo n.º 10
0
def putTodayHappiness():
	params = dict()
	params["userId"] = request.form['userId']
	params["companyId"] = request.form['companyId']
	params["groupId"] = request.form['groupId']
	params["happyVal"] = request.form['happyVal']

	today = datetime.today()
	todayDate = today.strftime("%Y-%m-%d")

	todayHappiness = Happiness.query.filter_by(userId=params["userId"]).filter(Happiness.rdate > todayDate ).first()
	if todayHappiness!=None and todayHappiness.id!=None:
		result = { "code": 305, "result": "Duplicate today's entry", "happyVal": todayHappiness.happyVal }

	else:
		happiness = Happiness(**params)
		db_session.add(happiness)
		try:
			db_session.commit()
		except exc.IntegrityError as e:
			db_session.rollback()

		if(happiness.id==None):
			result = { "code": 400, "result": "DB Error" }
		else:
			result = { "code": 200, "result": "Success" }

	return jsonify(result)
Ejemplo n.º 11
0
	def user_init_func(row):

		if len(row['name'])==0: return None

		group_row = db_session.query(Group.groupId).filter(Group.companyId==companyId).filter(Group.name==row['groupName']).first()
		if group_row:
			groupId = group_row[0]
		elif len(row['groupName']) > 0 :
			newGroup = Group(companyId, row['groupName'])
			db_session.add(newGroup)
			try:
				db_session.commit()
			except exc.IntegrityError as e:
				db_session.rollback()

			if(newGroup.groupId==None):
				return None
			else:
				groupId = newGroup.groupId
		else :
			groupId = None

		# companyId, jobClass, groupId, email, accessKey, name, gender, birth, jobType, workYear, workMonth, jobTitle, jobTitleNo
		u = User(companyId, jobClass, groupId, row['email'], row['accessKey'], row['name'], row['gender'], row['birth'], row['jobType'], row['workYear'], row['workMonth'], row['jobTitle'], row['jobTitleNo'])
		return u
Ejemplo n.º 12
0
def setPushToken():
	userId = request.form['userId']
	pushTokenStr = request.form['pushToken']
	os = request.form['os']

	update_result = db_session.query(PushToken).filter_by(userId=userId).update({'pushToken': pushTokenStr, 'os' : os})
	try:
		db_session.commit()
	except exc.IntegrityError as e:
		db_session.rollback()

	if(update_result==None):
		result = { "code": 400, "result": "DB Error" }
	elif(update_result==0):
		pushToken = PushToken(userId, pushTokenStr, os)
		db_session.add(pushToken)
		try:
			db_session.commit()
		except exc.IntegrityError as e:
			db_session.rollback()

		result = { "code": 201, "result": "Success to insert" }
	else:
		result = { "code": 200, "result": "Success to update" }
	return jsonify(result)
Ejemplo n.º 13
0
def putPointFunc(userId, point, where, why):
	#이벤트 체크 - 이벤트 당첨자(=해당 날)이면 point 2배
	if amIinEvent(userId) == True :
		point = point * 2

	insert_row = PointHistory(userId, point, where, why)
	db_session.add(insert_row)

	if where.startswith("Praise"):
		myPoint_update_result = db_session.query(PointTotal).filter_by(userId=userId)\
			.update({PointTotal.pointTotal: PointTotal.pointTotal + point, PointTotal.pointPraise: PointTotal.pointPraise + point})
	elif where.startswith("Thanks"):
		myPoint_update_result = db_session.query(PointTotal).filter_by(userId=userId)\
			.update({PointTotal.pointTotal: PointTotal.pointTotal + point, PointTotal.pointThanks: PointTotal.pointThanks + point})
	elif where.startswith("Good") :
		myPoint_update_result = db_session.query(PointTotal).filter_by(userId=userId)\
			.update({PointTotal.pointTotal: PointTotal.pointTotal + point, PointTotal.pointGood: PointTotal.pointGood + point})
	else :
		myPoint_update_result = False

	if not (myPoint_update_result > 0) : #insert when no row
		insert_row2 = PointTotal(userId, request.form['companyId'], request.form['groupId'], point, where)
		db_session.add(insert_row2)

	try:
		db_session.commit()
	except exc.IntegrityError as e:
		db_session.rollback()

	if(insert_row.id==None or (not (myPoint_update_result > 0) )): # and insert_row2.inserted_primary_key==None)):
		return False
	else:
		return { "pointId" : insert_row.id, "point" : point }
Ejemplo n.º 14
0
def updateGroup():

	groupId = request.form.get('groupId')

	if groupId :
		group = Group.query.filter_by(groupId=groupId).first()
		if group :
			group.name = request.form['name']
			try:
				db_session.commit()
				result = { "code" : 200, "msg" : "Success" }	
			except exc.IntegrityError as err:
				result = { "code" : 301, "msg" : "IntegrityError" }	
		else :
			result = { "code" : 300, "msg" : "No such group" }
	else : # new group
		companyId = session['companyId']
		if not companyId:
			return jsonify({"code": 405, "result": "no company id"})
		elif request.form.get("name"):
			newGroup = Group(companyId, request.form.get("name"))
			db_session.add(newGroup)
			try:
				db_session.commit()
			except exc.IntegrityError as e:
				db_session.rollback()

			if(newGroup.groupId==None):
				result = { "code": 400, "result": "DB Error" }
			else:
				result = { "code": 200, "result": "Success", "groupId": newGroup.groupId }
		else :
			result = { "code": 302, "result": "No group name" }

	return jsonify(result)
Ejemplo n.º 15
0
def add_recipe():
    data = request.data
    recipe_data = json.loads(data.decode("utf-8"))

    recipe = Recipe(title=recipe_data['title'],
                    instructions=recipe_data['instructions'],
                    img=recipe_data['img'],
                    type=recipe_data['type'],
                    time=recipe_data['time'],
                    people=recipe_data['people'],
                    owner=recipe_data['owner'])
    db_session.add(recipe)

    for ingredient in recipe_data['ingredients']:
        ingredient = Ingredient(item=ingredient['item'],
                                quantity=ingredient['quantity'])
        db_session.add(ingredient)
        recipe.ingredients.append(ingredient)

    try:
        db_session.commit()
    except Exception:
        db_session.rollback()

    clear_sessions()

    return return_result(data=recipe_data)
Ejemplo n.º 16
0
def verticalization_remove(server_id):
    output = {
        'error': None,
        'error_message': None,
        'redirect_url': None,
    }
    try:
        form_json = request.json
        location_system = db_session.query(LocationSystem).filter(
            LocationSystem.id == server_id).first()
        campi = location_system.campuses
        for campus in campi:
            campus.vertical_name = None
            for building in campus.buildings:
                building.vertical_name = None
                for floor in building.floors:
                    floor.vertical_name = None
                    for zone in floor.zones:
                        zone.vertical_name = None
                        zone.max_occupation = -1
        db_session.commit()
        output['redirect_url'] = url_for('mod_cmx_server.details',
                                         server_id=server_id)
    except Exception as e:
        output['error'] = True
        output['error_message'] = str(e)
        traceback.print_exc()
        db_session.rollback()

    output = Response(json.dumps(output), mimetype='application/json')
    return output
Ejemplo n.º 17
0
def confirmMsg():
	msgId = request.form['msgId']
	msgType = request.form['msgType']
	userId = request.form['userId']

	update_result = db_session.query(Message).filter_by(id=msgId).filter_by(rUserId=userId).filter_by(msgType=msgType).filter_by(isRead=0)\
					.update({'isRead': 1, 'readTime': datetime.now()})
	try:
		db_session.commit()
	except exc.IntegrityError as e:
		db_session.rollback()

	if(update_result==None):
		result = { "code": 400, "result": "DB Error" }
	elif(update_result==0):
		result = { "code": 401, "result": "No affected rows" }
	else:
		result = { "code": 200, "result": "Success" }

		# 포인트 적립
		msgTypeStr = params["msgType"]=='1' and 'PraiseRcv' or 'ThanksRcv'
		point_result = putPointFunc(request.form['userId'], 200, msgTypeStr, msgId)
		if point_result!=False :
			result["pointId"] = point_result["pointId"]
			result["point"] = point_result["point"]

	return jsonify(result)
Ejemplo n.º 18
0
def add_to_db(object):
    try:
        db_session.add(object)
        db_session.flush()
        return True
    except sqlalchemy.exc.IntegrityError as err:
        print "IntegrityError"
        db_session.rollback()
        return False
Ejemplo n.º 19
0
def replyGoodPost():

	# 일일한도 체크
	# todayCount = myTodayCounts(request.form['userId'], "GoodReply");
	# if todayCount["Reply"] >= 10 :
		# return jsonify({ "code": 314, "result": "Limit today's reply good thing" })

	reply = GoodReply(request.form['postId'], request.form['userId'], request.form['text'])
	db_session.add(reply)
	try:
		db_session.commit()
	except exc.IntegrityError as e:
		db_session.rollback()

	if(reply.replyId==None):
		result = { "code": 400, "result": "DB Error" }
	else:
		result = { "code": 200, "result": "Success", "replyId": reply.replyId }

		# 대댓글 : 부모댓글아이디와 순서값 업데이트
		if request.form.get("parentRId") : reply.parentRId = request.form.get("parentRId")
		if request.form.get("parentRuserId") : reply.parentRuserId = request.form.get("parentRuserId")
		if request.form.get("rootRId") : reply.rootRId = request.form.get("rootRId")
		else : reply.rootRId = reply.replyId

		try:
			db_session.commit()
		except exc.IntegrityError as e:
			db_session.rollback()

		if request.form['userId']!=request.form['pUserId'] : #내가 글쓴이 아닌 경우에만.
		
			if request.form.get("replyBefore")==None or request.form.get("replyBefore")!='true' : #댓글 포인트는 최초 1회만 받을 수 있음.
				
				#하루 최대 500점(게시물10개)까지만 가능하게.
				todayDate = datetime.today().strftime("%Y-%m-%d")
				today_reply_point_cnt = db_session.query\
											.filter(PointHistory.userId==request.form['userId'])\
											.filter(PointHistory.where=='GoodReply')\
											.filter(PointHistory.rdate>todayDate)\
											.with_entities(func.count()).first()[0]
				if today_reply_point_cnt < 10:
					# 포인트 적립
					point_result = putPointFunc(request.form['userId'], 50, "GoodReply", reply.replyId)
					if point_result!=False :
						result["pointId"] = point_result["pointId"]
						result["point"] = point_result["point"]

				# 글쓴이 적립
				putPointFunc(request.form['pUserId'], 10, "GoodReplyRcv", reply.replyId)

			# 푸쉬알림.
			push_result = sendPush(request.form['pUserId'], 4, "작성한 게시물에 댓글이 등록 되었습니다.")
			result["push"] = push_result

	return jsonify(result)
Ejemplo n.º 20
0
def updateUser():

	userId = request.form.get('userId')

	if userId :
		user = User.query.filter_by(userId=userId).first()
		if user :
			user.email = request.form['email']
			user.name = request.form['name']
			user.groupId = request.form.get('groupId')
			user.jobClass = request.form.get('jobClass')
			if request.form.get('birthYear') and request.form.get('birthMonth'):
				user.birth = date( int(request.form['birthYear']), int(request.form['birthMonth']), 1 )
			user.jobType = request.form.get('jobType')
			user.workYear = request.form.get('workYear')
			user.workMonth = request.form.get('workMonth')
			user.jobTitle = request.form.get('jobTitle')
			user.jobTitleNo = request.form.get('jobTitleNo')
			try:
				db_session.commit()
				result = { "code" : 200, "msg" : "Success" }	
			except exc.IntegrityError as err:
				result = { "code" : 301, "msg" : "IntegrityError" }	
		else :
			result = { "code" : 300, "msg" : "No such user" }
	else : # new user
		companyId = session['companyId']
		if not companyId:
			return jsonify({"code": 405, "result": "no company id"})
		elif request.form.get("email"):
			userDict = { key: request.form.get(key) for key in ["email","groupId","name","jobClass","jobType","workYear","workMonth","jobTitle","jobTitleNo"] }
			userDict.update({"companyId":companyId})
			newUser = User(**userDict)

			accessKey = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(8))#ascii_letters / ascii_uppercase
			newUser.accessKey = accessKey
			if request.form.get('birthYear') and request.form.get('birthMonth'):
				birth = date( int(request.form['birthYear']), int(request.form['birthMonth']), 1 )
				newUser.birth = birth

			db_session.add(newUser)
			try:
				db_session.commit()
			except exc.IntegrityError as e:
				db_session.rollback()

			if(newUser.userId==None):
				result = { "code": 400, "result": "DB Error" }
			else:
				result = { "code": 200, "result": "Success", "userId": newUser.userId, "accessKey": newUser.accessKey }
		else :
			result = { "code": 302, "result": "No user email" }

	return jsonify(result)
Ejemplo n.º 21
0
def access():
	log = LogAccess(request.form['userId'])
	db_session.add(log)
	try:
		db_session.commit()
	except exc.IntegrityError as e:
		db_session.rollback()
	# if(log.id==None): #Select한번더 발생함.
		# result = { "code": 400, "result": "DB Error" }
	# else:
	result = { "code": 200, "result": "Success" }
	return jsonify(result)
Ejemplo n.º 22
0
def call_order(order):
    try:
        order.is_called = True
        db_session.add(order)
        db_session.commit()
        message = get_messages("CALL_ORDER_MESSAGE").format(order.id)
        make_conversion(message)
    except ValueError as ex:
        print(ex)
        db_session.rollback()
    finally:
        db_session.close()
Ejemplo n.º 23
0
 def mutate(self, info, item_id, id_from_token):
     item = db.query(Item).filter_by(id=item_id).first()
     if item is None:
         raise Exception("No item was found with this ID!")
     if item.owner_id != id_from_token:
         return DeleteItem(ok=False, message="Access denied!")
     # TODO если не работают Cascade, то нужно удалять в остальных таблицах вручную
     try:
         db.delete(item)
         commit_with_check(db)
     except:
         db.rollback()
     return DeleteItem(ok=True, message="Item deleted!")
Ejemplo n.º 24
0
 def mutate(self, info, group_id, id_from_token):
     group_id = int(group_id)
     group = db.query(Group).filter_by(id=group_id).first()
     if group is None:
         raise Exception("No group with this ID found!")
     if group.admin_id != id_from_token:
         return DeleteGroup(ok=False, message="Access denied!")
     try:
         db.delete(group)
         commit_with_check(db)
     except:
         db.rollback()
     return EditGroup(ok=True, message="Group was deleted!")
Ejemplo n.º 25
0
def sendMsg():
	params = dict()
	params["sUserId"] = request.form['userId']
	params["rUserId"] = request.form['rUserId']
	params["companyId"] = request.form['companyId']
	params["groupId"] = request.form['groupId']
	params["msgType"] = request.form['msgType'] # 1:칭찬, 2:감사
	params["msg"] = request.form['msg']

	#일일한도 체크
	todayCount = myTodayCounts(request.form['userId'], "Message");
	if params["msgType"]==1 and todayCount["Praise"] >= 3 :
		return jsonify({ "code": 310, "result": "Limit today's praise message" })
	elif params["msgType"]==2 and todayCount["Thanks"] >= 3 :
		return jsonify({ "code": 311, "result": "Limit today's thanks message" })

	message = Message(**params)
	db_session.add(message)
	try:
		db_session.commit()
	except exc.IntegrityError as e:
		db_session.rollback()
		return jsonify({ "code": 400, "result": "DB Error" })

	if(message.id==None):
		result = { "code": 400, "result": "DB Error" }
	else:
		result = { "code": 200, "result": "Success" }

		# 포인트 적립
		msgTypeStr = params["msgType"]=='1' and 'PraiseSend' or 'ThanksSend'
		point_result = putPointFunc(request.form['userId'], 100, msgTypeStr, message.id)
		if point_result!=False :
			result["pointId"] = point_result["pointId"]
			result["point"] = point_result["point"]

		# 상대방이 오늘 중 메시지 3번째 수신 확인 후, 그러면 푸쉬 보내기.
		today = datetime.today()
		todayDate = today.strftime("%Y-%m-%d")
		rUserTodayRcvCnt = db_session.query(Message).filter_by(rUserId=params["rUserId"]).filter_by(msgType=params["msgType"]).filter(Message.rdate > todayDate).count()
		if rUserTodayRcvCnt >= 3 :
			pushMsg = params["msgType"]=='1' and '칭찬 메시지가 왔습니다.' or '감사 메시지가 왔습니다.'
			push_result = sendPush(params["rUserId"], 11, '축하합니다! ' + pushMsg)
			result["push"] = push_result

		else : #보통 푸쉬.
			pushMsg = params["msgType"]=='1' and '칭찬 메시지가 왔습니다.' or '감사 메시지가 왔습니다.'
			push_result = sendPush(params["rUserId"], 1, pushMsg)
			result["push"] = push_result

	return jsonify(result)
Ejemplo n.º 26
0
def close():
    """
    {
        "products":[{"id":1,"quantity":2},{"id":2,"quantity":3},{"id":3,"quantity":4}]
    }
    :return: {"result": "Order 1 closed.","status_code": 201}
    """
    json_data = request.get_json(force=True)
    if not json_data:
        return json_response(status_=StatusCodeEnum.HTTP_400_BAD_REQUEST)
    try:
        order = Order(None)
        db_session.add(order)
        db_session.commit()
        if not order:
            return json_response(
                status_=StatusCodeEnum.HTTP_404_NOT_FOUND,
                result=get_messages("ORDER_NOT_FOUND"),
            )

        products_order = ProductsOrderSchema().dump(json_data)
        product_ids = list(map(lambda p: p.get("id"), products_order.get("products")))
        products = Product.query.filter(Product.id.in_(product_ids))
        if not products:
            return json_response(
                status_=StatusCodeEnum.HTTP_404_NOT_FOUND,
                result=get_messages("PRODUCT_NOT_FOUND"),
            )
        if order.dt_closing:
            return json_response(
                status_=StatusCodeEnum.HTTP_400_BAD_REQUEST,
                result=get_messages("ORDER_HAS_CLOSED").format(order.id),
            )
        if order.is_sentent:
            return json_response(
                status_=StatusCodeEnum.HTTP_400_BAD_REQUEST,
                result=get_messages("ORDER_HAS_SENTENT").format(order.id),
            )
        calc_order(products_order.get("products"), order, products)
        *_, money_ext_brl = money_format(order.price)
        return json_response(
            status_=StatusCodeEnum.HTTP_201_CREATED,
            result=get_messages("CLOSING_ORDER_MESSAGE_POPUP").format(
                order.id, money_ext_brl, order.quantity
            ),
        )
    except ValueError as ex:
        db_session.rollback()
        raise ex
    finally:
        db_session.close()
Ejemplo n.º 27
0
def verticalization(server_id):
    output = None
    try:
        server = db_session.query(CMXServer).filter(
            CMXServer.id == server_id).first()
        output = render_template("server/verticalization.html",
                                 object=server,
                                 deployment="On-premises")

    except Exception as e:
        traceback.print_exc()
        output = redirect(url_for('mod_error.home', message=str(e)))
        db_session.rollback()
    return output
Ejemplo n.º 28
0
def deletePartner():
	update_result = Company.query.filter_by(companyId=request.form['companyId']).update({'isValid':0})
	try:
		db_session.commit()
	except exc.IntegrityError as e:
		db_session.rollback()

	if(update_result==None):
		result = { "code": 400, "result": "DB Error" }
	elif(update_result==0):
		result = { "code": 401, "result": "No affected rows" }
	else:
		result = { "code": 200, "result": "Success" }	
	return jsonify(result)
Ejemplo n.º 29
0
def deleteGroup():
	update_result = Group.query.filter_by(groupId=request.form['groupId']).delete()
	try:
		db_session.commit()
	except exc.IntegrityError as e:
		db_session.rollback()

	if(update_result==None):
		result = { "code": 400, "result": "DB Error" }
	elif(update_result==0):
		result = { "code": 401, "result": "No affected rows" }
	else:
		result = { "code": 200, "result": "Success" }
	return jsonify(result)
Ejemplo n.º 30
0
 def mutate(self, info, from_user_id, id_from_token):
     fr = db.query(FR).filter_by(user_id_from=from_user_id,
                                 user_id_to=id_from_token).first()
     if fr is not None:
         try:
             db.delete(fr)
             commit_with_check(db)
         except:
             db.rollback()
         return RejectFriendRequest(
             ok=True, message="Friend request has been rejected!")
     else:
         return RejectFriendRequest(
             ok=False, message="Friend request hasn't been rejected!")
Ejemplo n.º 31
0
def log_command(command_category, message_id, room_id, person_id, person_email,
                created, room_type, message_text, deployment_status):
    #instantiate new spark_command

    try:
        spark_command_request = SparkCommandRequest(
            message_id, command_category, room_id, person_id, person_email,
            created, room_type, message_text, deployment_status)
        db_session.add(spark_command_request)
        db_session.commit()

    except Exception as e:
        db_session.rollback()
        traceback.print_exc()
        print("Error while trying to log the command")
Ejemplo n.º 32
0
    def mutate(root, info, data, id_from_token):
        a_level = AccessLevelEnum(data.access_level)
        new_list = Wishlist(title=data.title,
                            user_id=id_from_token,
                            about=data.about,
                            access_level=a_level)
        try:
            db.add(new_list)
            commit_with_check(db)
        except:
            db.rollback()
        db.refresh(new_list)

        lists = db.query(Wishlist).filter_by(user_id=id_from_token)
        return AddList(ok=True, message="Wishlist added!", user_lists=lists)
Ejemplo n.º 33
0
def delGoodPost():
	update_result = db_session.query(GoodPost).filter_by(postId=request.form['postId'])\
					.filter_by(userId=request.form['userId']).filter_by(isValid=1).update({'isValid': 0})
	try:
		db_session.commit()
	except exc.IntegrityError as e:
		db_session.rollback()

	if(update_result==None):
		result = { "code": 400, "result": "DB Error" }
	elif(update_result==0):
		result = { "code": 401, "result": "No affected rows" }
	else:
		result = { "code": 200, "result": "Success" }
	return jsonify(result)
Ejemplo n.º 34
0
def delete(server_id):
    output = None
    try:
        server = db_session.query(MerakiServer).filter(MerakiServer.id == server_id).first()
        if request.method == 'GET':
            output = render_template("server/meraki_server/delete.html", object=server, deployment="Cloud")
        else:
            server = db_session.query(MerakiServer).filter(MerakiServer.id == request.form["meraki_server_id"]).delete()
            output = redirect(url_for('mod_meraki_server.show'))
    except:
        traceback.print_exc()
        output = redirect(url_for('error'))
        db_session.rollback()

    return output
Ejemplo n.º 35
0
def add():
    output = {
        'error': None,
        'error_message': None,
        'redirect_url': None,
    }
    if request.method == 'GET':
        output = render_template("server/cmx_server/add.html",
                                 deployment="On-premises")

    else:
        try:
            if request.json:
                form_data = request.json
            else:
                form_data = request.form
            name = form_data["cmx_server_name"]
            url = form_data["cmx_server_url"]
            username = form_data["cmx_server_username"]
            password = form_data["cmx_server_password"]
            externally_accessible = form_data[
                "cmx_server_externally_accessible"] == 'True'
            active = form_data["cmx_server_active"] == 'True'

            cmx_server = CMXServer(name, url, username, password, active,
                                   externally_accessible)

            valid_server = validate_cmx_server(cmx_server)

            if valid_server:
                if active:
                    elect_active_server()

                db_session.add(cmx_server)
                db_session.commit()
                output['redirect_url'] = url_for('mod_cmx_server.show')
            else:
                output['error'] = True
                output[
                    'error_message'] = 'There was an error on the communication with the cmx_server. Please check the data'

        except Exception as e:
            output['error'] = True
            output['error_message'] = str(e)
            db_session.rollback()
        output = Response(json.dumps(output), mimetype='application/json')

    return output
Ejemplo n.º 36
0
 def mutate(self, info, to_user_id, id_from_token):
     if db.query(FS).filter_by(user_id_1=id_from_token,
                               user_id_2=to_user_id).first() is not None:
         SendFriendRequest(ok=False, message="You are already friends!")
     if db.query(FR).filter_by(user_id_from=id_from_token,
                               user_id_to=to_user_id).first() is not None:
         SendFriendRequest(
             ok=False,
             message="You have already sent friend request to this user!")
     try:
         db.add(FR(user_id_from=id_from_token, user_id_to=to_user_id))
         commit_with_check(db)
     except:
         db.rollback()
     return SendFriendRequest(ok=True,
                              message="Friend request has been sent!")
Ejemplo n.º 37
0
 def mutate(self, info, to_user_id, from_user_id, id_from_token):
     if id_from_token != int(from_user_id):
         return CancelFriendRequest(ok=False, message="Access denied!")
     fr = db.query(FR).filter_by(user_id_from=id_from_token,
                                 user_id_to=to_user_id).first()
     if fr is not None:
         try:
             db.delete(fr)
             commit_with_check(db)
         except:
             db.rollback()
         return CancelFriendRequest(
             ok=True, message="Friend request has been canceled!")
     else:
         return CancelFriendRequest(
             ok=True, message="Friend request hasn't been canceled!")
Ejemplo n.º 38
0
def uploadProfile():
	userId = request.form.get("userId")
	if userId==None :
		return jsonify({"code": 304, "result": "No user ID"})
	
	file = request.files['thumb']
	if file and allowed_file(file.filename):
		from werkzeug import secure_filename
		now = datetime.now()
		imgFilename = now.strftime("%y%m%d%H%M%S") + "_" + secure_filename(file.filename)
		# file.save( app.config['UPLOAD_FOLDER'] + '/' + imgFilename )

		from PIL import Image
		try:
			im = Image.open(file)
			
			width = 200
			imgW, imgH = im.size
			if imgW > width:
				height = int(width * (float(imgH) / float(imgW)))
				im.thumbnail((width, height), Image.ANTIALIAS)

			ext = imgFilename.rsplit('.', 1)[1]
			if ext=='jpg' or ext=='JPG': ext='JPEG'
			im.save(app.config['UPLOAD_FOLDER'] + '/' + imgFilename, ext.upper())

			thumbURL = 'http://oasis.kwig.co.kr/loadImage/' + imgFilename
			update_result = db_session.query(User).filter_by(userId=userId).update({'thumbURL': thumbURL})
			try:
				db_session.commit()
			except exc.IntegrityError as e:
				db_session.rollback()

			if(update_result==None):
				result = { "code": 400, "result": "DB Error" }
			elif(update_result==0):
				result = { "code": 401, "result": "No affected rows" }
			else:
				result = { "code": 200, "result": "Success", "imgURL": thumbURL }	

		except IOError:
			print "cannot create thumbnail"
			result = { "code": 500, "result": "File IO Error" }            

	else:
		result = { "code": 303, "result": "File Not Aloowed" }
	return jsonify(result)
Ejemplo n.º 39
0
 def mutate(self, info, from_user_id, id_from_token):
     fr = db.query(FR).filter_by(user_id_from=from_user_id,
                                 user_id_to=id_from_token).first()
     if (fr is not None) and \
             (db.query(FS).filter_by(user_id_1=id_from_token, user_id_2=from_user_id).first() is None):
         try:
             db.add(FS(user_id_1=from_user_id, user_id_2=id_from_token))
             db.add(FS(user_id_2=from_user_id, user_id_1=id_from_token))
             db.delete(fr)
             commit_with_check(db)
         except:
             db.rollback()
         return AcceptFriendRequest(
             ok=True, message="Friend request has been accepted!")
     else:
         return AcceptFriendRequest(
             ok=False, message="Friend request hasn't been accepted!")
Ejemplo n.º 40
0
 def mutate(self, info, urls, id_from_token):
     if len(urls) == 0:
         return RemovePictures(ok=False,
                               message="No URLs to delete pictures!")
     for pic in urls:
         item_path = db.query(ItemPicture).filter_by(
             path_to_picture=pic).first()
         item = db.query(Item).filter_by(id=item_path.item_id).first()
         if item.owner_id != id_from_token:
             raise Exception("Access denied!")
         if delete_file(Config.bucket, item_path.path_to_picture):
             try:
                 db.delete(item_path)
                 commit_with_check(db)
             except:
                 db.rollback()
     return RemovePictures(ok=True, message="Pictures have been deleted!")
Ejemplo n.º 41
0
 def mutate(self, info, friend_id, id_from_token):
     fr1 = db.query(FS).filter_by(user_id_1=id_from_token,
                                  user_id_2=friend_id).first()
     fr2 = db.query(FS).filter_by(user_id_2=id_from_token,
                                  user_id_1=friend_id).first()
     if fr1 is not None and fr2 is not None:
         try:
             db.delete(fr1)
             db.delete(fr2)
             commit_with_check(db)
         except:
             db.rollback()
         return RemoveFromFriends(ok=True,
                                  message="Friend has been removed :-(")
     else:
         return RemoveFromFriends(ok=True,
                                  message="Friend hasn't been removed :-)")
Ejemplo n.º 42
0
def editGoodPostReply():
	update_result = db_session.query(GoodReply).filter_by(replyId=request.form['replyId'])\
					.filter_by(userId=request.form['userId']).filter_by(isValid=1)\
					.update({ 'text': request.form['text'], 'rdate': datetime.now() })
	try:
		db_session.commit()
	except exc.IntegrityError as e:
		db_session.rollback()

	if(update_result==None):
		result = { "code": 400, "result": "DB Error" }
	elif(update_result==0):
		result = { "code": 401, "result": "No affected rows" }
	else:
		result = { "code": 200, "result": "Success" }

	return jsonify(result)
Ejemplo n.º 43
0
def unlikeGoodPost():
	GoodLike.query.filter_by(postId=request.form['postId']).filter_by(userId=request.form['userId']).delete()
	try:
		db_session.commit()
	except exc.IntegrityError as e:
		db_session.rollback()

	result = { "code": 200, "result": "Success" }
	# 포인트 적립취소
	point_result = putPointFunc(request.form['userId'], -10, "GoodLike", request.form['postId'])
	if point_result!=False :
		result["pointId"] = point_result["pointId"]
		result["point"] = point_result["point"]
	# 글쓴이 적립취소
	putPointFunc(request.form['pUserId'], -10, "GoodLikeRcv", request.form['postId'])

	return jsonify(result)
Ejemplo n.º 44
0
def updatePush():
	if not request.form.get('msg'):
		return jsonify({"code": 302, "result": "no message"})
	
	id = request.form.get('id')

	if id :
		push = PushMsg.query.filter_by(id=id).first()
		if push :
			push.msg = request.form.get('msg')
			push.startTime = request.form.get('startTime')
			push.isRepeat = request.form.get('isRepeat')=='true' and True or False
			push.repeatVal = request.form.get('repeatVal')
			try:
				db_session.commit()
				result = { "code" : 200, "msg" : "Success" }	
			except exc.IntegrityError as err:
				result = { "code" : 301, "msg" : "IntegrityError" }	
		else :
			result = { "code" : 300, "msg" : "No such push" }
	else : # new push
		companyId = session['companyId']
		if not companyId:
			return jsonify({"code": 405, "result": "no company id"})
		accountId = session.get('accountId')
		if not accountId:
			return jsonify({"code": 405, "result": "no account id"})
		
		pushDict = { key: request.form.get(key) for key in ["msg","startTime","isRepeat","repeatVal"] }
		pushDict.update({"companyId":companyId, "accountId":accountId})
		newPush = PushMsg(**pushDict)
		db_session.add(newPush)
		try:
			db_session.commit()
		except exc.IntegrityError as e:
			db_session.rollback()

		if(newPush.id==None):
			result = { "code": 400, "result": "DB Error" }
		else:
			result = { "code": 200, "result": "Success", "id": newPush.id }


	return jsonify(result)
Ejemplo n.º 45
0
def add():
    output = {
        'error': None,
        'error_message': None,
        'redirect_url': None,
    }

    if request.method == 'GET':
        output = render_template("server/meraki_server/add.html", deployment="Cloud")

    else:
        try:
            if request.json:
                form_data = request.json
            else:
                form_data = request.form

            fake_server = form_data["fake_server"] == 'True'

            if fake_server:
                meraki_server = MerakiServer(name="Meraki HQ", active=True, organization_id=None, network_id=None, api_key=None, demo_server=True, demo_server_url="http://live-map.meraki.com/clients")
                valid_server = validate_meraki_server(meraki_server)
                output['error_message'] = valid_server

                if valid_server:
                    db_session.add(meraki_server)
                    db_session.commit()
                    output['redirect_url'] = url_for('mod_meraki_server.show')
                else:
                    output['error'] = True
                    output[
                        'error_message'] = 'There was an error setting up the Meraki Demo Server. Please check the data'
            else:
                output['error'] = True
                output['error_message'] = 'Under construction'

        except Exception as e:
            output['error'] = True
            output['error_message'] = str(e)
            db_session.rollback()
        output = Response(json.dumps(output), mimetype='application/json')

    return output
Ejemplo n.º 46
0
    def insert(self, date, hour, direction, address, count, percent):
        print "%s, %s, %s, %s, %s, %s" % (date, hour, direction, address, count, percent)

        self.tdstamp = "%s %s:00.00" % (date, hour)
        self.direction = direction
        self.address = ip2int(address)
        self.flows = count
        self.percentTraffic = percent

        try:
            db_session.merge(self)
            db_session.flush()
            #db_session.commit()

        except AttributeError:
            traceback.print_exc(file=sys.stderr)

        except:
            traceback.print_exc(file=sys.stderr)
            db_session.rollback()
Ejemplo n.º 47
0
def edit(product_id):
    """
    {
        "name":"Burger Cabulozo",
        "price":20,55,
        "category":"FastFood"
    }
    :param product_id: Product identify
    :return: {"result": "product has been changed","status_code": 202}
    """
    try:
        product = Product.query.get(product_id)
        if not product:
            return json_response(
                status_=StatusCodeEnum.HTTP_404_NOT_FOUND,
                result=get_messages("PRODUCT_NOT_FOUND_COD").format(id),
            )
        data = request.get_json(force=True)
        if not data or not data.get("name") or not data.get("price"):
            return json_response(
                status_=StatusCodeEnum.HTTP_400_BAD_REQUEST,
                result=get_messages("PRODUCT_REQUIRED_FIELDS"),
            )
        product_schema = ProductSchema().dump(data).data
        if product_schema.get("name"):
            product.name = product_schema["name"]
        if product_schema.get("price"):
            product.price = data["price"]
        if product_schema.get("category"):
            product.category = data["category"]
        db_session.add(product)
        db_session.commit()
        return json_response(
            status_=StatusCodeEnum.HTTP_202_ACCEPTED,
            result=get_messages("PRODUCT_CHANGED"),
        )
    except ValueError as ex:
        db_session.rollback()
        raise ex
    finally:
        db_session.close()
Ejemplo n.º 48
0
 def mutate(root, info, user_data):
     if db.query(User).filter_by(email=user_data.email).first():
         return ClassicRegisterUser(
             ok=False,
             message="An account is already registered for this mailbox")
     code = random.randint(100000, 999999)
     e_host.send_email(user_data.email, "Confirm actions",
                       user_data.user_name, "other/fast_registration.txt",
                       code)
     new_user = User(email=user_data.email,
                     user_name=user_data.user_name,
                     password_hash=au.get_password_hash(code))
     try:
         db.add(new_user)
         commit_with_check(db)
     except:
         db.rollback()
     db.refresh(new_user)
     return ClassicRegisterUser(ok=True,
                                message="Registration done!",
                                ID=new_user.id)
Ejemplo n.º 49
0
def edit(server_id):
    output = None
    try:
        server = db_session.query(CMXServer).filter(
            CMXServer.id == server_id).first()
        if request.method == 'GET':
            output = render_template("server/cmx_server/edit.html",
                                     object=server,
                                     deployment="On-premises")
        else:
            server.name = request.form["cmx_server_name"]
            server.externally_accessible = request.form[
                "cmx_server_externally_accessible"] == 'True'
            db_session.commit()
            output = redirect(url_for('mod_cmx_server.show'))

    except Exception as e:
        traceback.print_exc()
        output = redirect(url_for('mod_error.home', message=str(e)))
        db_session.rollback()
    return output
Ejemplo n.º 50
0
    def insert(self, date, hour, direction, address, count, percent):
        print "%s, %s, %s, %s, %s, %s" % (date, hour, direction, address,
                                          count, percent)

        self.tdstamp = "%s %s:00.00" % (date, hour)
        self.direction = direction
        self.address = ip2int(address)
        self.flows = count
        self.percentTraffic = percent

        try:
            db_session.merge(self)
            db_session.flush()
            #db_session.commit()

        except AttributeError:
            traceback.print_exc(file=sys.stderr)

        except:
            traceback.print_exc(file=sys.stderr)
            db_session.rollback()
Ejemplo n.º 51
0
def putSurveyAnswers():
	userId = request.form['userId']

	answerDict = { key: request.form[key] for key in request.form if not key.startswith('sum') }
	answer = Answer(**answerDict)
	db_session.add(answer)
	try:
		db_session.commit()
	except exc.IntegrityError as e:
		db_session.rollback()
		return jsonify({ "code": 400, "result": "DB Error : Answer"})

	resultDict = { "userId" : userId, "answerId" : answer.id, "nth" : request.form['nth'] }
	user_result = db_session.query(User.jobClass, User.gender, User.birth, User.jobType, User.workYear, User.workMonth, User.jobTitleNo.label("jobTitle")).filter_by(userId=userId).first()
	if user_result!=None:
		resultDict.update({"jobClass":user_result[0],"gender":user_result[1],"jobType":user_result[3],"workYear":user_result[4],"workMonth":user_result[5],"jobTitle":user_result[6]})		
		if user_result[2]!=None:
			resultDict.update({"age": date.today().year - user_result[2].year + 1 })

	resultDict.update( { key: request.form[key] for key in request.form if key.startswith('sum') } )
	resultObj = Result(**resultDict)
	db_session.add(resultObj)
	try:
		db_session.commit()
	except exc.IntegrityError as e:
		db_session.rollback()
		return jsonify({ "code": 400, "result": "DB Error : Result"})

	if(resultObj==None or resultObj.id==None):
		result = { "code": 400, "result": "DB Error"}
	else:

		des = AESCipher('kit-works-lnp')
		key = des.encrypt(str(userId).encode('utf-8'))
		encKey = urllib.quote(key, safe='')

		result = { "code": 200, "result": "Success", "key" : encKey }

	return jsonify(result)
Ejemplo n.º 52
0
 def mutate(self, info, list_id, id_from_token, with_items):
     wlist = db.query(Wishlist).filter_by(id=list_id).first()
     if wlist is None:
         raise Exception("No wishlist with this ID found!")
     if wlist.user_id != id_from_token:
         return DeleteWishList(ok=False, message="Access denied!")
     if with_items:
         # TODO если не работают Cascade, то нужно удалять в остальных таблицах вручную
         try:
             db.delete(wlist)
             commit_with_check(db)
         except:
             db.rollback()
         return DeleteWishList(ok=True,
                               message="Wishlist deleted with items!")
     else:
         items_in_list = db.query(Item).filter_by(list_id=list_id).all()
         for item in items_in_list:
             item.list_id = None
         return DeleteWishList(
             ok=True,
             message="Wishlist was deleted! Items are in default wishlist")
Ejemplo n.º 53
0
def delGoodPostReply():
	update_result = db_session.query(GoodReply).filter_by(replyId=request.form['replyId'])\
					.filter_by(userId=request.form['userId']).filter_by(isValid=1).update({'isValid': 0})
	try:
		db_session.commit()
	except exc.IntegrityError as e:
		db_session.rollback()

	if(update_result==None):
		result = { "code": 400, "result": "DB Error" }
	elif(update_result==0):
		result = { "code": 401, "result": "No affected rows" }
	else:
		result = { "code": 200, "result": "Success" }

		# 포인트 적립취소
		point_result = putPointFunc(request.form['userId'], -50, "GoodReply", request.form['replyId'])
		if point_result!=False :
			result["pointId"] = point_result["pointId"]
			result["point"] = point_result["point"]
		# 글쓴이 적립취소
		putPointFunc(request.form['pUserId'], -50, "GoodReplyRcv", reply.replyId)

	return jsonify(result)
Ejemplo n.º 54
0
def updatePartner():

	companyId = request.form.get('companyId')

	if companyId :
		company = Company.query.filter_by(companyId=companyId).first()
		if company :
			company.name = request.form['name']
			company.categoryId = request.form.get('categoryId')
			company.thumbURL = request.form.get('thumbURL')
			company.func_100days_sdate = request.form.get('func_100days_sdate')
			company.func_100days_edate = request.form.get('func_100days_edate')
			company.func_100days = request.form.get('func_100days')=='true' and True or False
			company.func_survey = request.form.get('func_survey')=='true' and True or False
			company.func_happiness = request.form.get('func_happiness')=='true' and True or False

			if request.form.get('admin'):
				admin = Account.query.filter_by(email=request.form.get('admin')).first()
				if admin:
					admin.companyId = companyId
				else:
					newAccount = Account(companyId, request.form['admin'])
					db_session.add(newAccount)
			try:
				db_session.commit()
				result = { "code" : 200, "msg" : "Success" }	
			except exc.IntegrityError as err:
				result = { "code" : 301, "msg" : "IntegrityError" }	

		else :
			result = { "code" : 300, "msg" : "No such company" }
	else : # new company
		companyDict = { key: request.form.get(key) for key in ["name","categoryId","thumbURL","func_100days_sdate","func_100days_edate"] }
		newCompany = Company(**companyDict)
		newCompany.func_100days = request.form.get("func_100days")=='true' and True or False
		newCompany.func_survey = request.form.get("func_survey")=='true' and True or False
		newCompany.func_happiness = request.form.get("func_happiness")=='true' and True or False
		db_session.add(newCompany)
		try:
			db_session.commit()
		except exc.IntegrityError as e:
			db_session.rollback()

		if(newCompany.companyId==None):
			result = { "code": 400, "result": "DB Error" }
		else:

			if request.form.get('admin'):
				admin = Account.query.filter_by(email=request.form.get('admin')).first()
				if admin:
					admin.companyId = newCompany.companyId
					db_session.commit()
				else:
					newAccount = Account(newCompany.companyId, request.form['admin'])
					db_session.add(newAccount)
					try:
						db_session.commit()
					except exc.IntegrityError as e:
						db_session.rollback()

			result = { "code": 200, "result": "Success", "companyId": newCompany.companyId }

	return jsonify(result)
Ejemplo n.º 55
0
def internal_error(error):
    db_session.rollback()
    return render_template('500.html'),500
Ejemplo n.º 56
0
def internal_server_error(e):
    from app.database import db_session
    db_session.rollback()
    return render_template('500.html'), 500
Ejemplo n.º 57
0
def rcvMsgList():
	userId = request.form['userId']
	msgType = request.form['msgType']
	page = request.form.get("page")
	if page==None: page = 1
	else: page = int(page)
	pageCnt = 10

	today = datetime.today()
	
	condFilter = [1==1]
	if request.form.get("today"):
		condFilter.append(Message.rdate > today.strftime("%y-%m-%d"))

	result_rows = db_session.query(Message, User.name, User.thumbURL, User.jobTitle, Group.name)\
				.join(User, Message.sUserId==User.userId)\
				.join(Group, Message.groupId==Group.groupId)\
				.filter(Message.rUserId==userId).filter(Message.msgType==msgType)\
				.filter(*condFilter)\
				.order_by(Message.id.desc())[ (page-1)*pageCnt : page*pageCnt ]

	result = { "code": 200, "msgs": list(), "page": page }
	
	todayRcvCnt = 0;
	isCloseCnt = 0;
	todayDate = today.strftime("%y/%m/%d")

	nowReadMsgs = list()

	for row, userName, thumbURL, jobTitle, groupName in result_rows :
		rdateStr = row.rdate.strftime('%y/%m/%d %H:%I')
		rowJSON = row.tojson()
		rowJSON["rdate"] = rdateStr

		if rdateStr.find(todayDate)==0:
			todayRcvCnt += 1

		if row.isOpen==1:				#이미 공개된 발신자.
			rowJSON["userName"] = userName
			rowJSON["thumbURL"] = thumbURL
			rowJSON["jobTitle"] = jobTitle
			rowJSON["groupName"] = groupName
		else:							#아직 공개안된 발신자.
			isCloseCnt += 1
			rowJSON["userName"] = "******"
			rowJSON["thumbURL"] = ""
			rowJSON["jobTitle"] = "○○"
			rowJSON["groupName"] = "○○○○○"
			rowJSON["_userName"] = userName
			rowJSON["_thumbURL"] = thumbURL
			rowJSON["_jobTitle"] = jobTitle
			rowJSON["_groupName"] = groupName

		if row.isRead==0:
			nowReadMsgs.append(row) # 수신확인 메시지

		result["msgs"].append(rowJSON)
	result["todayRcvCnt"] = todayRcvCnt
	result["isCloseCnt"] = isCloseCnt

	# 메시지 발신인 공개로직 적용 (3번 이상 받으면 당일과 이전꺼 모두 공개)
	if todayRcvCnt >= 3:
		for msg in result["msgs"]:	# 비공개 발신자들 다시 공개처리 해줌.
			if msg["isOpen"]==False :
				msg["userName"] = msg["_userName"]
				msg["thumbURL"] = msg["_thumbURL"]
				msg["jobTitle"] = msg["_jobTitle"]
				msg["groupName"] = msg["_groupName"]

		if result["msgs"][0]!=None and result["msgs"][0]["isOpen"]==False : #공개안된 메시지가 있는 경우에만 업데이트 실시.
			update_result1 = db_session.query(Message).filter_by(rUserId=userId).filter_by(msgType=msgType).filter_by(isOpen=0).update({'isOpen': 1})

	# 포인트 적립
	## 메시지 포인트 적립 특수 (메시지 수신 3회부터는 이전포함 모두 400점)
	msgTypeStr = msgType=='1' and 'PraiseRcv' or 'ThanksRcv'
	totalPointGet = 0
	totalPointGetRegardlessEvent = 0#
	for idx, msg in enumerate(nowReadMsgs):
		
		rdateStr = msg.rdate.strftime('%y/%m/%d')
		if todayRcvCnt==0 or rdateStr!=todayDate : #다 지난 메시지 or 과거 메시지
			point = 200

		else : # 오늘 수신 메시지 있고 && 오늘 메시지이면,
			todayNowReadCnt = todayRcvCnt - len(nowReadMsgs)
			if 0 > 2 - todayNowReadCnt : #오늘 4번째 이상 부터 새로수신
				point = 400
			elif idx < 2 - todayNowReadCnt : # 1,2번째 메시지
				point = 200
			elif idx == 2 - todayNowReadCnt : # 3번째 메시지 + 1,2번째 메시지 점수 두배 = 보너스 400
				point = 400 + 400
			elif idx > 2 - todayNowReadCnt : # 4번째 이상
				point = 400

		point_result = putPointFunc(userId, point, msgTypeStr, msg.id)
		if point_result!=False:
			totalPointGetRegardlessEvent += point#
			totalPointGet += point_result["point"]

		# 푸쉬알림 - 발신자에게 수신했다는 알림.
		push_result = sendPush(msg.sUserId, 2, "상대방이 메시지를 확인하였습니다.")
		result["push"] = push_result


	result["totalPoint"] = totalPointGet
	result["totalPointGetRegardlessEvent"] = totalPointGetRegardlessEvent#
	result["totalPointCnt"] = len(nowReadMsgs)

	# 메시지 수신확인
	update_result2 = db_session.query(Message).filter_by(rUserId=userId).filter_by(msgType=msgType).filter_by(isRead=0)\
					.update({'isRead': 1, 'readTime': datetime.now()})
	try:
		db_session.commit()
	except exc.IntegrityError as e:
		db_session.rollback()


	return jsonify(result)
Ejemplo n.º 58
0
def putGoodPost():
	params = dict()
	params["postId"] = request.form.get('postId')
	params["userId"] = request.form['userId']
	params["companyId"] = request.form['companyId']
	params["groupId"] = request.form.get('groupId')
	params["isHidden"] = request.form.get('isHidden')
	params["text"] = request.form['text']

	# 일일한도 체크
	if params["postId"] is None :
		app.logger.error("check today")
		todayCount = myTodayCounts(request.form['userId'], "GoodPost");
		if todayCount["Post"] >= 1 :
			return jsonify({ "code": 312, "result": "Limit today's post good thing" })

	file = request.files.get('img')
	if file and allowed_file(file.filename):
		from werkzeug import secure_filename
		now = datetime.now()
		imgFilename = now.strftime("%y%m%d%H%M%S") + "_" + secure_filename(file.filename)
		
		# file.save( app.config['UPLOAD_FOLDER'] + '/' + imgFilename)

		from PIL import Image
		try:
			im = Image.open(file)

			width = 480
			imgW, imgH = im.size
			if imgW > width:
				height = int(width * (float(imgH) / float(imgW)))
				im.thumbnail((width, height), Image.ANTIALIAS)

			ext = imgFilename.rsplit('.', 1)[1]
			if ext=='jpg' or ext=='JPG': ext='JPEG'
			im.save(app.config['UPLOAD_FOLDER'] + '/' + imgFilename, ext.upper())

			params["imgURL"] = 'http://oasis.kwig.co.kr/loadImage/' + imgFilename

		except IOError:
			print "cannot create thumbnail"
			return jsonify({ "code": 500, "result": "File IO Error" })


	if params["postId"] is not None and len(params["postId"]) > 0:
		formData = { 'text': params["text"], 'isHidden': params["isHidden"] }
		if "imgURL" in params.keys() : formData["imgURL"] = params["imgURL"]

		update_result = db_session.query(GoodPost).filter_by(postId=params["postId"])\
					.filter_by(userId=request.form['userId']).update(formData)
		try:
			db_session.commit()
		except exc.IntegrityError as e:
			db_session.rollback()

		post = GoodPost(**params)

	else :
		try:
			params.pop("postId", None)
			post = GoodPost(**params)
			db_session.add(post)
			db_session.commit()
		except exc.IntegrityError as e:
			db_session.rollback()
			return jsonify({ "code": 402, "result": "Duplicate entry or No such entry" })

	if(post.postId is None):
		if result is None : result = { "code": 400, "result": "DB Error" }
	else:
		result = { "code": 200, "result": "Success", "postId": post.postId, "imgURL": params.get("imgURL") }

		if 'postId' not in params.keys() :#새로 등록한 때만.
			# 포인트 적립
			point_result = putPointFunc(request.form['userId'], 200, "GoodPost", post.postId)
			if point_result!=False :
				result["pointId"] = point_result["pointId"]
				result["point"] = point_result["point"]

	return jsonify(result)
Ejemplo n.º 59
0
db.ex("database/data.sql")

lc = sess.query(Course).all()                
ls = sess.query(Student).all()
for s in ls:
    tmp = lc[:]
    shuffle(tmp)
    i = 0
    while i < 3:
        d = {}
        d["cid"] = tmp.pop().cid
        d["sid"] = s.sid
        d["exam1"] = randint(50,100)
        d["exam2"] = randint(55,100)
        d["final"] = randint(55,100)
        en = Enrolled(**d)
        try: 
            if student.check_schedule(d["cid"], s.sid) == 0:
                sess.add(en)
                sess.commit()
            else:
                print "****SCHEDULE CONFLICT*****"
                i -= 1
        except:
            print "error"
            sess.rollback()
            i -= 1
        i += 1
            
        
Ejemplo n.º 60
0
def login():

	email = request.form['email']
	accessKey = request.form['accessKey']
	
	user = User.query.filter_by(email=email).filter_by(isValid=1).first()
	
	result = dict()
	if(user):
		if user.accessKey != accessKey :
			return jsonify({ "code": 302, "result": "Wrong Access key" })

		result["code"] = 200
		result["result"] = "Success"
		result["user"] = user.tojson()
		#result["user"] = json.loads(user.to_JSON())
		result["company"] = user.company.tojson()
		result["companyCategory"] = user.company.category.tojson()
		if user.group!=None: 
			result["group"] = user.group.tojson()

		today = datetime.now()
		todayDate = today.strftime("%Y-%m-%d")

		survey = db_session.query(Result).filter_by(userId=user.userId).filter_by(nth=1).count()
		if survey > 0 :
			result["didSurvey1"] = True
		todayHappiness = db_session.query(Happiness).filter_by(userId=user.userId).filter(Happiness.rdate>todayDate).first()
		if todayHappiness :
			result["todayHappinessVal"] = todayHappiness.happyVal
		

		# result["companyWorkers"] = list()
		# for worker in Company.workers:
		# 	#result["companyWorkers"].append( worker.tojson() )

		# 100일 지정된 경우, 이벤트 날짜 랜덤설정
		if user.company.func_100days == True and user.company.func_100days_sdate!=None and user.company.func_100days_edate!=None :			

			if str(user.company.func_100days_sdate) > todayDate : #시작전.
				stime = time.mktime(time.strptime(str(user.company.func_100days_sdate), '%Y-%m-%d'))
			else : #이미 시작함.
				stime = time.mktime(today.timetuple())
			 
			etime = time.mktime(time.strptime(str(user.company.func_100days_edate), '%Y-%m-%d'))
			
			for i in range(3):
				randProp = random.randint( 33 * i + 1, 33 * (i+1)) / 100.0 # 1~33, 34~66, 67~99
				ptime = stime + randProp * (etime - stime)
				eDate = time.strftime("%Y-%m-%d", time.localtime(ptime))
				
				eventDouble = EventDouble(userId=user.userId, nth=(i+1), eventDate=eDate)
				db_session.add(eventDouble)

			try:
				db_session.commit()
			except exc.IntegrityError as e:
				db_session.rollback()


		# 포인트 세팅
		point_row = PointTotal(user.userId, user.companyId, user.groupId, None, None)
		db_session.add(point_row)
		try:
			db_session.commit()
		except exc.IntegrityError as e:
			db_session.rollback()

	else :
		result["code"] = 301
		result["result"] = "No Such User"

	return jsonify(result)