def test_deal_model(self): """ test deal models """ # TO DO Change procedure to a fresh started deal self.assertEqual(self.deal.status, DealStatus.PLACED) self.deal.set_placed() self.assertEqual(self.deal.status, DealStatus.PLACED) self.assertIsInstance(self.deal.partner_pulls, list) self.assertIsInstance(self.deal.get_users()[0], User) self.assertIsInstance(self.deal.get_users()[1], User) deal = Deal.by_users(self.deal.user2, self.deal.user1)[0] self.assertEqual(deal, self.deal) deal = Deal.by_users(self.random_object(User), self.random_object(User), create=True)[0] self.assertIsInstance(deal, Deal) deal = Deal.get_or_create(self.deal.user2, self.deal.user1)[0] self.assertEqual(deal, self.deal) self.deal.set_accepted() self.assertEqual(self.deal.status, DealStatus.ACCEPTED) self.assertEqual(self.deal.level, self.deal.level) self.assertEqual(self.deal.quality, self.deal.quality) self.assertIsInstance(self.deal.can_accept(self.deal.user1), bool) self.assertIsInstance(self.deal.can_accept(self.deal.user2), bool) _ = """
def dispatch(self, request, *args, **kwargs): self.kwargs.update(kwargs) for key, value in self.request.GET.items(): self.kwargs[key] = value[0] if isinstance(value, list) else value for key, value in self.request.POST.items(): self.kwargs[key] = value[0] if isinstance(value, list) else value self.action = self.kwargs.get('action') self.permissions = Deal.get_permissions(self.request) try: self.deal = self.model.objects.get(pk=self.kwargs.get('pk')) self.branch = self.deal.branch except (Deal.DoesNotExist, ValueError): pass try: self.client = Client.objects.get(pk=request.GET.get('client')) except (ValueError, Client.DoesNotExist): pass if not self.branch: try: self.branch = Branch.objects.get( pk=(self.request.GET.get('branch') or self.request.POST.get('branch'))) except Branch.DoesNotExist: try: self.branch = self.client.rel_deals.all().exclude( deal__branch=None).last().deal.branch except AttributeError: self.branch = User.objects.get(pk=self.request.user.person.id).manager_branches.first() or \ Branch.objects.first() return super().dispatch(request, *args, **kwargs)
def dispatch(self, request, *args, **kwargs): self.permissions = Deal.get_permissions(request) self.service, self.service_set = self.set_service() self.timezone = self.service_set['timezone'] self.action = kwargs.get('action') try: self.day_start = datetime.strptime(request.GET.get('day'), '%Y%m%d') except TypeError: pass get_day = request.GET.get('get_day') if not self.day_start or get_day == 'current': self.day_start = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0) if get_day == 'prev': self.day_start -= timedelta(days=1) elif get_day == 'next': self.day_start += timedelta(days=1) # self.day_start += timedelta(hours=self.timezone) self.day_finish = self.day_start + timedelta(hours=24) self.deals = self.get_deals() return super().dispatch(request, *args, **kwargs)
def dispatch(self, request, *args, **kwargs): self.today = date.today() self.permissions = Deal.get_permissions(request) self.days = int(request.GET.get('days', 7)) self.branch = Branch.objects.get(pk=request.GET.get('branch', 65)) self.timezone = self.branch.city.timezone try: self.masters = User.objects.filter( pk__in=json.loads(request.GET.get('masters'))) except (TypeError, json.decoder.JSONDecodeError): pass try: self.start = datetime.strptime(request.GET.get('current_day'), '%Y-%m-%d').date() except (ValueError, TypeError): self.start = self.today steps = dict(prev=-self.days, next=self.days) step = request.GET.get('step') if step == 'current': self.start = self.today else: self.start += timedelta(days=steps.get(request.GET.get('step'), 0)) # Если неделя (7 дней), то первый день берем понедельник if self.days == 7: self.start = get_week_start(self.start) self.start += timedelta(hours=self.timezone) self.end = self.start + timedelta(days=self.days) print('+++ 0') for deal in Deal.objects.filter(services=2): print('+++', deal) return super().dispatch(request, *args, **kwargs)
def dispatch(self, request, *args, **kwargs): self.permissions = Deal.get_permissions(request) self.client = self.request.GET.get('client', None) self.paging = dict(range=9, page_items=30, page=1, pages=1) self.paging['page'] = int(request.GET.get('page', 1)) self.filters = self.set_filters(request) self.filters_q = self.model.get_filters_q(self.request, filters=self.filters) return super().dispatch(request, *args, **kwargs)
def dispatch(self, request, *args, **kwargs): self.permissions = Deal.get_permissions(request) self.account_timezone = request.user.person.timezone or 0 try: self.client = Client.objects.get(pk=self.request.GET.get('client')) except Client.DoesNotExist: self.deal = Deal.objects.get(pk=self.request.GET.get('deal')) except Deal.DoesNotExist: pass return super().dispatch(request, *args, **kwargs)
def sync2db(self, art_list): """ 把文章列表写入物品数据库 @param art_list: 文章列表 @type art_list: List """ sites = Site.objects.all() cities = City.objects.all() for art in art_list: print art['title'] if art['url'] != "": site = self._get_site(sites, art['url']) city = self._get_city(cities, art['city']) print site, city if city is None: continue if site is None: continue try: deal = Deal.objects.get(site=site, name=art['title'], url=art['url']) except: deal = Deal( site = site, name = art['title'], detail = art['body'].replace(CMS_NAME+'/uploads/allimg', 'site_media/allimg'), current_price = str(art['price']), original_price = str(art['original_price']), url = art['url'], buy_url = art['url'], company_name = art['shop_name'], company_detail = art['shop_detail'], volunteer = art['volunteer'], begin_at = self._format_datetime(art['begin']), end_at = self._format_datetime(art['end']), accomplish_at = self._format_datetime(art['deadline']), category = self._get_category(art['category']), logo = art['litpic'].replace(CMS_NAME+'/uploads/allimg', 'site_media/allimg'), ) deal.save() deal.city.add(city) deal.begin_at = self._format_datetime(art['begin']) deal.end_at = self._format_datetime(art['end']) deal.status = self._get_status(deal.begin_at, deal.end_at) if art['tags'] != "": deal.tags = art['tags'] deal.save()
def dispatch(self, request, *args, **kwargs): self.permissions = Deal.get_permissions(request) self.filters = self.set_filters(request) if not self.filters['data']['branch']: # TODO make default branch self.filters['data']['branch'] = self.filters['fields']['branch']['widget']['choices'][0]['value'] self.filters_q = self.model.get_filters_q(self.request, filters=self.filters) self.branch = Branch.objects.get(pk=self.filters['data']['branch']) self.timezone = self.branch.city.timezone stage_values = ['id', 'step', 'name', 'label', 'color', 'background_color'] self.stages = [stage for stage in Stage.objects.exclude(name__in=['cancel', 'done']).values(*stage_values)] return super().dispatch(request, *args, **kwargs)
def dispatch(self, request, *args, **kwargs): self.permissions = Deal.get_permissions(request) self.timezone = request.user.person.timezone self.today = datetime.combine(date.today(), datetime.min.time()) self.client = self.request.GET.get('client', None) self.deal = self.request.GET.get('deal', None) self.filters = self.set_filters(request) if not self.filters['data']['time_planned']: self.filters['data']['time_planned'] = [ (self.today - timedelta(days=2)).strftime('%d.%m.%Y'), (self.today + timedelta(days=2)).strftime('%d.%m.%Y') ] self.filters_q = self.model.get_filters_q(self.request, filters=self.filters) return super().dispatch(request, *args, **kwargs)
def dispatch(self, request, *args, **kwargs): self.permissions = Deal.get_permissions(request) self.action = kwargs.get('action') self.list_display = ['id'] + getattr(self.model, 'list_display', []) self.perms = self.model.get_permissions(request) self.summary = dict( ordered=['deals', 'done', 'cancel', 'new', 'control', 'cost', 'paid', 'paid_non_cash'], labels=dict(deals='Сделок', done='Успешных', cancel='Отмененных', new='Правок', control='Контролей', cost='На сумму', paid='Всего оплачено', paid_non_cash='В том числе безнал'), values=dict(deals=0, done=0, cancel=0, new=0, control=0, cost=Decimal(0.0), paid=Decimal(0.0), paid_non_cash=Decimal(0.0)) ) self.filters = self.set_filters(request) if not request.user.has_perm('Администраторы'): person_id = request.user.person.id self.permission_q = Q(branch__managers=person_id) return super().dispatch(request, *args, **kwargs)
def dispatch(self, request, *args, **kwargs): self.permissions = Deal.get_permissions(request) self.branch = Branch.objects.get(pk=request.GET.get('branch', 65)) self.timezone = self.branch.city.timezone try: self.start = datetime.strptime(request.GET.get('current_day'), '%Y-%m-%d').date() except (ValueError, TypeError): self.start = date.today() steps = dict(prev=-1, next=32) step = request.GET.get('step', None) if not self.start or step == 'current': self.start = date.today() elif step: self.start += timedelta(days=steps.get(step)) self.start += timedelta(hours=self.timezone) # timezone self.start = self.start.replace(day=1) self.end = self.start.replace(day=calendar.monthrange(self.start.year, self.start.month)[1]) return super().dispatch(request, *args, **kwargs)
def post(self, request): file_serializer = FileUploadSerializer(data=request.data) file_serializer.is_valid(raise_exception=True) file = file_serializer.validated_data['deals'] decoded_file = file.read().decode('utf-8').splitlines() reader = csv.DictReader(decoded_file) deals = [] for row in reader: dict_row = dict(row) user_serializer = UsersSerializer(data=dict_row) user_serializer.is_valid(raise_exception=True) user, created = Users.objects.get_or_create( username=user_serializer.validated_data['username']) gem_serializer = GemSerializer(data=dict_row) gem_serializer.is_valid(raise_exception=True) gem, created = Gem.objects.get_or_create( title=gem_serializer.validated_data['title']) deal_serializer = DealSerializer(data=dict_row) deal_serializer.is_valid(raise_exception=True) deal = Deal( customer=user, item=gem, total=deal_serializer.validated_data['total'], quantity=deal_serializer.validated_data['quantity'], date=deal_serializer.validated_data['date'], ) deals.append(deal) Deal.objects.bulk_create(deals) content = [] for deal in deals: response_serializer = DealSerializer(deal) content.append(response_serializer.data) return Response(content, status=status.HTTP_201_CREATED)
def dispatch(self, request, *args, **kwargs): self.permissions = Deal.get_permissions(request) return super().dispatch(request, *args, **kwargs)
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.initial.update(kwargs.get('initial', {})) # print('INITIAL', self.initial) self.fields['interval'].initial = self.initial.get('interval') try: self.branch = Branch.objects.get(pk=self.initial.get('branch')) timezone = self.branch.city.timezone except Branch.DoesNotExist: self.branch = None timezone = self.instance.branch.city.timezone self.request = self.initial.get('request') self.old_mlm_agent = self.instance.mlm_agent if self.instance else None self.fields['start_datetime'].label = 'Время сеанса' if 'instance' in kwargs: if not self.fields['interval'].initial: if self.instance.start_datetime and self.instance.finish_datetime: interval = (self.instance.finish_datetime - self.instance.start_datetime).seconds / 60 else: interval = self.branch.interval interval = interval.hour * 60 + interval.minute self.fields['interval'].initial = interval if self.instance.start_datetime: self.fields[ 'start_datetime'].initial = self.instance.start_datetime + timedelta( hours=timezone) self.initial['start_datetime'] = self.fields[ 'start_datetime'].initial if self.instance.finish_datetime: self.fields[ 'finish_datetime'].initial = self.instance.finish_datetime + timedelta( hours=timezone) self.initial['finish_datetime'] = self.fields[ 'finish_datetime'].initial elif 'data' not in kwargs: self.fields['stage'].initial = self.fields['stage'].queryset.get( name='new').id self.fields['master'].initial = Deal.get_master(self.branch) if self.initial.get('start_iso'): self.fields['start_datetime'].initial = \ datetime.strptime(self.initial.get('start_iso'), '%Y-%m-%dT%H:%M') self.initial['start_datetime'] = self.fields[ 'start_datetime'].initial if self.initial.get('end_iso'): self.fields['finish_datetime'].initial = \ datetime.strptime(self.initial.get('end_iso'), '%Y-%m-%dT%H:%M') self.fields['interval'].initial = ( self.fields['finish_datetime'].initial - self.fields['start_datetime'].initial).seconds / 60 if not self.fields['interval'].initial and self.initial.get( 'interval'): self.fields['interval'].initial = int(self.initial.get('interval')) elif not self.fields['interval'].initial: self.fields[ 'interval'].initial = self.branch.interval.hour * 60 + self.branch.interval.minute null_list = ['0.00', Decimal(0.0)] self.fields['cost'].initial = '' if self.fields[ 'cost'].initial in null_list else self.fields['cost'].initial self.fields['paid'].initial = '' if self.fields[ 'paid'].initial in null_list else self.fields['paid'].initial self.fields['paid_non_cash'].initial = '' if self.fields['paid_non_cash'].initial in null_list \ else self.fields['paid_non_cash'].initial
def task_resp(request): resp = {} if request.method != 'POST': resp['status'] = 1 resp['message'] = 'Wrong http method!' return HttpResponse(json.dumps(resp), content_type = 'application/json') task_id = request.POST['task_id'] #owner_id = request.POST['owner_id'] user_id = request.POST['user_id'] task = None try: task = Task.objects.select_for_update().filter(id=task_id) except: resp['status'] = '7' resp['message'] = 'datebase locked!' return HttpResponse(json.dumps(resp), content_type='application/json') if not task.exists(): resp['status'] = 2 resp['message'] = 'No such task' return HttpResponse(json.dumps(resp), content_type='application/json') elif len(task) > 1: resp['status'] = 3 resp['message'] = 'Too many tasks found' return HttpResponse(json.dumps(resp), content_type='application/json') if task[0].status == 1: resp['status'] = 4 resp['message'] = 'Task is already toke by others' return HttpResponse(json.dumps(resp), content_type='application/json') user = User.objects.filter(id=user_id) if not user.exists(): resp['status'] = 5 resp['message'] = 'No such user' return HttpResponse(json.dumps(resp), content_type='application/json') if len(user) > 1: resp['status'] = 6 resp['message'] = 'Too many user found, impossible!' return HttpResponse(json.dumps(resp), content_type='application/json') if user[0].status == 0: resp['status'] = 7 resp['message'] = 'Not authenticated yet!' return HttpResponse(json.dumps(resp), content_type='application/json') if task[0].owner.id == user[0].id: resp['status'] = 8 resp['message'] = 'You can\'t response to your own task!' return HttpResponse(json.dumps(resp), content_type='application/json') task[0].status = 1 task[0].save() deal = Deal(task = task[0], needer = task[0].owner, helper=user[0], build_time=datetime.datetime.now()) deal.save() if deal.id is None: resp['status'] = 7 resp['message'] = 'Failed to create new deal' return HttpResponse(json.dumps(resp), content_type='application/json') dealinfo = deal.to_dict() neederinfo = deal.needer.to_dict() helperinfo = deal.helper.to_dict() dealinfo['needer'] = neederinfo dealinfo['helper'] = helperinfo dealinfo['task'] = task[0].id resp['status'] = 0 resp['message'] = 'Success' resp['data'] = dealinfo return HttpResponse(json.dumps(resp), content_type='application/json')
def publish(self): for storage in self.storages: deal = Deal.objects.get_deal_by_url(storage.url) s = pickle.loads(str(storage.content)) if deal is None: deal = Deal() deal.url = storage.url deal.name = s.get('name', self.publishrules.get('name').default_value) deal.detail = s.get('detail', self.publishrules.get('detail').default_value) deal.site_id = s.get('site_id', self.publishrules.get('site_id').default_value) deal.current_price = s.get('current_price', self.publishrules.get('current_price').default_value) if len(deal.current_price) > 5: deal.current_price = self.publishrules.get('current_price').default_value if deal.current_price == '': deal.current_price = self.publishrules.get('current_price').default_value deal.original_price = s.get('original_price', self.publishrules.get('original_price').default_value) if deal.original_price == '': deal.original_price = self.publishrules.get('original_price').default_value deal.category_id= s.get('category_id', self.publishrules.get('category_id').default_value) deal.company_name = s.get('company_name', self.publishrules.get('company_name').default_value) deal.company_detail= s.get('company_detail', self.publishrules.get('company_detail').default_value) deal.volunteer = s.get('volunteer', self.publishrules.get('volunteer').default_value) if deal.volunteer == '': deal.volunteer = self.publishrules.get('volunteer').default_value deal.min_actor = s.get('min_actor', self.publishrules.get('min_actor').default_value) deal.buy_url = s.get('buy_url', self.publishrules.get('buy_url').default_value) if deal.min_actor == '': deal.min_actor = self.publishrules.get('min_actor').default_value try: deal.end_at = datetime.datetime.fromtimestamp(s.get('end_at')) except: deal.end_at = datetime.date.today() + datetime.timedelta(days=1) try: path = re.findall('src="(.*?)"', s.get('logo'))[0] except: path = self.publishrules.get('logo').default_value deal.logo = path try: deal.status = s.get('status', self.publishrules.get('status').default_value) except: pass #deal.save() try: deal.save() city = City.objects.get(pk=s.get('city_id', self.publishrules.get('city_id').default_value)) deal.city.add(city) except: print "faild : %s " % deal.url pass else: if self.publishrules.get('name').auto_update: deal.name = s.get('name', self.publishrules.get('name').default_value) if self.publishrules.get('detail').auto_update: deal.detail = s.get('detail', self.publishrules.get('detail').default_value) if self.publishrules.get('site_id').auto_update: deal.site_id = s.get('site_id', self.publishrules.get('site_id').default_value) if self.publishrules.get('current_price').auto_update: deal.current_price = s.get('current_price', self.publishrules.get('current_price').default_value) if len(deal.current_price) > 8 or deal.current_price == '': deal.current_price = self.publishrules.get('current_price').default_value if self.publishrules.get('original_price').auto_update: deal.original_price = s.get('original_price', self.publishrules.get('original_price').default_value) if deal.original_price == '': deal.original_price = self.publishrules.get('original_price').default_value if self.publishrules.get('category_id').auto_update: deal.category_id= s.get('category_id', self.publishrules.get('category_id').default_value) deal.company_name = s.get('company_name', self.publishrules.get('company_name').default_value) deal.company_detail= s.get('company_detail', self.publishrules.get('company_detail').default_value) deal.volunteer = s.get('volunteer', self.publishrules.get('volunteer').default_value) deal.min_actor = s.get('min_actor', self.publishrules.get('min_actor').default_value) deal.buy_url = s.get('buy_url', self.publishrules.get('buy_url').default_value) if deal.min_actor == '': deal.min_actor = self.publishrules.get('min_actor').default_value if deal.volunteer == '': deal.volunteer = self.publishrules.get('volunteer').default_value try: deal.end_at = datetime.datetime.fromtimestamp(s.get('end_at')) except: deal.end_at = datetime.date.today() + datetime.timedelta(days=1) try: path = re.findall('src="(.*?)"', s.get('logo').replace('\'', '"'))[0] except: path = self.publishrules.get('logo').default_value deal.logo = path if self.publishrules.get('category_id').auto_update: pass #deal.category_id= s.get('category_id', self.publishrules.get('category_id').default_value) try: if self.publishrules.get('status').auto_update: deal.status= s.get('status', self.publishrules.get('status').default_value) except: print "status faild : %s" % deal.url pass #deal.save() try: deal.save() city = City.objects.get(pk=s.get('city_id', self.publishrules.get('city_id').default_value)) deal.city.clear() deal.city.add(city) except: print "faild : %s " % deal.url pass