def post(self):
            self.set_header("Content-Type", "application/json")

            ret = {}

            uid                     = self.get_argument('uid', '')
            search_keys             = self.get_argument('search_keys', '')
            store_key               = self.get_argument('store_key', '')
            
            price                   = self.get_argument('price', 0)
            price_with_task         = self.get_argument('price_with_task', 0)
            discounted_price        = self.get_argument('discounted_price', 0)
            promotion_code          = self.get_argument('promotion_code', '')
            
            laundry_apply_all       = self.get_argument('laundry_apply_all', 0) # -1 - 없앰, 0 - one time, 1 - all time

            # convert datetime
            price                   = int(price)
            price_with_task         = int(price_with_task)
            discounted_price        = int(discounted_price)
            laundry_apply_all       = int(laundry_apply_all)

            search_keys = search_keys.split(',')

            mongo_logger = get_mongo_logger()
            mix = get_mixpanel()

            try:
                session = Session()
                masterdao = MasterDAO()
                userdao = UserDAO()
                promotiondao = PromotionDAO()

                holder = IntermediateValueHolder()

                # request id to group each individual bookings
                request_id = str(uuid.uuid4())

                obj = holder.retrieve(store_key)
                print obj
                if obj == None:
                    self.set_status(Response.RESULT_OK)
                    add_err_message_to_response(ret, err_dict['err_booking_timeout'])
                    mix.track(uid, 'request timeout', {'time' : dt.datetime.now()})
                    mongo_logger.error('%s got timed out' % uid)
                    return  

                # retrieve all stored values
                uid                 = obj['user_id']
                mid                 = obj['master_id']
                dates               = obj['dates']
                time                = obj['time']
                appointment_type    = obj['appointment_type']
                additional_task     = obj['additional_task']

                taking_time         = obj['taking_time']
                first_added_time    = obj['first_added_time']
                additional_time     = obj['additional_time']
                total_time          = obj['total_time']
                master_gender       = obj['master_gender']
                have_pet            = obj['have_pet']
                isdirty             = obj['isdirty']

                # hasids to generate unique booking id
                now = dt.datetime.strftime(dt.datetime.now(), '%Y%m%d%H%M%S')
                hashids = Hashids(min_length = 16, salt = now + uid)

                # set tool info
                havetools = 1
                if additional_task >= 64:
                    havetools = 0

                card_idx = 0
                addr_idx = 0

                # get card and address idx
                addr_idx = userdao.get_user_default_address_index(uid)
                card_idx = userdao.get_user_default_card_index(uid)

                i = 1
                booking_ids = []
                start_time_list = []

                for date in dates: # 
                    print date, time
                    booking_id = hashids.encode(int(date + time.replace(':', '')))
                    print 'key', booking_id
                    master_id  = mid

                    date               = dt.datetime.strptime(date, '%Y%m%d')
                    dow                = date.date().weekday()
                    booking_time       = dt.time(hour = int(time.split(':')[0]), minute = int(time.split(':')[1]))

                    start_time         = dt.datetime.combine(date, booking_time)
                    estimated_end_time = start_time + dt.timedelta(minutes = total_time)
                    cleaning_duration  = taking_time

                    actual_price = 0
                    if i == 1: # 1 번째 클리닝
                        actual_price = price_with_task - discounted_price # 할인은 1회만 적용됨

                    else: # 나머지
                        actual_price = price
                        if havetools == 1:
                            additional_task = 0
                        else: 
                            additional_task = 64

                        if laundry_apply_all == 1:
                            additional_task += 4 # 빨래

                        isdirty = 0 # 첫째 이후에는 is dirty는 0
                        estimated_end_time = estimated_end_time - dt.timedelta(minutes = additional_time + first_added_time)

                    booking = Booking(id = booking_id, 
                                      request_id = request_id, 
                                      user_id = uid, 
                                      master_id = mid, 
                                      appointment_type = appointment_type, 
                                      appointment_index = i,
                                      dow = dow,
                                      booking_time = dt.datetime.now(),
                                      org_start_time = start_time,
                                      start_time = start_time,
                                      estimated_end_time = estimated_end_time,
                                      end_time = estimated_end_time, # update after homemaster finish their job
                                      cleaning_duration = cleaning_duration,
                                      additional_task = additional_task, 
                                      price = price,
                                      price_with_task = actual_price,
                                      charging_price = 0,
                                      card_idx = card_idx, 
                                      addr_idx = addr_idx, 
                                      havetools = havetools, 
                                      havepet = have_pet,
                                      laundry_apply_all = laundry_apply_all,
                                      is_dirty = isdirty,
                                      master_gender = master_gender,
                                      status = BC.BOOKING_UPCOMMING, 
                                      cleaning_status = BC.BOOKING_UPCOMMING,
                                      payment_status = BC.BOOKING_UNPAID_YET)
                    i += 1

                    session.add(booking) 
                    booking_ids.append(booking_id)
                    start_time_list.append(start_time)

                    #print 'booking_id', booking_id, 'was added..'

                # charge for first appointment date
                user_name = userdao.get_user_name(uid)
                if price_with_task - discounted_price <= 0:
                    ret_code = True
                    msg = ''
                else:
                    ret_code = True
                    msg = ''

                if ret_code:
                    session.commit()

                    # remove store_key and related_keys
                    holder.remove(store_key)
                    for sk in search_keys:
                        holder.remove(sk)

                    # promotion code 와 연결
                    if promotion_code != '':
                        promotiondao.set_promotion_code_status(promotion_code, 1, booking_ids[0], price_with_task)
                    
                    session.commit()

                    mix.track(uid, 'confirm booking', {'time' : dt.datetime.now(), 'appointment_type' : appointment_type, 'additional_task' : additional_task})
                    mongo_logger.debug('confirm booking', extra = {'user_id' : uid, 'master_id' : mid, 'booking_id' : booking_ids[0], 'start_time' : start_time_list[0]})

                    #ret['response'] = {'booking_ids' : booking_ids} # victor 요청으로 첫번째 
                    ret['response'] = booking_ids[0]
                    self.set_status(Response.RESULT_OK)

                    # notification to managers
                    send_booking_iphone(booking_ids[0])

                    appointment_type_text = ''
                    if appointment_type == BC.ONE_TIME or appointment_type == BC.ONE_TIME_BUT_CONSIDERING:
                        appointment_type_text = '1회'
                    elif appointment_type == BC.FOUR_TIME_A_MONTH:
                        appointment_type_text = '매주'
                    elif appointment_type == BC.TWO_TIME_A_MONTH:
                        appointment_type_text = '2주 1회'
                    elif appointment_type == BC.ONE_TIME_A_MONTH:
                        appointment_type_text = '4주 1회'

                    master_phone = masterdao.get_master_phone(mid)
                    send_alimtalk(master_phone, 'noti_manager_new', user_name, appointment_type_text)

                    try:
                        first_booking = session.query(Booking, User, MasterPushKey) \
                                                .join(User, Booking.user_id == User.id) \
                                                .outerjoin(MasterPushKey, Booking.master_id == MasterPushKey.master_id) \
                                                .filter(Booking.id == booking_ids[0]) \
                                                .one()
                    except NoResultFound, e:
                        session.close()
                        self.set_status(Response.RESULT_OK)
                        mongo_logger.debug('no first booking record', extra = {    'uid' : uid, 'mid' : mid,'appointment_type' : appointment_type, 'have_pet' : have_pet, 'master_gender' : master_gender, 'isdirty' : isdirty})
                        add_err_message_to_response(ret, err_dict['err_no_record'])
                        return                

                    except MultipleResultsFound, e:
                        session.close()
                        self.set_status(Response.RESULT_OK)
                        mongo_logger.debug('multiple first booking record', extra = {    'uid' : uid, 'mid' : mid, 'appointment_type' : appointment_type, 'have_pet' : have_pet, 'master_gender' : master_gender, 'isdirty' : isdirty})
                        add_err_message_to_response(ret, err_dict['err_multiple_record'])
                        return  
コード例 #2
0
    def add_upcoming(self):
        try:
            print '-' * 40
            print 'charge and add upcoming appointment started'
            current_time = dt.datetime.now()

            print current_time

            hour = current_time.hour
            minute = 30 if current_time.minute >= 30 else 0

            cron_time = current_time.replace(hour=hour,
                                             minute=minute,
                                             second=0,
                                             microsecond=0)
            print cron_time
            print '-' * 40

            userdao = UserDAO()
            session = Session()
            result = session.query(Booking) \
                                .filter(or_(Booking.appointment_type == BC.ONE_TIME_A_MONTH, Booking.appointment_type == BC.TWO_TIME_A_MONTH, Booking.appointment_type == BC.FOUR_TIME_A_MONTH)) \
                                .filter(func.date(Booking.start_time) == cron_time.date()) \
                                .filter(func.HOUR(Booking.start_time) == cron_time.time().hour) \
                                .filter(func.MINUTE(Booking.start_time) == cron_time.time().minute) \
                                .all()

            for row in result:
                try:
                    # add next appointment
                    booking_id = row.id
                    request_id = row.request_id

                    # 11번가의 경우 정해진 새로 추가 하지 않는다.
                    if row.source in [
                            '11st', 'auction', 'gmarket'
                    ] or row.user_type in ['11st', 'auction', 'gmarket']:
                        continue

                    # 전체 취소인 경우가 아닐 때만 새로 추가한다.
                    if self.is_cancelled_all(booking_id):
                        continue

                    org_master_id = self.get_org_master(request_id)

                    appointment_type = row.appointment_type
                    user_id = row.user_id
                    master_id = org_master_id if org_master_id != None else row.master_id
                    additional_task = row.additional_task
                    cleaning_duration = row.cleaning_duration
                    booking_time = dt.datetime.now()
                    price = row.price
                    price_with_task = row.price_with_task
                    card_idx = userdao.get_user_default_card_index(user_id)
                    addr_idx = row.addr_idx
                    message = row.message
                    trash_location = row.trash_location
                    laundry_apply_all = self.get_last_laundry_all(request_id)
                    enterhome = row.enterhome
                    enterbuilding = row.enterbuilding
                    havetools = row.havetools
                    havepet = row.havepet
                    is_dirty = row.is_dirty
                    master_gender = row.master_gender
                    wage_per_hour = row.wage_per_hour
                    status = row.status
                    cleaning_status = row.cleaning_status
                    routing_method = row.routing_method
                    source = row.source
                    user_type = row.user_type

                    actual_price = price
                    if havetools == 1:
                        additional_task = 0
                    else:
                        additional_task = 64
                        #actual_price += BC.VACCUM_CHARGE

                    if laundry_apply_all == 1:
                        additional_task += 4  # 빨래

                    print 'booking_id', booking_id
                    print 'user_id', user_id, 'master_id', master_id, 'price', price, 'request_id', request_id

                    # get next appointment info
                    start_time, estimated_end_time = self.get_next_appointment_date(
                        request_id, appointment_type)
                    appointment_index = self.get_next_appointment_index(
                        request_id, cleaning_status, appointment_type)

                    # add appointment
                    self.add_new_appointment(
                        request_id, master_id, user_id, appointment_type,
                        appointment_index, booking_time, start_time,
                        estimated_end_time, cleaning_duration, additional_task,
                        price, actual_price, card_idx, addr_idx, message,
                        trash_location, enterhome, enterbuilding,
                        routing_method, havetools, havepet, laundry_apply_all,
                        is_dirty, master_gender, wage_per_hour, source,
                        user_type)
                except Exception, e:
                    session.rollback()
                    print_err_detail(e)
                    continue

        except Exception, e:
            session.rollback()
            print_err_detail(e)
コード例 #3
0
    def post(self):
        self.set_header("Content-Type", "application/json")
        self.set_header('Access-Control-Allow-Origin', '*')

        ret = {}

        uid = self.get_argument('uid', '')
        search_keys = self.get_argument('search_keys', '')
        store_key = self.get_argument('store_key', '')

        price = self.get_argument('price', 0)
        price_with_task = self.get_argument('price_with_task', 0)

        wage_per_hour = self.get_argument('wage_per_hour', 0)
        address_index = self.get_argument('address_index', 0)

        discounted_price = self.get_argument('discounted_price', 0)
        promotion_code = self.get_argument('promotion_code', '')

        coupon_id = self.get_argument('coupon_id', '')
        coupon_discount_price = self.get_argument('coupon_discount_price', 0)

        laundry_apply_all = self.get_argument(
            'laundry_apply_all', 0)  # -1 - 없앰, 0 - one time, 1 - all time

        user_type = self.get_argument('user_type', 'unknown')

        # convert datetime

        # for ios fix
        if discounted_price != 0:
            discounted_price = discounted_price.replace('Optional(',
                                                        '').replace(')', '')

        price = int(price)
        price_with_task = int(price_with_task)
        discounted_price = int(discounted_price)
        coupon_discount_price = int(coupon_discount_price)
        laundry_apply_all = int(laundry_apply_all)
        wage_per_hour = int(wage_per_hour)

        print 'price_with_task', price_with_task
        print 'discounted_price', discounted_price

        search_keys = search_keys.split(',')

        mongo_logger = get_mongo_logger()
        mix = get_mixpanel()

        try:
            session = Session()
            userdao = UserDAO()
            masterdao = MasterDAO()
            promotiondao = PromotionDAO()
            addressdao = AddressDAO()
            coupondao = CouponDAO()

            holder = IntermediateValueHolder()

            # request id to group each individual bookings
            request_id = str(uuid.uuid4())

            obj = holder.retrieve(store_key)
            print obj
            if obj == None:
                self.set_status(Response.RESULT_OK)
                add_err_message_to_response(ret,
                                            err_dict['err_booking_timeout'])
                mix.track(uid, 'request timeout', {'time': dt.datetime.now()})
                mongo_logger.error('%s got timed out' % uid)
                return

            # retrieve all stored values
            uid = obj['user_id']
            mid = obj['master_id']
            dates = obj['dates']
            time = obj['time']
            appointment_type = obj['appointment_type']
            additional_task = obj['additional_task']
            org_additional_task = additional_task

            taking_time = obj['taking_time']
            first_added_time = obj['first_added_time']
            additional_time = obj['additional_time']
            total_time = obj['total_time']
            master_gender = obj['master_gender']
            have_pet = obj['have_pet']
            isdirty = obj['isdirty']

            is_b2b = userdao.is_b2b(uid)

            # hasids to generate unique booking id
            now = dt.datetime.strftime(dt.datetime.now(), '%Y%m%d%H%M%S')
            hashids = Hashids(min_length=16, salt=now + uid)

            # set tool info
            havetools = 1
            if additional_task >= 64:
                havetools = 0

            card_idx = 0
            addr_idx = 0

            # get card and address idx
            if is_b2b:
                addr_idx = address_index
            else:
                addr_idx = userdao.get_user_default_address_index(uid)

            card_idx = userdao.get_user_default_card_index(uid)

            i = 1
            booking_ids = []
            start_time_list = []

            for date in dates:  #
                print date, time
                booking_id = hashids.encode(int(date + time.replace(':', '')))
                print 'key', booking_id
                master_id = mid

                date = dt.datetime.strptime(date, '%Y%m%d')
                dow = date.date().weekday()
                booking_time = dt.time(hour=int(time.split(':')[0]),
                                       minute=int(time.split(':')[1]))

                start_time = dt.datetime.combine(date, booking_time)
                estimated_end_time = start_time + dt.timedelta(
                    minutes=total_time)
                cleaning_duration = taking_time

                actual_price = 0
                if i == 1:  # 1 번째 클리닝
                    actual_price = price_with_task - (
                        discounted_price + coupon_discount_price
                    )  # 할인은 1회만 적용됨

                else:  # 나머지
                    actual_price = price
                    if havetools == 1:
                        additional_task = 0
                    else:
                        additional_task = 64

                    if laundry_apply_all == 1:
                        additional_task += 4  # 빨래

                    isdirty = 0  # 첫째 이후에는 is dirty는 0
                    estimated_end_time = estimated_end_time - dt.timedelta(
                        minutes=additional_time + first_added_time)

                booking = Booking(
                    id=booking_id,
                    request_id=request_id,
                    user_id=uid,
                    master_id=mid,
                    appointment_type=appointment_type,
                    appointment_index=i,
                    dow=dow,
                    booking_time=dt.datetime.now(),
                    org_start_time=start_time,
                    start_time=start_time,
                    estimated_end_time=estimated_end_time,
                    end_time=
                    estimated_end_time,  # update after homemaster finish their job
                    cleaning_duration=cleaning_duration,
                    additional_task=additional_task,
                    price=price,
                    price_with_task=actual_price,
                    charging_price=0,
                    card_idx=card_idx,
                    addr_idx=addr_idx,
                    havetools=havetools,
                    havepet=have_pet,
                    laundry_apply_all=laundry_apply_all,
                    is_dirty=isdirty,
                    master_gender=master_gender,
                    user_type=user_type,
                    wage_per_hour=wage_per_hour,
                    status=BC.BOOKING_UPCOMMING,
                    cleaning_status=BC.BOOKING_UPCOMMING,
                    payment_status=BC.BOOKING_UNPAID_YET)
                i += 1

                session.add(booking)
                booking_ids.append(booking_id)
                start_time_list.append(start_time)

                #print 'booking_id', booking_id, 'was added..'

            # charge for first appointment date
            user_name = userdao.get_user_name(uid)

            if is_b2b:
                session.commit()

                # remove store_key and related_keys
                holder.remove(store_key)
                for sk in search_keys:
                    holder.remove(sk)

                send_jandi('NEW_BOOKING', '[b2b]새 예약 알림', 'b2b 고객님 예약완료',
                           user_name)

                # b2b용 알림톡 추가 필요

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

                mongo_logger.debug('b2b confirm booking',
                                   extra={
                                       'user_id': uid,
                                       'master_id': mid,
                                       'booking_id': booking_ids[0]
                                   })

                return

            charge_price = price_with_task - (discounted_price +
                                              coupon_discount_price)

            # 1주 1회면서, 이벤트 기간인 경우에는 결제 하지 않음
            import redis
            try:
                from utils.secrets import REDIS_HOST, REDIS_PORT, REDIS_PWD
            except ImportError:
                REDIS_HOST = 'localhost'
                REDIS_PORT = 6379
                REDIS_PWD = ''

            r = redis.Redis(host=REDIS_HOST,
                            port=REDIS_PORT,
                            password=REDIS_PWD)
            event_on = r.get('free_event')

            print event_on
            if appointment_type == 4 and event_on:
                charge_price = price_with_task - price

                # 1회 이벤트 고객임을 명시해야함
                # table 필요
                free_event = UserFreeEvent(booking_request_id=request_id,
                                           user_id=uid,
                                           datetime=dt.datetime.now())
                session.add(free_event)

            if charge_price <= 0:
                ret_code = True
                msg = ''
            else:
                ret_code, msg = request_payment(uid, user_name, booking_ids[0],
                                                charge_price, appointment_type)

            # 결제 정보 출력
            print user_name, ret_code, msg

            if ret_code:
                session.commit()

                # remove store_key and related_keys
                holder.remove(store_key)
                for sk in search_keys:
                    holder.remove(sk)

                # promotion code 와 연결
                if promotion_code != '':
                    promotiondao.set_promotion_code_status(
                        promotion_code, 1, booking_ids[0], price_with_task)

                if coupon_id != '':
                    coupondao.set_coupon_status(coupon_id, 1, booking_ids[0],
                                                price_with_task)

                # change status to paid
                try:
                    first_booking = session.query(Booking, User, MasterPushKey) \
                                            .join(User, Booking.user_id == User.id) \
                                            .outerjoin(MasterPushKey, Booking.master_id == MasterPushKey.master_id) \
                                            .filter(Booking.id == booking_ids[0]) \
                                            .one()
                except NoResultFound, e:
                    session.close()
                    self.set_status(Response.RESULT_OK)
                    mongo_logger.debug('no first booking record',
                                       extra={
                                           'uid': uid,
                                           'mid': mid,
                                           'appointment_type':
                                           appointment_type,
                                           'have_pet': have_pet,
                                           'master_gender': master_gender,
                                           'isdirty': isdirty
                                       })
                    add_err_message_to_response(ret, err_dict['err_no_record'])
                    return

                except MultipleResultsFound, e:
                    session.close()
                    self.set_status(Response.RESULT_OK)
                    mongo_logger.debug('multiple first booking record',
                                       extra={
                                           'uid': uid,
                                           'mid': mid,
                                           'appointment_type':
                                           appointment_type,
                                           'have_pet': have_pet,
                                           'master_gender': master_gender,
                                           'isdirty': isdirty
                                       })
                    add_err_message_to_response(
                        ret, err_dict['err_multiple_record'])
                    return
コード例 #4
0
    def charge(self):
        try:
            print '-' * 40
            print 'charge started'
            current_time = dt.datetime.now()

            print current_time

            hour = current_time.hour
            minute = 30 if current_time.minute >= 30 else 0

            cron_time = current_time.replace(hour=hour,
                                             minute=minute,
                                             second=0,
                                             microsecond=0)
            print cron_time
            print '-' * 40

            userdao = UserDAO()

            session = Session()
            result = session.query(Booking) \
                                .filter(or_(Booking.cleaning_status == BC.BOOKING_UPCOMMING, Booking.cleaning_status == BC.BOOKING_STARTED)) \
                                .filter(Booking.payment_status == BC.BOOKING_UNPAID_YET) \
                                .filter(func.date(Booking.start_time) == cron_time.date()) \
                                .filter(func.HOUR(Booking.start_time) == cron_time.time().hour) \
                                .filter(func.MINUTE(Booking.start_time) == cron_time.time().minute) \
                                .all()

            for row in result:
                try:
                    # payment
                    booking_id = row.id
                    user_id = row.user_id
                    price = int(row.price_with_task)
                    user_name = userdao.get_user_name(user_id)

                    devicetype = userdao.get_user_device_type(user_id)
                    if devicetype == 'None':  # 안드로이드 사용자만 자동 과금한다
                        continue

                    print booking_id, user_id, price, user_name, 'tried to pay'

                    ret_code, msg = request_payment(
                        user_id, user_name, booking_id, price,
                        row.appointment_type)  # 자동 결제 성공
                    if ret_code:
                        # paid 로 상태 변경이 필요함
                        card_idx = userdao.get_user_default_card_index(user_id)

                        tid = msg
                        row.card_idx = card_idx
                        row.tid = tid
                        row.payment_status = BC.BOOKING_PAID
                        #row.cleaning_status = BC.BOOKING_UPCOMMING
                        row.status = BC.BOOKING_PAID
                        print tid, 'success'
                    else:  # 자동 결제 실패
                        row.payment_status = BC.BOOKING_PAYMENT_FAILED
                        #row.cleaning_status = BC.BOOKING_UPCOMMING
                        row.status == BC.BOOKING_PAYMENT_FAILED
                        print msg, 'failed'

                    session.commit()

                except Exception, e:
                    session.rollback()
                    print_err_detail(e)
                    continue

        except Exception, e:
            session.rollback()
            print_err_detail(e)
コード例 #5
0
    def post(self):
        self.set_header("Content-Type", "application/json")
        self.set_header('Access-Control-Allow-Origin', '*')

        booking_id = self.get_argument('booking_id', '')
        reason_id = self.get_argument('reason_id', CANCEL_ADMIN)
        etc_reason = self.get_argument('etc_reason', '')
        no_fee = self.get_argument('no_fee', 0)

        reason_id = int(reason_id)

        print "reason_id : ", reason_id

        no_fee = int(no_fee)

        ret = {}

        mongo_logger = get_mongo_logger()
        mix = get_mixpanel()

        try:
            session = Session()

            try:
                row = session.query(Booking, Master, User, UserAddress) \
                             .join(Master, Booking.master_id == Master.id) \
                             .join(User, Booking.user_id == User.id) \
                             .join(UserDefaultAddress, User.id == UserDefaultAddress.user_id) \
                             .join(UserAddress, and_(UserAddress.user_id == UserDefaultAddress.user_id, UserAddress.user_addr_index == UserDefaultAddress.address_idx)) \
                             .filter(Booking.id == booking_id) \
                             .filter(Booking.cleaning_status == BC.BOOKING_UPCOMMING) \
                             .one()

            except NoResultFound, e:
                session.close()
                self.set_status(Response.RESULT_OK)
                add_err_message_to_response(ret,
                                            err_dict['err_no_entry_to_cancel'])
                return

            user_id = row.Booking.user_id

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

            # push to homemaster via sms
            master_id = row.Master.id

            master_phone = str(row.Master.phone)
            master_name = str(row.Master.name)
            username = str(crypto.decodeAES(row.User.name))
            userphone = str(crypto.decodeAES(row.User.phone))
            date = str(convert_datetime_format(row.Booking.start_time))
            addr = str(crypto.decodeAES(row.UserAddress.address))

            charge = 0
            new_status = BC.BOOKING_CANCELED_CHARGE

            request_id = row.Booking.request_id

            appointment_index = row.Booking.appointment_index
            appointment_time = row.Booking.start_time
            appointment_type = row.Booking.appointment_type
            current_status = row.Booking.status
            current_cleaning_status = row.Booking.cleaning_status
            current_payment_status = row.Booking.payment_status
            price = row.Booking.price_with_task
            source = row.Booking.source
            device_type = row.Booking.user_type
            now = dt.datetime.now()
            cancel_amount = 0

            diff_in_hours = (appointment_time - now).total_seconds() / 3600

            if diff_in_hours >= 24:
                charge = price * BC.BOOKING_CHARGE_RATE_NO
            elif 4 <= diff_in_hours < 24:
                charge = price * BC.BOOKING_CHARGE_RATE_30
            else:
                charge = price * BC.BOOKING_CHARGE_RATE_50

            if current_payment_status == BC.BOOKING_PAID:
                if no_fee == 1:  # 관리자가 선택하여 fee를 지불 할 수 있게 하기 위해서
                    charge = 0

                new_status = BC.BOOKING_CANCELED_REFUND

                partial = '1'
                if charge == 0:
                    partial = '0'

                is_event = session.query(UserFreeEvent) \
                                .filter(UserFreeEvent.booking_request_id == request_id) \
                                .first()

                is_event = True if is_event != None else False

                cancel_amount = int(price - charge)
                if cancel_amount > 0 and source == 'hm' and userdao.get_user_default_card_index(
                        user_id) != -1:
                    if not (is_event and appointment_index == 1):
                        ret_code, msg = cancel_payment(user_id, booking_id,
                                                       cancel_amount, partial)
                        if ret_code == False:
                            session.close()
                            self.set_status(Response.RESULT_OK)
                            add_err_ko_message_to_response(ret, msg)
                            #self.write(json.dumps(ret))
                            return
                    else:
                        # 결제 필요
                        # 취소에 대한 결제 필요
                        partial = '0'
                        cancel_amount = row.Booking.price_with_task - row.Booking.price
                        if cancel_amount > 0:
                            cancel_payment(user_id, booking_id, cancel_amount,
                                           partial)

                        complete_count = session.query(Booking) \
                                .filter(Booking.request_id == request_id) \
                                .filter(Booking.cleaning_status == 2) \
                                .count()

                        print complete_count, row.Booking.cleaning_status
                        if complete_count < 9 and row.Booking.cleaning_status == 2:
                            ret_code, msg = request_payment(
                                user_id, username, booking_id, price,
                                appointment_type)
                            if ret_code == False:
                                row.Booking.payment_status = BC.BOOKING_PAYMENT_FAILED

            else:  # cancel charge price
                print 'cancel charge'
                charging_price = int(charge)
                if charging_price > 0 and source == 'hm' and userdao.get_user_default_card_index(
                        user_id) != -1 and no_fee == 0:
                    print user_id, username, booking_id, charging_price, appointment_type

                    ret_code, msg = request_payment(user_id, username,
                                                    booking_id, charging_price,
                                                    appointment_type)
                    if ret_code == False:
                        new_status = BC.BOOKING_PAYMENT_FAILED

            #row.Booking.modified_date   = now
            row.Booking.charging_price = int(charge)
            row.Booking.status = new_status
            row.Booking.cleaning_status = BC.BOOKING_CANCELED
            row.Booking.payment_status = new_status

            appointment_type_text = ''
            if appointment_type == BC.ONE_TIME or appointment_type == BC.ONE_TIME_BUT_CONSIDERING:
                appointment_type_text = '1회'
            elif appointment_type == BC.FOUR_TIME_A_MONTH:
                appointment_type_text = '매주'
            elif appointment_type == BC.TWO_TIME_A_MONTH:
                appointment_type_text = '2주 1회'
            elif appointment_type == BC.ONE_TIME_A_MONTH:
                appointment_type_text = '4주 1회'

            #sms_sender = SMS_Sender()
            #text = BOOKING_CANCEL_TEXT % (username, userphone, master_name, date)
            #print sms_sender.send_for_manager(sender = MAIN_CALL, mtype = 'sms', to = MANAGERS_CALL, subject = BOOKING_TEXT_SUBJECT, text = text)
            #for manager_phone in MANAGERS_CALL.split(','):
            #    send_alimtalk(manager_phone, 'noti_manager_cancel', username, date, appointment_type_text)

            cancel_reasons = []
            cancel_reasons.append('지금은 서비스가 필요하지 않아요')
            cancel_reasons.append('집에 없어서 문을 열어드릴 수가 없어요')
            cancel_reasons.append('시간이 마음에 들지 않아요')
            cancel_reasons.append('클리닝을 잊고 있었네요')
            cancel_reasons.append('원하는 홈마스터가 아니에요')
            cancel_reasons.append('기타')
            cancel_reasons.append('이사가요')
            cancel_reasons.append('기타')
            cancel_reasons.append('관리자가 취소 했습니다')

            cancel_reason = cancel_reasons[reason_id]
            if cancel_reason == '기타':
                cancel_reason += ' ' + etc_reason
            elif reason_id == CANCEL_ADMIN:
                cancel_reason += ', 관리자 메모 : ' + etc_reason

            send_jandi(
                'NEW_BOOKING', "취소 알림", username + ' 고객님 취소함',
                '{}, {}, 사유 : {}'.format(date, appointment_type_text,
                                         cancel_reason))
            print 'jandi notification for cancel...'

            master_pushkey = masterdao.get_master_pushkey(master_id)
            #master_name = masterdao.get_master_name(master_id)
            #master_phone   = masterdao.get_master_phone(master_id)

            send_booking_canceled('android', [master_pushkey], booking_id,
                                  date, username)

            content = '''{} 홈마스터님
예약이 1회 취소 되었습니다.

고객 : {}
주기 : {}
날짜 : {}'''.format(master_name, username, appointment_type_text, date)

            message_sender = MessageSender()
            message_sender.send([master_phone], '예약 1회 취소 알림', content)

            print 'master_pushkey', master_pushkey
            print booking_id, date

            #send_alimtalk(master_phone, 'noti_manager_cancel', username, date, appointment_type_text)
            # adjust appointment index
            index_result = session.query(Booking).filter(
                Booking.request_id == request_id).filter(
                    Booking.appointment_index > appointment_index).all()
            for index_row in index_result:
                index_row.appointment_index -= 1

            coupondao = CouponDAO()
            coupondao.cancel_coupon_usage(booking_id)

            CANCEL = 0
            cancel_reason = CancelReason(booking_id=booking_id,
                                         user_id=user_id,
                                         reason_id=reason_id,
                                         etc_reason=etc_reason,
                                         kind=CANCEL,
                                         cancel_time=dt.datetime.now())
            session.add(cancel_reason)

            session.commit()

            mix.track(
                user_id, 'cancel', {
                    'time': dt.datetime.now(),
                    'reason_id': reason_id,
                    'etc_reason': etc_reason,
                    'cancel_amount': cancel_amount
                })
            mongo_logger.debug('%s was canceled' % booking_id,
                               extra={
                                   'user_id': user_id,
                                   'booking_id': booking_id,
                                   'cancel_amount': cancel_amount
                               })

            ret['response'] = Response.SUCCESS

            self.set_status(Response.RESULT_OK)
コード例 #6
0
    def post(self):
            self.set_header("Content-Type", "application/json")

            ret = {}

            store_key               = self.get_argument('store_key', '')
            uid                     = self.get_argument('uid', '')
            mid                     = self.get_argument('mid', '')
            appointment_type        = self.get_argument('appointment_type', BC.ONE_TIME)
            additional_task         = self.get_argument('additional_task', 0)
            discounted_price        = self.get_argument('discounted_price', 0)
            price                   = self.get_argument('price', 0)
            price_with_task         = self.get_argument('price_with_task', 0)
            promotion_code          = self.get_argument('promotion_code', '')
            have_pet                = self.get_argument('have_pet', 0)
            search_keys             = self.get_argument('search_keys', '')
            master_gender           = self.get_argument('master_gender', 0)
            isdirty                 = self.get_argument('isdirty', 0)
            first_added_time        = self.get_argument('first_added_time', 0)
            additional_time         = self.get_argument('additional_time', 10)
            laundry_apply_all       = self.get_argument('laundry_apply_all', 0) # -1 - 없앰, 0 - one time, 1 - all time

            # convert datetime
            appointment_type        = int(appointment_type)
            additional_task         = int(additional_task)
            price                   = int(price)
            price_with_task         = int(price_with_task)
            discounted_price        = int(discounted_price)
            have_pet                = int(have_pet)
            master_gender           = int(master_gender)
            isdirty                 = int(isdirty)
            laundry_apply_all       = int(laundry_apply_all)


            first_added_time        = int(first_added_time)
            additional_time         = int(additional_time)
            first_added_time_in_minutes   = first_added_time * 6
            additional_time_in_minutes    = additional_time * 6 

            print first_added_time, additional_time

            search_keys = search_keys.split(',')


            havetools = 1
            if additional_task >= 64:
                havetools = 0

            mongo_logger = get_mongo_logger()

            mongo_logger.debug('%s request booking' % uid, extra = {    'uid' : uid, 'mid' : mid,
                                                                        'appointment_type' : appointment_type, 
                                                                        'have_pet' : have_pet, 'master_gender' : master_gender,
                                                                        'isdirty' : isdirty})

            mix = get_mixpanel()

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

                holder = IntermediateValueHolder()

                card_idx = 0
                addr_idx = 0

                # get card and address idx
                addr_idx = userdao.get_user_default_address_index(uid)
                card_idx = userdao.get_user_default_card_index(uid)

                # hasids to generate unique booking id
                now = dt.datetime.strftime(dt.datetime.now(), '%Y%m%d%H%M%S')
                hashids = Hashids(min_length = 16, salt = now + uid)
                print 'salt : ', now + uid

                # request id to group each individual bookings
                request_id = str(uuid.uuid4())

                obj = holder.retrieve(store_key)
                if obj == None:
                    session.close()
                    self.set_status(Response.RESULT_OK)
                    add_err_message_to_response(ret, err_dict['err_booking_timeout'])
                    mix.track(uid, 'request timeout', {'time' : dt.datetime.now()})
                    mongo_logger.error('%s got timed out' % uid)
                    self.write(json.dumps(ret)) 
                    return  

                i = 1
                booking_ids = []
                start_time_list = []

                obj = sorted(obj, key = lambda x: x['date'])

                for item in obj:
                    print item['date']
                    booking_id = hashids.encode(int(item['date'] + time_to_str(item['start_time'])))
                    master_id = item['mid']

                    dow                = dt.datetime.strptime(item['date'], '%Y%m%d').date().weekday()
                    start_time         = dt.datetime.combine(dt.datetime.strptime(item['date'], '%Y%m%d'), item['start_time'])
                    estimated_end_time = dt.datetime.combine(dt.datetime.strptime(item['date'], '%Y%m%d'), item['end_time'])

                    cleaning_duration = time_to_minutes(timedelta_to_time(estimated_end_time - dt.timedelta(minutes=additional_time_in_minutes + first_added_time_in_minutes) - start_time))

                    actual_price = 0
                    if i == 1: # 1 번째 클리닝
                        actual_price = price_with_task - discounted_price # 할인은 1회만 적용됨

                    else: # 나머지
                        actual_price = price
                        if havetools == 1:
                            additional_task = 0
                        else: 
                            additional_task = 64
                            #actual_price += BC.VACCUM_CHARGE

                        if laundry_apply_all == 1:
                            additional_task += 4 # 빨래

                        isdirty = 0 # 첫째 이후에는 is dirty는 0
                        estimated_end_time = estimated_end_time - dt.timedelta(minutes=additional_time_in_minutes + first_added_time_in_minutes)


                    booking = Booking(id = booking_id, 
                                      request_id = request_id, 
                                      user_id = uid, 
                                      master_id = mid, 
                                      appointment_type = appointment_type, 
                                      appointment_index = i,
                                      dow = dow,
                                      booking_time = dt.datetime.now(),
                                      org_start_time = start_time,
                                      start_time = start_time,
                                      estimated_end_time = estimated_end_time,
                                      end_time = estimated_end_time, # update after homemaster finish their job
                                      cleaning_duration = cleaning_duration,
                                      additional_task = additional_task, 
                                      price = price,
                                      price_with_task = actual_price,
                                      charging_price = 0,
                                      card_idx = card_idx, 
                                      addr_idx = addr_idx, 
                                      havetools = havetools, 
                                      havepet = have_pet,
                                      laundry_apply_all = laundry_apply_all,
                                      is_dirty = isdirty,
                                      master_gender = master_gender,
                                      status = BC.BOOKING_UPCOMMING, 
                                      cleaning_status = BC.BOOKING_UPCOMMING,
                                      payment_status = BC.BOOKING_UNPAID_YET)
                    i += 1

                    session.add(booking) 
                    booking_ids.append(booking_id)
                    start_time_list.append(start_time)

                    #print 'booking_id', booking_id, 'was added..'

                # charge for first appointment date
                user_name = userdao.get_user_name(uid)
                if price_with_task - discounted_price <= 0:
                    ret_code = True
                    msg = ''
                else:
                    ret_code, msg = request_payment(uid, user_name, booking_ids[0], price_with_task - discounted_price, appointment_type)

                # 결제 정보 출력
                print user_name, ret_code, msg

                if ret_code:
                    session.commit()

                    # remove store_key and related_keys
                    holder.remove(store_key)
                    for sk in search_keys:
                        holder.remove(sk)

                    # promotion code 와 연결
                    if promotion_code != '':
                        promotiondao.set_promotion_code_status(promotion_code, 1, booking_ids[0], price_with_task)

                    # change status to paid
                    try:
                        first_booking = session.query(Booking).filter(Booking.id == booking_ids[0]).one()
                    except NoResultFound, e:
                        session.close()
                        self.set_status(Response.RESULT_OK)
                        mongo_logger.debug('no first booking record', extra = {    'uid' : uid, 'mid' : mid,'appointment_type' : appointment_type, 'have_pet' : have_pet, 'master_gender' : master_gender, 'isdirty' : isdirty})
                        add_err_message_to_response(ret, err_dict['err_no_record'])
                        return                

                    except MultipleResultsFound, e:
                        session.close()
                        self.set_status(Response.RESULT_OK)
                        mongo_logger.debug('multiple first booking record', extra = {    'uid' : uid, 'mid' : mid, 'appointment_type' : appointment_type, 'have_pet' : have_pet, 'master_gender' : master_gender, 'isdirty' : isdirty})
                        add_err_message_to_response(ret, err_dict['err_multiple_record'])
                        return  
コード例 #7
0
    def post(self):
        self.set_header("Content-Type", "application/json")
        self.set_header('Access-Control-Allow-Origin', '*')

        ret = {}

        uid = self.get_argument('uid', '')
        search_keys = self.get_argument('search_keys', '')
        store_key = self.get_argument('store_key', '')

        #price                   = self.get_argument('price', 0)
        #price_with_task         = self.get_argument('price_with_task', 0)
        #discounted_price        = self.get_argument('discounted_price', 0)
        promotion_code = self.get_argument('promotion_code', '')

        laundry_apply_all = self.get_argument(
            'laundry_apply_all', 0)  # -1 - 없앰, 0 - one time, 1 - all time

        has_card = self.get_argument('has_card', 0)
        # ---------- card paremeters ------------
        cno = self.get_argument('cno', '')
        expy = self.get_argument('expy', '')
        expm = self.get_argument('expm', '')
        ssnf = self.get_argument('ssnf', '')
        cpftd = self.get_argument('cpftd', '')
        calias = self.get_argument('calias', '')

        # register card
        request_url = '%s:%d/homemaster_payment/register_card' % (PAYMENT_HOST,
                                                                  PAYMENT_PORT)
        params = {}
        params['id'] = uid
        params['cno'] = cno
        params['expy'] = expy
        params['expm'] = expm
        params['ssnf'] = ssnf
        params['cpftd'] = cpftd
        params['calias'] = calias

        has_card = int(has_card)

        mongo_logger = get_mongo_logger()
        mix = get_mixpanel()

        # 카드가 없는 경우에만 카드 등록하고 진행, 있다면 바로 진행
        if has_card == 0:
            response = requests.post(request_url, data=params)
            result = json.loads(response.text)

            if response.status_code != 200 or result['response'] == "":
                print 'An error occurred while register card'
                print result['err_code'], result['err_msg']
                add_err_ko_message_to_response(ret, result['err_msg'])
                mongo_logger.error('register card failed', extra={'uid': uid})
                return

        laundry_apply_all = int(laundry_apply_all)

        search_keys = search_keys.split(',')

        try:
            session = Session()
            userdao = UserDAO()
            masterdao = MasterDAO()
            promotiondao = PromotionDAO()
            addressdao = AddressDAO()

            holder = IntermediateValueHolder()

            # request id to group each individual bookings
            request_id = str(uuid.uuid4())

            obj = holder.retrieve(store_key)
            print obj
            if obj == None:
                self.set_status(Response.RESULT_OK)
                add_err_message_to_response(ret,
                                            err_dict['err_booking_timeout'])
                mix.track(uid, 'request timeout', {'time': dt.datetime.now()})
                mongo_logger.error('%s got timed out' % uid)
                return

            # retrieve all stored values
            uid = obj['user_id']
            mid = obj['master_id']
            dates = obj['dates']
            time = obj['time']
            appointment_type = obj['appointment_type']
            additional_task = obj['additional_task']
            org_additional_task = additional_task

            taking_time = obj['taking_time']
            first_added_time = obj['first_added_time']
            additional_time = obj['additional_time']
            total_time = obj['total_time']
            master_gender = obj['master_gender']
            have_pet = obj['have_pet']
            isdirty = obj['isdirty']

            # price
            # price_with_task
            # discounted_price
            address, house_size, house_type = userdao.get_user_address_detail(
                uid)
            _, _, price, _ = get_time_price(appointment_type, house_type,
                                            house_size)
            _, additional_price = get_additional_task_time_price(
                additional_task, house_type, house_size)

            discounted_price = 0
            if promotion_code != '':
                discounted_price = promotiondao.get_discount_price(
                    promotion_code)

            price_with_task = price + additional_price
            if 0 < discounted_price <= 100:
                price_with_task *= (float(100 - discounted_price) / 100)
            else:
                price_with_task -= discounted_price

            price_with_task = int(price_with_task)

            print '-' * 30
            print price, additional_price
            print promotion_code, price_with_task
            print '##' * 20

            # hasids to generate unique booking id
            now = dt.datetime.strftime(dt.datetime.now(), '%Y%m%d%H%M%S')
            hashids = Hashids(min_length=16, salt=now + uid)

            # set tool info
            havetools = 1
            if additional_task >= 64:
                havetools = 0

            card_idx = 0
            addr_idx = 0

            # get card and address idx
            addr_idx = userdao.get_user_default_address_index(uid)
            card_idx = userdao.get_user_default_card_index(uid)

            i = 1
            booking_ids = []
            start_time_list = []

            for date in dates:  #
                print date, time
                booking_id = hashids.encode(int(date + time.replace(':', '')))
                print 'key', booking_id
                master_id = mid

                date = dt.datetime.strptime(date, '%Y%m%d')
                dow = date.date().weekday()
                booking_time = dt.time(hour=int(time.split(':')[0]),
                                       minute=int(time.split(':')[1]))

                start_time = dt.datetime.combine(date, booking_time)
                estimated_end_time = start_time + dt.timedelta(
                    minutes=total_time)
                cleaning_duration = taking_time

                actual_price = 0
                if i == 1:  # 1 번째 클리닝
                    actual_price = price_with_task  # 할인은 1회만 적용됨

                else:  # 나머지
                    actual_price = price
                    if havetools == 1:
                        additional_task = 0
                    else:
                        additional_task = 64

                    if laundry_apply_all == 1:
                        additional_task += 4  # 빨래

                    isdirty = 0  # 첫째 이후에는 is dirty는 0
                    estimated_end_time = estimated_end_time - dt.timedelta(
                        minutes=additional_time + first_added_time)

                booking = Booking(
                    id=booking_id,
                    request_id=request_id,
                    user_id=uid,
                    master_id=mid,
                    appointment_type=appointment_type,
                    appointment_index=i,
                    dow=dow,
                    booking_time=dt.datetime.now(),
                    org_start_time=start_time,
                    start_time=start_time,
                    estimated_end_time=estimated_end_time,
                    end_time=
                    estimated_end_time,  # update after homemaster finish their job
                    cleaning_duration=cleaning_duration,
                    additional_task=additional_task,
                    price=price,
                    price_with_task=actual_price,
                    charging_price=0,
                    card_idx=card_idx,
                    addr_idx=addr_idx,
                    havetools=havetools,
                    havepet=have_pet,
                    laundry_apply_all=laundry_apply_all,
                    is_dirty=isdirty,
                    master_gender=master_gender,
                    status=BC.BOOKING_UPCOMMING,
                    cleaning_status=BC.BOOKING_UPCOMMING,
                    payment_status=BC.BOOKING_UNPAID_YET)
                i += 1

                session.add(booking)
                booking_ids.append(booking_id)
                start_time_list.append(start_time)

                #print 'booking_id', booking_id, 'was added..'

            # charge for first appointment date
            user_name = userdao.get_user_name(uid)
            if price_with_task <= 0:
                ret_code = True
                msg = ''
            else:
                ret_code, msg = request_payment(uid, user_name, booking_ids[0],
                                                price_with_task,
                                                appointment_type)

            # 결제 정보 출력
            print user_name, ret_code, msg

            if ret_code:
                session.commit()

                # remove store_key and related_keys
                holder.remove(store_key)
                for sk in search_keys:
                    holder.remove(sk)

                # promotion code 와 연결
                if promotion_code != '':
                    promotiondao.set_promotion_code_status(
                        promotion_code, 1, booking_ids[0], price_with_task)

                # change status to paid
                try:
                    first_booking = session.query(Booking, User, MasterPushKey) \
                                            .join(User, Booking.user_id == User.id) \
                                            .outerjoin(MasterPushKey, Booking.master_id == MasterPushKey.master_id) \
                                            .filter(Booking.id == booking_ids[0]) \
                                            .one()
                except NoResultFound, e:
                    session.close()
                    self.set_status(Response.RESULT_OK)
                    mongo_logger.debug('no first booking record',
                                       extra={
                                           'uid': uid,
                                           'mid': mid,
                                           'appointment_type':
                                           appointment_type,
                                           'have_pet': have_pet,
                                           'master_gender': master_gender,
                                           'isdirty': isdirty
                                       })
                    add_err_message_to_response(ret, err_dict['err_no_record'])
                    return

                except MultipleResultsFound, e:
                    session.close()
                    self.set_status(Response.RESULT_OK)
                    mongo_logger.debug('multiple first booking record',
                                       extra={
                                           'uid': uid,
                                           'mid': mid,
                                           'appointment_type':
                                           appointment_type,
                                           'have_pet': have_pet,
                                           'master_gender': master_gender,
                                           'isdirty': isdirty
                                       })
                    add_err_message_to_response(
                        ret, err_dict['err_multiple_record'])
                    return
コード例 #8
0
    def post(self):
        self.set_header("Content-Type", "application/json")
        self.set_header('Access-Control-Allow-Origin', '*')

        booking_id = self.get_argument('booking_id', '')
        reason_id = self.get_argument('reason_id', CANCEL_ADMIN)
        etc_reason = self.get_argument('etc_reason', '')
        charge_amount = self.get_argument('charge_amount', 0)
        no_fee = self.get_argument('no_fee', 0)

        regular_cancel_charge = self.get_argument('regular_cancel_charge', 0)

        charge_amount = int(charge_amount)
        reason_id = int(reason_id)
        no_fee = int(no_fee)

        regular_cancel_charge = int(regular_cancel_charge)

        print 'cancel all charge amount : ', charge_amount
        print 'reason_id : ', reason_id
        print 'etc_reason : ', etc_reason

        ret = {}

        mongo_logger = get_mongo_logger()
        mix = get_mixpanel()

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

            stmt = session.query(Booking.request_id).filter(
                Booking.id == booking_id).subquery()
            first_startime = session.query(Booking.start_time).filter(
                Booking.request_id == stmt).order_by(
                    Booking.start_time).first()[0]

            result = session.query(Booking, Master, User, UserAddress) \
                         .join(Master, Booking.master_id == Master.id) \
                         .join(User, Booking.user_id == User.id) \
                         .join(UserDefaultAddress, User.id == UserDefaultAddress.user_id) \
                         .join(UserAddress, and_(UserAddress.user_id == UserDefaultAddress.user_id, UserAddress.user_addr_index == UserDefaultAddress.address_idx)) \
                         .filter(Booking.request_id == stmt) \
                         .filter(or_(Booking.cleaning_status == BC.BOOKING_UPCOMMING, Booking.cleaning_status == BC.BOOKING_STARTED, Booking.cleaning_status == BC.BOOKING_COMPLETED)) \
                         .all()

            # 서비스를 처음 이용한지 2달이 넘었는지 아닌지 조사,
            # 넘지 않았다면 이미 부과된 금액에 대해서도 1회 서비스 금액 과의 차액만큼 부과됨
            current_time = dt.datetime.now()

            completed_charge = 1
            if current_time >= first_startime + dt.timedelta(days=57):
                completed_charge = 0

            cancel_all_charge = 0
            # 그동안의 모든 예약에 대해서 처리함
            for row in result:
                charge = 0

                new_status = BC.BOOKING_CANCELED_CHARGE

                key = userdao.get_user_salt_by_id(row.User.id)[:16]
                crypto = aes.MyCrypto(key)

                username = str(crypto.decodeAES(row.User.name))

                request_id = row.Booking.request_id
                appointment_index = row.Booking.appointment_index

                bid = row.Booking.id
                user_id = row.Booking.user_id
                appointment_time = row.Booking.start_time
                current_status = row.Booking.status
                current_cleaning_status = row.Booking.cleaning_status
                current_payment_status = row.Booking.payment_status
                price = row.Booking.price_with_task
                source = row.Booking.source
                appointment_type = row.Booking.appointment_type

                diff_in_hours = (appointment_time -
                                 current_time).total_seconds() / 3600

                if diff_in_hours >= 24:
                    charge = price * BC.BOOKING_CHARGE_RATE_NO
                elif 4 <= diff_in_hours < 24:
                    charge = price * BC.BOOKING_CHARGE_RATE_30
                else:
                    charge = price * BC.BOOKING_CHARGE_RATE_50

                # 이미 지불한 금액에 대해 1회 비용의 차액만큼 계산
                if completed_charge == 1:
                    if current_cleaning_status == BC.BOOKING_COMPLETED:
                        # 차액만큼 계속 더함
                        _, house_size, house_type = userdao.get_user_address_detail_by_index(
                            user_id, row.Booking.addr_idx)
                        time_prices = get_basic_time_price(
                            house_type, house_size)
                        try:
                            print time_prices[0]['price']
                            print time_prices[appointment_type]['price']
                            charge_amount = int(
                                time_prices[0]['price'] -
                                time_prices[appointment_type]['price'])
                        except Exception:
                            charge_amount = 3000
                        cancel_all_charge += charge_amount

                # event
                is_event = session.query(UserFreeEvent) \
                                .filter(UserFreeEvent.booking_request_id == request_id) \
                                .first()

                is_event = True if is_event != None else False

                if is_event == True and appointment_index == 1:
                    partial = '0'
                    cancel_amount = row.Booking.price_with_task - row.Booking.price
                    cancel_payment(user_id, bid, cancel_amount, partial)

                    # 취소에 대한 결제 필요
                    # 8회 이상 썼다면(완료카운트 9회 미만일 경우 결제)
                    complete_count = session.query(Booking) \
                            .filter(Booking.request_id == request_id) \
                            .filter(Booking.cleaning_status == 2) \
                            .count()

                    if complete_count < 9 and row.Booking.cleaning_status == 2:
                        ret_code, msg = request_payment(
                            user_id, username, booking_id, price,
                            appointment_type)
                        if ret_code == False:
                            row.Booking.payment_status = BC.BOOKING_PAYMENT_FAILED

                if current_payment_status == BC.BOOKING_PAID and current_cleaning_status == BC.BOOKING_UPCOMMING:
                    if no_fee == 1:
                        charge = 0

                    new_status = BC.BOOKING_CANCELED_REFUND

                    partial = '1'
                    if charge == 0:
                        partial = '0'

                    cancel_amount = int(price - charge)
                    if cancel_amount > 0 and source == 'hm' and userdao.get_user_default_card_index(
                            user_id) != -1:
                        if not (is_event and appointment_index == 1):
                            ret_code, msg = cancel_payment(
                                user_id, bid, cancel_amount, partial)
                            if ret_code == False:
                                session.close()
                                self.set_status(Response.RESULT_OK)
                                add_err_ko_message_to_response(ret, msg)
                                #self.write(json.dumps(ret))
                                return

                elif current_payment_status == BC.BOOKING_UNPAID_YET and current_cleaning_status == BC.BOOKING_UPCOMMING:
                    print 'cancel charge'
                    charging_price = int(charge)
                    if charging_price > 0 and source == 'hm' and userdao.get_user_default_card_index(
                            user_id) != -1 and no_fee == 0:
                        print user_id, username, booking_id, charging_price, appointment_type
                        ret_code, msg = request_payment(
                            user_id, username, bid, charging_price,
                            appointment_type)
                        if ret_code == False:
                            new_status = BC.BOOKING_PAYMENT_FAILED

                #row.Booking.modified_date   = current_time
                if current_cleaning_status == BC.BOOKING_UPCOMMING:
                    row.Booking.charging_price = int(charge)
                    row.Booking.status = new_status
                    row.Booking.cleaning_status = BC.BOOKING_CANCELED
                    row.Booking.payment_status = new_status

                # add cancel reason
                CANCEL_ALL = 1
                reason = session.query(CancelReason).filter(
                    CancelReason.booking_id == bid)
                if reason.count() == 0:
                    cancel_reason = CancelReason(booking_id=bid,
                                                 user_id=user_id,
                                                 reason_id=reason_id,
                                                 etc_reason=etc_reason,
                                                 kind=CANCEL_ALL,
                                                 cancel_time=dt.datetime.now())
                    session.add(cancel_reason)
                else:
                    try:
                        reason_row = reason.one()
                        reason_row.kind = 1
                    except Exception, e:
                        print e

            # 수수료 임시 처리 막기
            #cancel_all_charge = 0
            if cancel_all_charge > 0 and source == 'hm' and regular_cancel_charge == 0:
                user_name = userdao.get_user_name(user_id)
                ret_code, msg = request_charge(user_id, user_name,
                                               cancel_all_charge)
                if ret_code == False:
                    session.close()
                    self.set_status(Response.RESULT_OK)
                    add_err_ko_message_to_response(ret, msg)
                    self.write(json.dumps(ret))
                    return

            if row != None:
                key = userdao.get_user_salt_by_id(row.User.id)[:16]
                crypto = aes.MyCrypto(key)

                # push to homemaster via sms
                master_id = row.Master.id
                master_phone = str(row.Master.phone)
                master_name = str(row.Master.name)
                username = str(crypto.decodeAES(row.User.name))
                userphone = str(crypto.decodeAES(row.User.phone))
                date = str(convert_datetime_format(row.Booking.start_time))
                addr = str(crypto.decodeAES(row.UserAddress.address))
                appointment_type = str(row.Booking.appointment_type)

                print 'app _type'
                print appointment_type

                appointment_type_text = ''
                if appointment_type == BC.ONE_TIME or appointment_type == BC.ONE_TIME_BUT_CONSIDERING:
                    appointment_type_text = '1회'
                elif appointment_type == BC.FOUR_TIME_A_MONTH:
                    appointment_type_text = '매주'
                elif appointment_type == BC.TWO_TIME_A_MONTH:
                    appointment_type_text = '2주 1회'
                elif appointment_type == BC.ONE_TIME_A_MONTH:
                    appointment_type_text = '4주 1회'

                #sms_sender = SMS_Sender()
                #text = BOOKING_CANCEL_ALL_TEXT % (appointment_type, username, userphone, master_name, date)
                #send_result = sms_sender.send_for_manager(sender = MAIN_CALL, mtype = 'sms', to = MANAGERS_CALL, subject = BOOKING_TEXT_SUBJECT, text = text)

                #for manager_phone in MANAGERS_CALL.split(','):
                #    send_alimtalk(manager_phone, 'noti_manager_cancel_all', username, date, appointment_type_text)

                cancel_all_reasons = []
                cancel_all_reasons.append('너무 비싸요')
                cancel_all_reasons.append('제가 여행을 가요')
                cancel_all_reasons.append('청소품질이 마음에 들지 않아요')
                cancel_all_reasons.append('필요할 때에만 서비스를 이용하고 싶어요')
                cancel_all_reasons.append('다른 업체로 바꿀래요')
                cancel_all_reasons.append('원하던 홈마스터가 오질 않아요')
                cancel_all_reasons.append('저 이사가요')
                cancel_all_reasons.append('기타')
                cancel_all_reasons.append('관리자가 취소 했습니다')

                cancel_reason = cancel_all_reasons[reason_id]
                if cancel_reason == '기타':
                    cancel_reason += ' ' + etc_reason
                elif reason_id == CANCEL_ADMIN:
                    cancel_reason += ', 관리자 메모 : ' + etc_reason

                send_jandi(
                    'NEW_BOOKING', "전체 취소 알림", username + ' 고객님 전체 취소함',
                    '{}, {} 사유 : {}'.format(date, appointment_type_text,
                                            cancel_reason))

                print 'jandi notification for cancel all...'

                master_pushkey = masterdao.get_master_pushkey(master_id)
                send_all_bookings_canceled('android', [master_pushkey],
                                           booking_id, date, username)

                master_phone = masterdao.get_master_phone(master_id)
                master_name = masterdao.get_master_name(master_id)

                user_name = userdao.get_user_name(user_id)

                content = '''{} 홈마스터님
정기 고객의 예약이 전체 취소 되었습니다.

고객 : {}
주기 : {}'''.format(master_name, user_name, appointment_type_text)

                print 'text'
                print appointment_type_text
                message_sender = MessageSender()
                message_sender.send([master_phone], '예약 전체 취소 알림', content)

                #send_alimtalk(master_phone, 'noti_manager_cancel_all', username, date, appointment_type_text)

            coupondao = CouponDAO()
            coupondao.cancelall_coupon_usage(booking_id)

            session.commit()

            mix.track(
                user_id, 'cancel all', {
                    'time': dt.datetime.now(),
                    'reason_id': reason_id,
                    'etc_reason': etc_reason
                })
            mongo_logger.debug('%s was all canceled' % booking_id,
                               extra={
                                   'user_id': user_id,
                                   'booking_id': booking_id
                               })

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