def check_lead_duplication(user, fields): """ Finds leads by fields and check duplications and sales # Провалено, Лид <дата создания=None> не существует в системе # Успешно, Лид <дата создания> никому не продавался # Успешно, Лид <дата создания> никому не продавался, аудировался вами # Провалено, Лид <дата создания> был продан N раз # Провалено, Лид <дата создания> был продан вам вне системы # Провалено, Лид <дата создания> не продавался, имеет N дубликатов # Провалено, Лид <дата создания> не продавался, имеет N дубликатов, аудировался вами # Провалено, Лид <дата создания> был продан N раз, имеет N дубликатов, аудировался вами :param check_fields: поля для проверки на подмену :type check_fields: dict {f_name: f_value, f_name: f_value} :raise: audit.audit.AuditError :return: { 'success': bool, 'resolution': str, 'created': DateTime, 'your_audits': list of DateTime, 'duplicates': list of DateTime, 'sales': list of DateTime, } """ fields = check_input_fields(fields) fields = _check_input_required_fieldsets(fields) leads = _load_leads_by_fields(fields) res = _check_lead_duplication(user, leads) Audit.log(user, 'lead_duplication', fields, leads) return res
def test__check_lead_duplication_fail_if_your_leads_found_and_audited_by_others( self): you = User(id=1) your_project = Project(user=you) your_pixel = Pixel(project=your_project) someone = User(id=2) sometwo = User(id=3) someone_audit1 = Audit(processed=strptime('2018-02-26'), user=someone) sometwo_audit2 = Audit(processed=strptime('2018-02-27'), user=sometwo) your_lead1 = Lead(pixel=your_pixel, created=strptime('2018-02-24')) your_lead2 = Lead(pixel=your_pixel, created=strptime('2018-02-25')) your_lead3 = Lead(pixel=your_pixel, created=strptime('2018-02-26')) with mock.patch( 'collector.models.analytics.Lead.audits') as mock_manager: mock_manager.all.return_value = [someone_audit1, sometwo_audit2] leads = [ your_lead1, your_lead2, your_lead3, ] res = lead_duplication._check_lead_duplication(you, leads) self.assertEquals( { 'success': False, 'resolution': 'Lead was sold 2 times', 'created': strptime('2018-02-26'), 'your_audits': [], 'duplicates': [strptime('2018-02-25'), strptime('2018-02-24')], 'sales': [strptime('2018-02-27'), strptime('2018-02-26')] }, res)
def check_lead_authenticity(pixel, check_fields): """ :param pixel: пиксел для которого проверяем лиды :type pixel: collector.models.Pixel :param check_fields: поля для проверки на подмену :type check_fields: dict {f_name: f_value} :raise: audit.error.AuditError :rtype: tuple :return: (authentic: bool, fields: dict) - authentic: bool - если все поля совпали то true, иначе false fields: { field-name1: bool true - совпало, false - не совпало ip: bool, created: bool, confirm: bool, field-name2: bool } список полей : совпало / не совпало, если ни один лид не найден пустой объект 1. Делим все поля на те что обязательные в мэппинге и остальные 2. Ищем лиды по тем что в мэппинге 3. сравниваем и остальные поля 4. в филдс в ответе выводим все совпало/несовпало 5. Нужен интерфейс вызова данного апи 5.1 В нем должны требоваться все поля из меппинга 5.2 Также должна быть возможность добавить поля неописанные в меппинге """ req_fields_mapping = pixel.fields_mapping.filter( required=True).select_related('target_field') required_fields = _parse_required_fields(req_fields_mapping, check_fields) check_fields = check_input_fields(check_fields) leads = load_leads_by_fields(required_fields, pixel) res = _check_lead_authenticity(leads, check_fields) Audit.log(pixel.project.user, 'lead_authenticity', check_fields, leads) return res
def audit_log_task(self, audit_dict): """ Celery task to asynchronously create an audit record. """ audit = Audit(**audit_dict) try: audit.save() except (OperationalError, IntegrityError) as err: self.retry(countdown=60, max_retries=15, exc=err)
def create_audit(template_id): template = AuditTemplate.objects.get(template_id=template_id) inventory_items = fetch_inventory_items(template) # Creating the Audit and appending the template ID to it as well as the items audit = Audit(template_id=template) audit.save() # Didnt find another way of adding the list directly in the ManytoManyfield for item in inventory_items: audit.inventory_items.add(item)
def test_case_title_saved(self): Audit.objects.all().delete() case = Case.objects.create(created_by=self.user, name="Foobar") case_title = str(case) audit = Audit(type="CREATE", case_id=case.id) audit_id = audit.id # Unsaved, there should be no json field data assert not audit.data # But we should get a case title self.assertEqual(audit.case_title, case_title) # That auto-populates the json field assert audit.data.get("case_title") audit.save() # That we see in a retrieved model saved_audit = Audit.objects.filter(id=audit_id)[0] self.assertEqual(saved_audit.data["case_title"], case_title) self.assertEqual(saved_audit.case_title, case_title)
def test__check_lead_duplication_success_if_one_your_lead_found_and_audited_by_you( self): you = User(id=1) your_project = Project(user=you) your_pixel = Pixel(project=your_project) your_audit = Audit(processed=strptime('2018-02-27'), user=you) your_lead = Lead(pixel=your_pixel, created=strptime('2018-02-26')) with mock.patch( 'collector.models.analytics.Lead.audits') as mock_manager: mock_manager.all.return_value = [your_audit] leads = [your_lead] res = lead_duplication._check_lead_duplication(you, leads) self.assertEquals( { 'success': True, 'resolution': 'You already audited this lead 1 times', 'created': strptime('2018-02-26'), 'your_audits': [strptime('2018-02-27')], 'duplicates': [], 'sales': [] }, res)
def test_export_compatible(self, audits): export = QuerysetExporter(queryset=audits, file_format="csv") export_file = export.do_export(compatible=True) export_file.seek(0) entry = export_file.readline() assert entry.strip("\n") == ",".join(Audit.row_columns())