Example #1
0
    def get_html(self, **kwargs):
        user_type_mapping = {"ADT": u"成人", "STU": u"留学生"}
        users = kwargs.get("users", [])
        for user in users:
            user['passenger_type'] = user['user_type']
            user['user_type'] = user_type_mapping.get(
                user.get('user_type', ""), u"成人")

        routes = kwargs['products'].get("routes", [])
        for route in routes:
            route['limits'] = Route.get_limits(route['limit_no'])
            now_time = datetime.datetime.now()
            route_delta = Flight.format_datetime(route['departure']) - now_time
            if route_delta.days >= const.DAYS_LIMIT:
                route['deadline'] = datetime_delta(now_time,
                                                   hours=const.DEADLINE_MUCH)
            else:
                route['deadline'] = datetime_delta(now_time,
                                                   hours=const.DEADLINE_LESS)

            for flight in route.get("flights", []):
                flight['departure'] = Flight.format_datetime(
                    flight['departure'])
                flight['arrival'] = Flight.format_datetime(flight['arrival'])

        pnr = self.get_pnr(routes, users)
        const_data = self.get_const()
        kwargs.update(const_data)
        kwargs['pnr'] = pnr
        return render_to_string("email.html", kwargs), kwargs
Example #2
0
    def get_html(self, **kwargs):
        user_type_mapping = {
            "ADT": u"成人",
            "STU": u"留学生"
        }
        users = kwargs.get("users", [])
        for user in users:
            user['passenger_type'] = user['user_type']
            user['user_type'] = user_type_mapping.get(user.get('user_type', ""), u"成人")

        routes = kwargs['products'].get("routes", [])
        for route in routes:
            route['limits'] = Route.get_limits(route['limit_no'])
            now_time = datetime.datetime.now()
            route_delta = Flight.format_datetime(route['departure']) - now_time
            if route_delta.days >= const.DAYS_LIMIT:
                route['deadline'] = datetime_delta(now_time, hours=const.DEADLINE_MUCH)
            else:
                route['deadline'] = datetime_delta(now_time, hours=const.DEADLINE_LESS)

            for flight in route.get("flights", []):
                flight['departure'] = Flight.format_datetime(flight['departure'])
                flight['arrival'] = Flight.format_datetime(flight['arrival'])

        pnr = self.get_pnr(routes, users)
        const_data = self.get_const()
        kwargs.update(const_data)
        kwargs['pnr'] = pnr
        return render_to_string("email.html", kwargs), kwargs
Example #3
0
class PlaneSearchView(TemplateView):
    template_name = "plane/search.html"

    def get_context_data(self, **kwargs):
        context = super(PlaneSearchView, self).get_context_data(**kwargs)
        context['products'] = self.get_products()
        return context

    def get_products(self):
        starting = self.request.GET.get("starting", "")
        destination = self.request.GET.get("destination", "")
        try:
            departure = datetimes.str_to_datetime(
                self.request.GET.get("departure", ""), datetimes.DATE_FORMAT)
        except Exception, err:
            return []

        ending = datetimes.datetime_delta(departure, days=1)

        if not all([starting, departure, destination]):
            return []

        products = FlightProduct.objects.filter(starting=starting,
                                                destination=destination,
                                                departure__gte=departure,
                                                departure__lte=ending)
        return products
Example #4
0
 def handle_get_date(self, start_date, end_date):
     start_date = str_to_date(start_date)
     end_date = str_to_date(end_date)
     date_list = []
     day_number = (end_date - start_date).days
     for d in range(day_number):
         date_list.append(datetime_delta(start_date, days=int(d)))
     return date_list
Example #5
0
    def get(self, request, *args, **kwargs):
        page_size = 5

        query_dict = self.get_route_query_dict(request, *args, **kwargs)
        city = City.get_name_by_code(query_dict.get("destination", ""))
        routes_search = Route.search(**query_dict)
        departure_str = query_dict.get("departure", "")
        if not departure_str:
            return json_response({
                "hotels": [],
                "commodities": [],
                "routes": [],
            })
        departure = str_to_datetime(departure_str, DATE_FORMAT)
        departure_tomorrow = datetime_delta(departure, days=1)

        if not city:
            hotels = []
            commodities = []
        else:
            hotels = map(
                lambda hotel: hotel.to_json(),
                list(
                    HotelProduct.objects.filter(
                        city=city,
                        check_in_time__gte=departure,
                        check_in_time__lt=departure_tomorrow).select_related())
            )
            commodities = map(
                lambda commodity: commodity.to_json(),
                list(
                    CommodityProduct.objects.filter(
                        city=city,
                        datetime__gte=departure,
                        datetime__lt=departure_tomorrow).select_related()))
        routes = map(lambda route: route.to_json(), routes_search)

        def cmp(a, b):
            price_a = int(a['price']) + int(a['tax'])
            price_b = int(b['price']) + int(b['tax'])
            if price_a <= price_b:
                return -1
            else:
                return 1

        routes = sorted(routes, cmp=cmp)
        routes_available = [
            'HA',
        ]
        routes = filter(
            lambda route: route['company_three'] in routes_available, routes)

        return json_response({
            "hotels": hotels[:page_size],
            "commodities": commodities[:page_size],
            "routes": routes[:page_size]
        })
Example #6
0
    def fetch_user_access_token(cls, user, code, app=None):
        if not app:
            app = App.only_one()
        url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code" % (app.app_key, app.app_id, code)
        json_data = requests.get(url).json()
        expires_in = datetime_delta(datetime_now(), seconds=json_data['expires_in'])

        token = WeixinUserToken(user=user, openid=json_data['openid'], access_token=json_data['access_token'],
                                refresh_token=json_data['refresh_token'], scope=json_data['scope'],
                                expires_in=expires_in)
        token.save()
Example #7
0
    def handle(self, *args, **options):
        # 清理前一天的图片和日志
        now = datetime_now()
        if now.hour != 1:
            return
        yesterday = datetime_delta(now, days=-1)
        path = "%s/data/image/%s*" % (PROJECT_HOME, date_to_str(yesterday.date()))
        shell_command = "rm -rf %s" % path
        os.system(shell_command)

        log_path = "%s/data/logs/%s*" % (PROJECT_HOME, date_to_str(yesterday.date()).replace('-', ""))
        shell_command = "rm -rf %s" % log_path
        os.system(shell_command)
Example #8
0
    def refresh_access_token(self, app=None):
        if not app:
            app = App.only_one()
        url = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=%s&grant_type=refresh_token&refresh_token=%s" % (app.app_key, self.refresh_token)
        json_data = requests.get(url).json()

        expires_in = datetime_delta(datetime_now(), seconds=json_data['expires_in'])
        self.expires_in = expires_in
        self.access_token = json_data['access_token']
        self.refresh_token = json_data['refresh_token']
        self.openid = json_data['openid']
        self.scope = json_data['scope']
        self.save()
Example #9
0
    def fetch_yesterday(self):
        """获取昨天的咨询量"""
        today = datetime.date.today()
        yesterday = datetime_delta(today, days=-1)
        start_str = str(yesterday) + ' 00:00:00'
        end_str = str(yesterday) + " 23:59:59"

        start_strp = time.strptime(start_str, '%Y-%m-%d %H:%M:%S')
        end_strp = time.strptime(end_str, '%Y-%m-%d %H:%M:%S')

        today_timestamp = time.mktime(start_strp)
        yesterday_timestamp = time.mktime(end_strp)
        return self._fetch_data(from_time=yesterday_timestamp,
                                to_time=today_timestamp)
Example #10
0
 def get_queryset(self):
     kwargs = self.request.GET
     query_params = {"user_id": self.request.user.id}
     from_date = kwargs.get("form_date", '').strip()
     to_date = kwargs.get("to_date", '').strip()
     operationmodule = kwargs.get("name", None)
     if from_date and from_date != 'undefined':
         query_params.update({"operationtime__gte": str_to_date(from_date)})
     if to_date and to_date != 'undefined':
         to_date = datetime_delta(str_to_date(to_date), days=1)
         query_params.update({"operationtime__lte": to_date})
     if operationmodule:
         query_params.update({"operationmodule": operationmodule})
     return OperateLog.objects.all().filter(**query_params).exclude(
         operationmodule__in=("客户库", "培训管理")).order_by("-operationtime")
Example #11
0
 def create_station_info(self):
     grid = Grid.objects.filter(pk=self.company_data.get('grid_id')).first()
     if not grid:
         logger.error(
             f"{self.company_data.get('site_id')}未找到对应节点id{self.company_data.get('grid_id')}"
         )
         raise DatabaseError(
             f"{self.company_data.get('site_id')}未找到对应节点id{self.company_data.get('grid_id')}"
         )
     # 部署方式
     deploy_way = self.company_data.get('deploy_way', 1)
     # 有效期
     validity_days = self.company_data.get('validity_days', 365)
     # 客户版本
     cli_version = self.get_cli_version(self.company_data['site_id'])
     # 开站日期
     open_station_time = datetime.date.today()
     # 到期日期
     close_station_time = datetime_delta(open_station_time, days=365)
     # 销售人员
     sales = self.company_data.get('sales', '0')
     # 售前人员
     pre_sales = self.company_data.get('pre_sales', '0')
     # 运营顾问
     oper_cslt = self.company_data.get('oper_cslt', '0')
     # 实施顾问
     impl_cslt = self.company_data.get('impl_cslt', '0')
     # 运营支持
     oper_supt = self.company_data.get('oper_supt', '0')
     station_info, _ = StationInfo.objects.update_or_create(
         defaults=dict(
             deploy_way=deploy_way,
             validity_days=validity_days,
             grid=grid,
             cli_version=cli_version,
             open_station_time=open_station_time,
             close_station_time=close_station_time,
             sales=sales,
             classify=2,
             pre_sales=pre_sales,
             oper_cslt=oper_cslt,
             impl_cslt=impl_cslt,
             oper_supt=oper_supt,
         ),
         company_id=self.company_data.get('site_id'),
     )
     return station_info
Example #12
0
    def get(self, request, *args, **kwargs):
        page_size = 5

        query_dict = self.get_route_query_dict(request, *args, **kwargs)
        city = City.get_name_by_code(query_dict.get("destination", ""))
        routes_search = Route.search(**query_dict)
        departure_str = query_dict.get("departure", "")
        if not departure_str:
            return json_response({
                "hotels": [],
                "commodities": [],
                "routes": [],
            })
        departure = str_to_datetime(departure_str, DATE_FORMAT)
        departure_tomorrow = datetime_delta(departure, days=1)

        if not city:
            hotels = []
            commodities = []
        else:
            hotels = map(lambda hotel: hotel.to_json(),
                         list(HotelProduct.objects.filter(city=city,
                                                          check_in_time__gte=departure,
                                                          check_in_time__lt=departure_tomorrow).select_related()))
            commodities = map(lambda commodity: commodity.to_json(),
                              list(CommodityProduct.objects.filter(city=city,
                                                                   datetime__gte=departure,
                                                                   datetime__lt=departure_tomorrow).select_related()))
        routes = map(lambda route: route.to_json(), routes_search)

        def cmp(a, b):
            price_a = int(a['price']) + int(a['tax'])
            price_b = int(b['price']) + int(b['tax'])
            if price_a <= price_b:
                return -1
            else:
                return 1
        routes = sorted(routes, cmp=cmp)
        routes_available = ['HA', ]
        routes = filter(lambda route: route['company_three'] in routes_available, routes)

        return json_response({
            "hotels": hotels[:page_size],
            "commodities": commodities[:page_size],
            "routes": routes[:page_size]
        })
Example #13
0
    def matter_export(self, request):
        """
        问题列表导出
        :param request:
        :return:
        """
        # 获取参数
        start_time = request.GET.get("start_time")
        end_time = request.GET.get("end_time")
        matter_flow = MatterFlowViewsets()
        query_params = {}

        if start_time:
            query_params.update({"start_time__gte": str_to_date(start_time)})
        if end_time:
            end_time = datetime_delta(str_to_date(end_time), days=1)
            query_params.update({"end_time__lte": end_time})

        name = "培训管理-客户培训"
        title_key = ["id", "company_name", "company_id", "deploy_way", "impl_cslt", "oper_supt", "commercial",
                     "training_instructors", "training_method", "training_contact", "start_time", "end_time",
                     "training_model"]
        title_value = ["id", "企业名称", "企业ID", "部署方式", "实施顾问", "运营顾问", "商务","培训讲师","培训方式",
                       "培训联系人","培训开始时间", "培训结束时间","培训模块"]
        title = dict(zip(title_key, title_value))
        content_list = []
        queryset = Matter.objects.filter(**query_params).values('id', 'matter_status', 'company_matter')
        # 如果查询不是空集
        if not queryset:
            content_list.append(dict(zip(title_key, [i-i for i in range(len(title_key))])))
            excl = Excel_export(filename=name, title=title, content=content_list)
            response = excl.export_csv()
            return response

        for query in queryset:
            id = query["id"]
            company_matter = query["company_matter"]
            dic_comstaion = matter_flow.get_comstaion(company_matter)
            train_dict = matter_flow.get_trainfo(id)
            query.update(dic_comstaion)
            query.update(train_dict)
            content_list.append(query)
        excl = Excel_export(filename=name, title=title, content=content_list)
        response = excl.export_csv()
        return response
Example #14
0
 def get_queryset(self):
     kwargs = self.request.GET
     query_params = {}
     from_date = kwargs.get("form_date", None)
     to_date = kwargs.get("to_date", None)
     username = kwargs.get("username", None)
     action = kwargs.get("action", None)
     if from_date:
         query_params.update({"operationtime__gte": str_to_date(from_date)})
     if to_date:
         to_date = datetime_delta(str_to_date(to_date), days=1)
         query_params.update({"operationtime__lte": to_date})
     if username:
         query_params.update({"user__last_name__icontains": username})
     if action:
         query_params.update({"action": action})
     return OperateLog.objects.all().filter(
         **query_params).order_by("-operationtime")
Example #15
0
 def get_queryset(self):
     kwargs = self.request.GET
     query_params = {}
     from_date = kwargs.get("form_date", None)
     to_date = kwargs.get("to_date", None)
     username = kwargs.get("username", None)
     operationmodule = kwargs.get("name", None)
     if from_date:
         query_params.update({"operationtime__gte": str_to_date(from_date)})
     if to_date:
         to_date = datetime_delta(str_to_date(to_date), days=1)
         query_params.update({"operationtime__lte": to_date})
     if username:
         query_params.update({"user__last_name__icontains": username})
     if operationmodule:
         query_params.update({"operationmodule": operationmodule})
     return OperateLog.objects.all().filter(**query_params).exclude(
         operationmodule__in=("客户库", "培训管理")).order_by("-operationtime")
Example #16
0
    def get_or_update_token(cls, user, access_token_json):
        openid = access_token_json['openid']

        # 先找用户是否已经绑定
        try:
            token = cls.objects.get(user=user)
        except:
            token = None

        # 如果没有绑定,查看微信号是否绑定过用户,再没有,创建用户
        if not token:
            try:
                token = cls.objects.get(openid=openid)
            except cls.DoesNotExist:
                token = cls(user=user)

        token.user = user
        token.openid = openid
        token.access_token = access_token_json['access_token']
        token.refresh_token = access_token_json['refresh_token']
        token.scope = access_token_json['scope']
        token.expires_in = datetime_delta(datetime_now(), seconds=3600)
        token.save()
        return token
Example #17
0
 def __init__(self, start_time):
     self.start_time = str(start_time) + ' 00:00:00'
     self.end_time = date_to_str(
         datetime_delta(str_to_date(start_time), days=1)) + ' 00:00:00'
     self.grid_data = self.get_grid()
Example #18
0
 def __init__(self):
     db_info = DataBaseInfo.objects.filter(db_name="kf")
     self.db_list = db_info.values_list("db_address", "db_port",
                                        "db_username", "db_pwd").distinct()
     self.today = date.today()
     self.yesterday = datetime_delta(self.today, days=-1)
Example #19
0
 def __init__(self):
     self.today = date_to_str(date.today())
     self.yesterday = date_to_str(datetime_delta(date.today(), days=-1))