def post(self):
        self.set_header("Content-Type", "application/json")
        self.set_header('Access-Control-Allow-Origin', '*')

        ret = {}

        uid                         = self.get_argument('uid', '')
        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)
        for_manager                 = self.get_argument('for_manager', '')

        # for address parameter
        address = self.get_argument('address', '')
        size    = self.get_argument('size', 25)
        kind    = self.get_argument('kind', 0)

        size = int(size)
        kind = int(kind)

        # convert parameters
        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
        isdirty                         = int(isdirty)


        # logging part
        mix = get_mixpanel()
        mongo_logger = get_mongo_logger()

        try:
            print uid
            if self.is_user_block(ret, uid) == True:
                return

            if appointment_type == BC.ONE_TIME_A_MONTH:
                self.set_status(Response.RESULT_OK)
                add_err_ko_message_to_response(ret, '4주 1회 서비스는 신규 예약을 지원하지 않습니다.')
                mongo_logger.debug('not booking one time a month', extra = { 'user_id' : uid })
                ret['err_code'] = '4038' # 임시 처리
                return

            if total_taking_time_in_minutes <= 0 or taking_time_in_minutes <= 0:
                self.set_status(Response.RESULT_OK)
                add_err_ko_message_to_response(ret, '클리닝 시간이 잘못 설정되었습니다.')
                ret['err_code'] = '9999' # 임시 처리
                return


            if total_taking_time_in_minutes >= 600:
                self.set_status(Response.RESULT_OK)
                add_err_ko_message_to_response(ret, '클리닝 가능 시간을 초과하였습니다. (최대 10시간) 이전 화면으로 돌아가 추가사항을 2개이하로 줄여주세요.')
                ret['err_code'] = '4036' # 임시 처리
                return

            scheduler = HMScheduler()

            session = Session()
            userdao = UserDAO()
            addrdao = AddressDAO()

            # add user address
            latlng = get_latlng_from_address(address)
            if len(latlng) > 1:
                latitude = latlng[0]
                longitude = latlng[1]

                geohash5 = get_geohash(latitude, longitude, 5)
                geohash6 = get_geohash(latitude, longitude, 6)
            else:
                latitude = 0.0
                longitude = 0.0
                geohash5 = ''
                geohash6 = ''

            key = userdao.get_user_salt_by_id(uid)[:16]
            crypto = aes.MyCrypto(key)

            encrypted_address = crypto.encodeAES(str(address))

            count = session.query(UserAddress).filter(UserAddress.user_id == uid).count()
            last_index = session.query(UserAddress).filter(UserAddress.user_id == uid).order_by(desc(UserAddress.user_addr_index)).first()

            index = 0
            if last_index != None:
                index = last_index.user_addr_index + 1

            new_address = UserAddress(user_id = uid, address = encrypted_address, size = size, kind = kind,
                                        user_addr_index = index, latitude = latitude, longitude = longitude,
                                        geohash5 = geohash5, geohash6 = geohash6)
            session.add(new_address)
            session.commit()

            # set default address index
            if count == 0:
                new_default_address = UserDefaultAddress(user_id=uid, address_idx=index)
                session.add(new_default_address)
            else:
                record = session.query(UserDefaultAddress).filter(UserDefaultAddress.user_id == uid).one()
                record.address_idx = index

            session.commit()

            address, geohash5, geohash6 = userdao.get_user_address(uid)
            _, size, kind = userdao.get_user_address_detail(uid)

            gu_id = addrdao.get_gu_id(address)

            if gu_id == '':
                raise Exception('gu id is incorrect')
                return

            available_schedules = scheduler.get_available_slots(gu_id = gu_id, geohash = geohash6, appointment_type = appointment_type, taking_time = total_taking_time_in_minutes,
                                                                prefer_women = True if master_gender == 1 else False,
                                                                have_pet = True if have_pet == 1 else False,
                                                                isdirty = True if isdirty == 1 else False,
                                                                user_id = uid)


            now = dt.datetime.now()
            if now.hour >= 17: # 7시 이후 라면 -> 5시로 변경 2016.06.03
                if for_manager == '': # 사용자 앱에서는 내일 예약 불가능
                    tomorrow = now + dt.timedelta(days=1)
                    tomorrow = dt.datetime.strftime(tomorrow, '%Y%m%d')
                    if tomorrow in available_schedules:
                        del available_schedules[tomorrow]

            for day in available_schedules:
                print '[', day, ']'
                print available_schedules[day]['by_time']
            # log to mixpanel
            mix.track(uid, 'request available schedule', {'time' : dt.datetime.now(), 'taking_time' : taking_time, 'additional_time' : additional_time, 'appointment_type' : appointment_type, 'have_pet' : have_pet, 'master_gender' : master_gender,'isdirty' : isdirty})

            # log to mongo
            mongo_logger.debug('request available schedule', extra = {'log_time' : dt.datetime.now(),  'user_id' : uid, 'taking_time' : taking_time, 'additional_time' : additional_time, 'appointment_type' : appointment_type, 'have_pet' : have_pet, 'master_gender' : master_gender,'isdirty' : isdirty})

            if len(available_schedules) > 0: # 가능한 날짜가 있다면
                ret['response'] = {'schedule' : available_schedules, 'first_date' : available_schedules.keys()[0] }
            else:
                add_err_message_to_response(ret, err_dict['err_not_available'])

                mongo_logger.debug('no masters', extra = {'log_time' : dt.datetime.now(), 'user_id' : uid, 'taking_time' : total_taking_time_in_minutes, 'gu_id' : gu_id, 'address' : address})
                user_name = userdao.get_user_name(uid)
                user_phone = userdao.get_user_phone(uid)
                send_jandi('BOOKING_NOT_AVAILABE', '예약 불가능 알림', '고객 : {} 전번 : {}'.format(user_name, user_phone),
                            '주기 : {}, 주소 : {}'.format(appointment_type, address))

            self.set_status(Response.RESULT_OK)
        except Exception, e:
            add_err_message_to_response(ret, err_dict['err_mysql'])
            self.set_status(Response.RESULT_SERVERERROR)
            print_err_detail(e)
            mongo_logger.error('error request available schedules', extra = {'user_id' : uid, 'err' : str(e)})
class ModifyAddressBookingHandler(tornado.web.RequestHandler):
    def post(self):
        ret = {}

        user_id = self.get_argument('user_id', '')
        index   = self.get_argument('index', '')
        address = self.get_argument('address', '')
        size    = self.get_argument('size', 0)
        kind    = self.get_argument('kind', 1)

        index = int(index)
        size = int(size)
        kind = int(kind)

        self.set_header("Content-Type", "application/json")
        self.set_header('Access-Control-Allow-Origin', '*')

        mongo_logger = get_mongo_logger()
        mix = get_mixpanel()

        try:
            session = Session()
            userdao = UserDAO()

            try:
                row = session.query(UserAddress) \
                            .filter(and_(UserAddress.user_id == user_id, UserAddress.user_addr_index == index)) \
                            .one()
            except NoResultFound, e:
                session.close()
                self.set_status(Response.RESULT_OK)
                add_err_message_to_response(ret, err_dict['err_no_record'])
                mongo_logger.error('failed to find address, no record', extra = {'err' : str(e)})
                return

            except MultipleResultsFound, e:
                session.close()
                self.set_status(Response.RESULT_OK)
                add_err_message_to_response(ret, err_dict['err_multiple_record'])
                mongo_logger.error('failed to find address, multiple record', extra = {'err' : str(e)})
                return

            latlng = get_latlng_from_address(address)
            if len(latlng) > 1:
                latitude = latlng[0]
                longitude = latlng[1]

                geohash5 = get_geohash(latitude, longitude, 5)
                geohash6 = get_geohash(latitude, longitude, 6)
            else:
                latitude = 0.0
                longitude = 0.0
                geohash5 = ''
                geohash6 = ''

            key = userdao.get_user_salt_by_id(user_id)[:16]
            crypto = aes.MyCrypto(key)

            encrypted_address = crypto.encodeAES(str(address))

            row.address = encrypted_address
            row.size = size
            row.kind = kind
            row.latitude = latitude
            row.longitude = longitude
            row.geohash5 = geohash5
            row.geohash6 = geohash6

            # modify booking info time and price
            now = dt.datetime.now().date()

            result = session.query(Booking) \
                            .filter(Booking.user_id == user_id) \
                            .filter(Booking.addr_idx == index) \
                            .filter(Booking.start_time >= now) \
                            .all()

            i = 0
            for row in result:
                if i == 0:
                    appointment_type = row.appointment_type
                    _, time, price, first_time = get_time_price(appointment_type, kind, size)

                new_duration = time
                org_duration = row.cleaning_duration

                new_price = price
                org_price = row.price

                # fix time
                row.estimated_end_time += dt.timedelta(minutes = (new_duration - org_duration))
                row.end_time = row.estimated_end_time

                # fix price
                row.price_with_task += (new_price - org_price)
                row.price = new_price

                row.cleaning_duration = new_duration

                i += 1

            session.commit()

            ret['response'] = Response.SUCCESS
            self.set_status(Response.RESULT_OK)

            print user_id, 'modify address successfully!'
            mix.track(user_id, 'modify address', {'time' : dt.datetime.now()})
            mongo_logger.debug('%s modify address' % user_id, extra = {'user_id' : user_id, 'address' : address, 'size' : size, 'kind' : kind})
class ModifyAddressHandler(tornado.web.RequestHandler):
    def post(self):
        ret = {}

        guid = self.get_argument('id', '')
        address = self.get_argument('address', '')
        size = self.get_argument('size', 0)
        kind = self.get_argument('kind', 1)

        self.set_header("Content-Type", "application/json")
        self.set_header('Access-Control-Allow-Origin', '*')

        mongo_logger = get_mongo_logger()
        mix = get_mixpanel()

        try:
            session = Session()
            userdao = UserDAO()

            default_addr_index = userdao.get_user_default_address_index(guid)

            try:
                row = session.query(UserAddress) \
                            .filter(and_(UserAddress.user_id == guid, UserAddress.user_addr_index == default_addr_index)) \
                            .one()
            except NoResultFound, e:
                session.close()
                self.set_status(Response.RESULT_OK)
                add_err_message_to_response(ret, err_dict['err_no_record'])
                mongo_logger.error('%s failed to find address, no record' %
                                   email,
                                   extra={'err': str(e)})
                return

            except MultipleResultsFound, e:
                session.close()
                self.set_status(Response.RESULT_OK)
                add_err_message_to_response(ret,
                                            err_dict['err_multiple_record'])
                mongo_logger.error(
                    '%s failed to find address, multiple record' % email,
                    extra={'err': str(e)})
                return

            latlng = get_latlng_from_address(address)
            if len(latlng) > 1:
                latitude = latlng[0]
                longitude = latlng[1]

                geohash5 = get_geohash(latitude, longitude, 5)
                geohash6 = get_geohash(latitude, longitude, 6)
            else:
                latitude = 0.0
                longitude = 0.0
                geohash5 = ''
                geohash6 = ''

            key = userdao.get_user_salt_by_id(guid)[:16]
            crypto = aes.MyCrypto(key)

            encrypted_address = crypto.encodeAES(str(address))

            row.address = encrypted_address
            row.size = size
            row.kind = kind
            row.latitude = latitude
            row.longitude = longitude
            row.geohash5 = geohash5
            row.geohash6 = geohash6

            session.commit()

            ret['response'] = Response.SUCCESS
            self.set_status(Response.RESULT_OK)

            print guid, 'add address successfully!'
            mix.track(guid, 'modify address', {'time': dt.datetime.now()})
            mongo_logger.debug('%s modify address' % guid,
                               extra={
                                   'user_id': guid,
                                   'address': address,
                                   'size': size,
                                   'kind': kind
                               })
    def add_new_address(self, user_id, address, size, kind, rooms=0, baths=0):
        try:
            session = Session()

            latlng = get_latlng_from_address(address)
            if len(latlng) > 1:
                latitude = latlng[0]
                longitude = latlng[1]

                geohash5 = get_geohash(latitude, longitude, 5)
                geohash6 = get_geohash(latitude, longitude, 6)
            else:
                latitude = 0.0
                longitude = 0.0
                geohash5 = ''
                geohash6 = ''

            key = self.get_user_salt_by_id(user_id)[:16]
            crypto = aes.MyCrypto(key)

            encrypted_address = crypto.encodeAES(str(address))

            count = session.query(UserAddress).filter(UserAddress.user_id == user_id) \
                            .count()
            last_index = session.query(UserAddress).filter(UserAddress.user_id == user_id) \
                        .order_by(desc(UserAddress.user_addr_index)).first()

            index = 0
            if last_index != None:
                index = last_index.user_addr_index + 1

            new_address = UserAddress(user_id=user_id,
                                      address=encrypted_address,
                                      size=size,
                                      kind=kind,
                                      rooms=rooms,
                                      baths=baths,
                                      user_addr_index=index,
                                      latitude=latitude,
                                      longitude=longitude,
                                      geohash5=geohash5,
                                      geohash6=geohash6)
            session.add(new_address)
            session.commit()

            # set default address index
            if count == 0:
                new_default_address = UserDefaultAddress(user_id=user_id,
                                                         address_idx=index)
                session.add(new_default_address)
            else:
                record = session.query(UserDefaultAddress) \
                                .filter(UserDefaultAddress.user_id == user_id) \
                                .one()
                record.address_idx = index

            session.commit()

            return index

        except Exception, e:
            print_err_detail(e)
Esempio n. 5
0
    def post(self):
        ret = {}

        guid = self.get_argument('id', '')
        address = self.get_argument('address', '')
        size = self.get_argument('size', 0)
        kind = self.get_argument('kind', 1)

        self.set_header("Content-Type", "application/json")
        self.set_header('Access-Control-Allow-Origin', '*')

        mongo_logger = get_mongo_logger()
        mix = get_mixpanel()

        try:
            session = Session()
            userdao = UserDAO()
            addressdao = AddressDAO()

            latlng = get_latlng_from_address(address)
            if len(latlng) > 1:
                latitude = latlng[0]
                longitude = latlng[1]

                geohash5 = get_geohash(latitude, longitude, 5)
                geohash6 = get_geohash(latitude, longitude, 6)
            else:
                latitude = 0.0
                longitude = 0.0
                geohash5 = ''
                geohash6 = ''

            key = userdao.get_user_salt_by_id(guid)[:16]
            crypto = aes.MyCrypto(key)

            encrypted_address = crypto.encodeAES(str(address))

            count = session.query(UserAddress).filter(
                UserAddress.user_id == guid).count()
            last_index = session.query(UserAddress).filter(
                UserAddress.user_id == guid).order_by(
                    desc(UserAddress.user_addr_index)).first()

            index = 0
            if last_index != None:
                index = last_index.user_addr_index + 1

            new_address = UserAddress(user_id=guid,
                                      address=encrypted_address,
                                      size=size,
                                      kind=kind,
                                      user_addr_index=index,
                                      latitude=latitude,
                                      longitude=longitude,
                                      geohash5=geohash5,
                                      geohash6=geohash6)
            session.add(new_address)
            session.commit()

            # set default address index
            if count == 0:
                new_default_address = UserDefaultAddress(user_id=guid,
                                                         address_idx=index)
                session.add(new_default_address)
            else:
                record = session.query(UserDefaultAddress).filter(
                    UserDefaultAddress.user_id == guid).one()
                record.address_idx = index

            session.commit()

            ret['response'] = Response.SUCCESS
            self.set_status(Response.RESULT_OK)

            print guid, 'add address successfully!'

            gu_name = addressdao.get_gu_name(address)

            mix.people_set(guid, {'address': address, 'gu': gu_name})
            mix.track(guid, 'add address', {
                'time': dt.datetime.now(),
                'address': address
            })
            mongo_logger.debug('add address',
                               extra={
                                   'log_time': dt.datetime.now(),
                                   'user_id': guid,
                                   'address': address,
                                   'size': size,
                                   'kind': kind
                               })

        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('failed to add address',
                               extra={
                                   'log_time': dt.datetime.now(),
                                   'user_id': guid,
                                   'address': address,
                                   'size': size,
                                   'kind': kind,
                                   'err': str(e)
                               })
    def post(self):
        self.set_header("Content-Type", "application/json")

        ret = {}

        address                     = self.get_argument('address', '')
        house_type                  = self.get_argument('house_type', 0)
        house_size                  = self.get_argument('house_size', 10)

        appointment_type            = self.get_argument('appointment_type', BC.ONE_TIME)
        additional_task             = self.get_argument('additional_task', 0)
        have_pet                    = self.get_argument('have_pet', 0)
        master_gender               = self.get_argument('master_gender', 0)
        isdirty                     = self.get_argument('isdirty', 0)

        # convert parameters
        house_type                      = int(house_type)
        house_size                      = int(house_size)
        appointment_type                = int(appointment_type)
        additional_task                 = int(additional_task)
        have_pet                        = int(have_pet)
        master_gender                   = int(master_gender) # 0 dont care 1 women
        isdirty                         = int(isdirty)

        if house_type == 0 or house_type == 5:
            house_type = 0
            if house_size == 8:
                house_size = 12
            elif house_size == 9:
                house_size = 20
            elif house_size == 10:
                house_size = 30
            elif house_size == 11:
                house_size = 40
            elif house_size == 12:
                house_size = 54
        elif house_type == 1 or house_type == 6:
            house_type = 1
            if house_size == 13:
                house_size = 7
            elif house_size == 14:
                house_size = 13
            elif house_size == 15:
                house_size = 19
            elif house_size == 16:
                house_size = 29
            elif house_size == 18:
                house_size = 54
        elif house_type == 2 or house_type == 7:
            house_type = 1
            if house_size == 19:
                house_size = 24
            elif house_size == 20:
                house_size = 34
            elif house_size == 21:
                house_size = 44
            elif house_size == 22:
                house_size = 54

        # logging part
        mix = get_mixpanel()
        mongo_logger = get_mongo_logger()

        try:
            scheduler = HMScheduler()

            userdao = UserDAO()
            addrdao = AddressDAO()

            print 'request available_schedules 11'
            print address
            print house_size
            print house_type
            print appointment_type
            print additional_task
            print have_pet
            print master_gender
            print isdirty
            print '--------------------------------'

            if additional_task == 64:
                additional_task = 0

            basic_address   = address.rsplit(',', 1)[0]
            detail_address  = address.rsplit(',', 1)[1]

            print "basic_address : ", basic_address
            print "detail_address : ", detail_address

            # get gu_id & geohash
            full_address = '%s %s' % (basic_address, detail_address)
            print "full_address : ", full_address
            lat, lng    = get_latlng_from_address(full_address)
            geohash6   = get_geohash(lat, lng, 6)
            gu_id       = addrdao.get_gu_id(basic_address)

            if gu_id == '':
                raise Exception('gu id is incorrect')

            tp_key, time, price, first_time = get_time_price(appointment_type, house_type, house_size)
            cleaning_time = time + first_time

            task_time, task_price = get_additional_task_time_price(additional_task, house_type, house_size)

            comb_key = '%s_%d_%d_%d' % (tp_key, additional_task, have_pet, master_gender)

            # total time and price
            total_taking_time_in_minutes = cleaning_time + task_time

            available_schedules = scheduler.get_available_slots(gu_id = gu_id, geohash = geohash6, appointment_type = appointment_type, taking_time = total_taking_time_in_minutes,
                                                                prefer_women = True if master_gender == 1 else False,
                                                                have_pet = True if have_pet == 1 else False,
                                                                isdirty = True if isdirty == 1 else False)


            now = dt.datetime.now()
            if now.hour >= 17: # 7시 이후 라면 -> 5시로 변경
                tomorrow = now + dt.timedelta(days=1)
                tomorrow = dt.datetime.strftime(tomorrow, '%Y%m%d')
                if tomorrow in available_schedules:
                    del available_schedules[tomorrow]


            #for day in available_schedules:
            #    print '[', day, ']'
            #    print available_schedules[day]['by_time']

            print '11 street log'
            # log to mixpanel
            #mix.track(uid, '11 request available schedule', {'time' : dt.datetime.now(), 'taking_time' : taking_time, 'additional_time' : additional_time, 'appointment_type' : appointment_type, 'have_pet' : have_pet, 'master_gender' : master_gender,'isdirty' : isdirty})

            # log to mongo
            mongo_logger.debug('11 request available schedule', extra = {'taking_time' : cleaning_time, 'additional_time' : task_time, 'appointment_type' : appointment_type, 'have_pet' : have_pet, 'master_gender' : master_gender,'isdirty' : isdirty})

            if len(available_schedules) > 0: # 가능한 날짜가 있다면
                ret['response'] = available_schedules
                ret['comb_key'] = comb_key
                print comb_key
            else:
                add_err_message_to_response(ret, err_dict['err_not_available'])

            self.set_status(Response.RESULT_OK)
        except Exception, e:
            add_err_message_to_response(ret, err_dict['err_mysql'])
            self.set_status(Response.RESULT_SERVERERROR)
            print_err_detail(e)
            mongo_logger.error('error 11 request available schedules', extra = {'err' : str(e)})