def post(self): self.set_header("Content-Type", "application/json") uid = self.get_argument('uid', '') taking_time = self.get_argument('taking_time', 25) additional_time = self.get_argument('additional_time', 10) appointment_type = self.get_argument('appointment_type', 0) have_pet = self.get_argument('have_pet', 0) master_gender = self.get_argument('master_gender', 0) isdirty = self.get_argument('isdirty', 0) # convert appointment_type = int(appointment_type) have_pet = int(have_pet) taking_time = int(taking_time) additional_time = int(additional_time) taking_time_in_minutes = taking_time * 6 additional_time_in_minutes = additional_time * 6 total_taking_time_in_minutes = taking_time_in_minutes + additional_time_in_minutes master_gender = int(master_gender) # 0 dont care 1 women 2 men isdirty = int(isdirty) ret = {} print 'recommend schedule' print 'taking time :', taking_time_in_minutes mongo_logger = get_mongo_logger() mongo_logger.debug('%s request recommendation' % uid, extra={ 'taking_time': taking_time, 'additional_time': additional_time, 'appointment_type': appointment_type, 'have_pet': have_pet, 'master_gender': master_gender, 'isdirty': isdirty }) mix = get_mixpanel() try: session = Session() userdao = UserDAO() addrdao = AddressDAO() masterdao = MasterDAO() holder = IntermediateValueHolder() # request id to group each individual bookings request_id = str(uuid.uuid4()) # get user's address and cover address to gu code address, geohash5, geohash6 = userdao.get_user_address(uid) gu_id = addrdao.get_gu_id(address) start_time_range_begin = 8 start_time_range_end = 18 # 똥집인 경우 3시간 추가됨. if isdirty == 1: if appointment_type == BC.ONE_TIME or appointment_type == BC.ONE_TIME_BUT_CONSIDERING: total_taking_time_in_minutes += 120 #get available homemaster's time table day by day schedule_by_date_list = masterdao.get_recommended_schedule( gu_id, have_pet, master_gender, appointment_type, geohash6, dt.datetime.now().date()) success, msg, store_key, search_keys, result = masterdao.find_master_by_score(schedule_by_date_list, \ gu_id, \ uid, \ appointment_type, \ None, \ start_time_range_begin, \ 0, start_time_range_end, \ 0, total_taking_time_in_minutes, \ geohash6, True) # if not successful if success != 'SUCCESS': print 'haha no recommendation.....' self.set_status(Response.RESULT_OK) ret['response'] = 'NoRecommendation' mongo_logger.error('have no recommendation', extra={'err': msg}) #add_err_message_to_response(ret, err_dict['err_hm_no_recommendation']) #self.write(json.dumps(ret)) return else: schedules = [] for row in result: s = {} s['date'] = row['date'] s['start_time'] = time_to_str(row['start_time']) s['end_time'] = time_to_str(row['end_time']) schedules.append(s) # 스케쥴이 이미 해당 날짜에 있다면, 있다고 표시하고 리턴함 num_schedules_on_dates = userdao.get_user_schedule_on_dates( uid, [ dt.datetime.strptime(str(s['date']), '%Y%m%d').date() for s in schedules ]) if num_schedules_on_dates > 0: print 'already have appointment on that days, no recommendation.....' holder.remove(store_key) for sk in search_keys: holder.remove(sk) self.set_status(Response.RESULT_OK) ret['response'] = 'NoRecommendation' mongo_logger.error( 'have no recommendation', extra={'err': 'already have cleaning on that day'}) #add_err_message_to_response(ret, err_dict['err_hm_no_recommendation']) #self.write(json.dumps(ret)) return mid = row['mid'] name, img_url, avg_rating = masterdao.get_master_name_img_and_average_rating( mid) search_keys_str = ','.join(search_keys) print 'search key string :', search_keys_str ret['response'] = { 'store_key': store_key, 'search_keys': search_keys_str, 'schedules': schedules, 'uid': uid, 'mid': row['mid'], 'name': name, 'img_url': img_url, 'avg_rating': str(float(avg_rating)) } mix.track(uid, 'recommend', { 'time': dt.datetime.now(), 'master_gender': master_gender }) mongo_logger.debug('%s got recommendation' % uid, extra={'user_id': uid}) self.set_status(Response.RESULT_OK) print uid, 'got recommendation ' self.set_status(Response.RESULT_OK) except Exception, e: session.rollback() print_err_detail(e) self.set_status(Response.RESULT_SERVERERROR) add_err_message_to_response(ret, err_dict['err_mysql']) mongo_logger.error('error occurred when make recommendation', extra={'err': str(e)}) # if error occur, then remove all keys holder.remove(store_key) for sk in search_keys: holder.remove(sk)
def post(self): self.set_header("Content-Type", "application/json") booking_id = self.get_argument('booking_id', '') new_master_id = self.get_argument('new_master_id', '') ret = {} try: session = Session() userdao = UserDAO() addrdao = AddressDAO() masterdao = MasterDAO() holder = IntermediateValueHolder() row = session.query(Booking).filter(Booking.id == booking_id).one() uid = row.user_id master_id_to_change = row.master_id org_start_time = row.start_time org_end_time = row.estimated_end_time appointment_type = 0 # 여기서는 1회 청소로 한다. 편집이기 때문에 have_pet = row.havepet master_gender = row.master_gender addr_idx = row.addr_idx taking_time_in_minutes = time_to_minutes(timedelta_to_time(org_end_time - org_start_time)) address, geohash5, geohash6 = userdao.get_user_address_by_index(uid, addr_idx) gu_id = addrdao.get_gu_id(address) dates = [int(dt.datetime.strftime(org_start_time, '%Y%m%d'))] time_range_begin = org_start_time.hour time_range_begin_min = org_start_time.minute time_range_end = org_start_time.hour time_range_end_min = org_start_time.minute print gu_id, dates print time_range_begin print time_range_begin_min print time_range_end print time_range_end_min print taking_time_in_minutes schedule_by_date_list = masterdao.get_master_schedule_by_dates(gu_id, have_pet, master_gender, dates, new_master_id) print schedule_by_date_list success, msg, store_key, search_keys, result = masterdao.find_master_by_score(schedule_by_date_list, \ gu_id, \ uid, \ appointment_type, \ dates, \ time_range_begin, \ time_range_begin_min, \ time_range_end, \ time_range_end_min, \ taking_time_in_minutes, \ geohash6) if success != 'SUCCESS': session.close() self.set_status(Response.RESULT_OK) add_err_message_to_response(ret, err_dict['err_no_hm_at_that_time']) #self.write(json.dumps(ret)) print booking_id, ' WAS NOT ... successfully updated to master_id : ', new_master_id return else: row.master_id = result[0]['mid'] if master_id_to_change != row.master_id: row.is_master_changed = 1 session.commit() holder.remove(store_key) for sk in search_keys: holder.remove(sk) ret['response'] = Response.SUCCESS self.set_status(Response.RESULT_OK) print booking_id, ' was successfully updated to master_id : ', new_master_id except Exception, e: session.rollback() print_err_detail(e) self.set_status(Response.RESULT_SERVERERROR) add_err_message_to_response(ret, err_dict['err_mysql'])
def post(self): self.set_header("Content-Type", "application/json") ret = {} uid = self.get_argument('uid', '') date = self.get_argument('date', dt.datetime.now()) start_time_range_begin = self.get_argument('range_begin', BC.START_TIME_RANGE_BEGIN) start_time_range_begin_min = self.get_argument('range_begin_min', 0) start_time_range_end = self.get_argument('range_end', BC.START_TIME_RANGE_END) start_time_range_end_min = self.get_argument('range_end_min', 0) appointment_type = self.get_argument('appointment_type', BC.ONE_TIME) taking_time = self.get_argument('taking_time', 25) first_added_time = self.get_argument('first_added_time', 0) additional_time = self.get_argument('additional_time', 10) have_pet = self.get_argument('have_pet', 0) master_gender = self.get_argument('master_gender', 0) isdirty = self.get_argument('isdirty', 0) # convert datetime date = dt.datetime.strptime(date, '%Y%m%d') start_time_range_begin = int(start_time_range_begin) start_time_range_begin_min = int(start_time_range_begin_min) start_time_range_end = int(start_time_range_end) start_time_range_end_min = int(start_time_range_end_min) appointment_type = int(appointment_type) taking_time = int(taking_time) first_added_time = int(first_added_time) additional_time = int(additional_time) taking_time_in_minutes = taking_time * 6 first_added_time_in_minutes = first_added_time * 6 additional_time_in_minutes = additional_time * 6 total_taking_time_in_minutes = taking_time_in_minutes + first_added_time_in_minutes + additional_time_in_minutes have_pet = int(have_pet) master_gender = int(master_gender) # 0 dont care 1 women 2 men isdirty = int(isdirty) print 'request schedule' print 'taking time :', taking_time_in_minutes mongo_logger = get_mongo_logger() mongo_logger.debug('%s request schedule' % uid, extra={ 'date': dt.datetime.strftime(date, '%Y%m%d'), 'start_time_range_begin': start_time_range_begin, 'start_time_range_end': start_time_range_end, 'taking_time': taking_time, 'additional_time': additional_time, 'appointment_type': appointment_type, 'have_pet': have_pet, 'master_gender': master_gender, 'isdirty': isdirty }) mix = get_mixpanel() try: session = Session() userdao = UserDAO() addrdao = AddressDAO() masterdao = MasterDAO() holder = IntermediateValueHolder() # request id to group each individual bookings request_id = str(uuid.uuid4()) # get user's address and cover address to gu code address, geohash5, geohash6 = userdao.get_user_address(uid) gu_id = addrdao.get_gu_id(address) # four consecutive appointment days to make booking if regular , otherwise just one day dates = [int(dt.datetime.strftime(date, '%Y%m%d'))] if appointment_type == BC.ONE_TIME_A_MONTH or appointment_type == BC.TWO_TIME_A_MONTH or appointment_type == BC.FOUR_TIME_A_MONTH: dates = [ int( dt.datetime.strftime( date + dt.timedelta(days=i * BC.DAYS_IN_A_WEEK * (4 / appointment_type)), '%Y%m%d')) for i in xrange(4) ] # 크리스마스 및 새해 임시로 막음. if date.date() == dt.date(2016, 2, 7) or date.date() == dt.date( 2016, 2, 8) or date.date() == dt.date( 2016, 2, 9) or date.date() == dt.date(2016, 2, 10): self.set_status(Response.RESULT_OK) add_err_ko_message_to_response(ret, '설날 연휴동안은, 예약이 불가능합니다.') self.write(json.dumps(ret)) return # 스케쥴이 이미 해당 날짜에 있다면, 있다고 표시하고 리턴함 num_schedules_on_dates = userdao.get_user_schedule_on_dates( uid, [dt.datetime.strptime(str(d), '%Y%m%d').date() for d in dates]) if num_schedules_on_dates > 0: self.set_status(Response.RESULT_OK) add_err_message_to_response(ret, err_dict['err_schedules_on_dates']) self.write(json.dumps(ret)) return # 똥집인 경우 3시간 추가됨. if isdirty == 1: if appointment_type == BC.ONE_TIME or appointment_type == BC.ONE_TIME_BUT_CONSIDERING: total_taking_time_in_minutes += 120 print 'gu_id', gu_id, have_pet, master_gender, dates #get available homemaster's time table day by day schedule_by_date_list = masterdao.get_master_schedule_by_dates( gu_id, have_pet, master_gender, dates) success, msg, store_key, search_keys, result = masterdao.find_master_by_score(schedule_by_date_list, \ gu_id, \ uid, \ appointment_type, \ dates, \ start_time_range_begin, \ start_time_range_begin_min, \ start_time_range_end, \ start_time_range_end_min, \ total_taking_time_in_minutes, \ geohash6) # if not successful if success != 'SUCCESS': self.set_status(Response.RESULT_OK) add_err_message_to_response(ret, err_dict['err_no_hm_at_that_time']) mix.track( uid, 'request schedule', { 'time': dt.datetime.now(), 'date': dt.datetime.strftime(date, '%Y%m%d'), 'start_time_range_begin': start_time_range_begin, 'start_time_range_begin_min': start_time_range_begin_min, 'start_time_range_end': start_time_range_end, 'start_time_range_end_min': start_time_range_end_min, 'taking_time': taking_time, 'additional_time': additional_time, 'appointment_type': appointment_type, 'have_pet': have_pet, 'master_gender': master_gender, 'isdirty': isdirty, 'status': 'no homemaster' }) print uid, 'was not able to find any homemasters....' else: schedules = [] for row in result: s = {} s['date'] = row['date'] s['start_time'] = time_to_str(row['start_time']) s['end_time'] = time_to_str(row['end_time']) schedules.append(s) mid = row['mid'] name, img_url, avg_rating = masterdao.get_master_name_img_and_average_rating( mid) search_keys_str = ','.join(search_keys) ret['response'] = { 'store_key': store_key, 'search_keys': search_keys_str, 'schedules': schedules, 'uid': uid, 'mid': row['mid'], 'name': name, 'img_url': img_url, 'avg_rating': str(float(avg_rating)) } print uid, 'successfully made booking requests...' mix.track( uid, 'request schedule', { 'time': dt.datetime.now(), 'date': dt.datetime.strftime(date, '%Y%m%d'), 'start_time_range_begin': start_time_range_begin, 'start_time_range_begin_min': start_time_range_begin_min, 'start_time_range_end': start_time_range_end, 'start_time_range_end_min': start_time_range_end_min, 'taking_time': taking_time, 'additional_time': additional_time, 'appointment_type': appointment_type, 'have_pet': have_pet, 'master_gender': master_gender, 'isdirty': isdirty, 'status': 'find homemaster' }) mongo_logger.debug('%s made booking requests' % uid, extra={'user_id': uid}) self.set_status(Response.RESULT_OK) except Exception, e: session.rollback() add_err_message_to_response(ret, err_dict['err_mysql']) self.set_status(Response.RESULT_SERVERERROR) print_err_detail(e) mongo_logger.error('error occurred when request schedule', extra={'err': str(e)}) # if error occur, then remove all keys holder.remove(store_key) for sk in search_keys: holder.remove(sk)
def post(self): self.set_header("Content-Type", "application/json") master_id = self.get_argument('master_id', '') ret = {} # 해당 마스터의 상태를 deactivate 시킨다. # 남아있는 일정이 있다면 모든 일정을 다른 마스터에게 양도 한다. try: session = Session() userdao = UserDAO() addrdao = AddressDAO() masterdao = MasterDAO() holder = IntermediateValueHolder() # deactivate master row = session.query(Master).filter(Master.id == master_id).one() row.active = 0 session.commit() # automatically assign that master's remain jobs to other masters masterdao = MasterDAO() request_ids = masterdao.get_distinct_req_ids(master_id) matched_booking_groups = [] unmatched_booking_groups = [] for req_id in request_ids: reqs = session.query(Booking, User, UserAddress) \ .join(User, User.id == Booking.user_id) \ .join(UserAddress, and_(Booking.user_id == UserAddress.user_id, Booking.addr_idx == UserAddress.user_addr_index)) \ .filter(Booking.request_id == req_id).filter(Booking.cleaning_status == BC.BOOKING_UPCOMMING) \ .order_by(Booking.start_time) \ .all() key = userdao.get_user_salt_by_id(reqs.User.id)[:16] crypto = aes.MyCrypto(key) dates = [] datetimes = [] max_taking_time_in_minutes = 0 for item in reqs: appointment_type = item.Booking.appointment_type address = crypto.decodeAES(item.UserAddress.address) geohash5 = item.UserAddress.geohash5 geohash6 = item.UserAddress.geohash6 start_time = item.Booking.start_time end_time = item.Booking.estimated_end_time # 최대 시간 기준으로 할당을 잡음 taking_time_in_minutes = time_to_minutes( timedelta_to_time(end_time - start_time)) if taking_time_in_minutes > max_taking_time_in_minutes: max_taking_time_in_minutes = taking_time_in_minutes gu_id = addrdao.get_gu_id(address) dates.append( int(dt.datetime.strftime(start_time, '%Y%m%d'))) datetimes.append(start_time) uid = item.Booking.user_id time_range_begin = datetimes[0].hour time_range_begin_min = datetimes[0].minute time_range_end = datetimes[0].hour time_range_end_min = datetimes[0].minute have_pet = item.Booking.havepet master_gedner = item.Booking.master_gender schedule_by_date_list = masterdao.get_master_schedule_by_dates( gu_id, have_pet, master_gender, dates) success, msg, store_key, search_keys, result = masterdao.find_master_by_score(schedule_by_date_list, \ gu_id, \ uid, \ appointment_type, \ dates, \ time_range_begin, \ time_range_begin_min, \ time_range_end, \ time_range_end_min, \ max_taking_time_in_minutes, \ geohash6) if success == 'SUCCESS': matched_booking_groups.append(req_id) matched_list = session.query(Booking) \ .filter(Booking.request_id == req_id) \ .filter(Booking.cleaning_status == BC.BOOKING_UPCOMMING) \ .all() for match in matched_list: match.master_id = result[0]['mid'] session.commit() holder.remove(store_key) for sk in search_keys: holder.remove(sk) else: unmatched_booking_groups.append(req_id) unmatched_list = session.query(Booking) \ .filter(Booking.request_id == req_id) \ .filter(Booking.cleaning_status == BC.BOOKING_UPCOMMING) \ .all() for unmatch in unmatched_list: print unmatch unmatch.master_id = None session.commit() ret['response'] = { 'matched_group': matched_booking_groups, 'unmatched_group': unmatched_booking_groups } self.set_status(Response.RESULT_OK) except NoResultFound, e: session.rollback() print_err_detail(e) self.set_status(Response.RESULT_SERVERERROR) add_err_message_to_response(ret, err_dict['err_no_record'])