def test_update(self): Poll.objects.create(question="what's up?", pub_date=today) p = Poll.objects.get() p.pub_date = tomorrow p.save() update_change_reason(p, "future poll") update_record, create_record = p.history.all() self.assertRecordValues( create_record, Poll, { "question": "what's up?", "pub_date": today, "id": p.id, "history_change_reason": None, "history_type": "+", }, ) self.assertRecordValues( update_record, Poll, { "question": "what's up?", "pub_date": tomorrow, "id": p.id, "history_change_reason": "future poll", "history_type": "~", }, ) self.assertDatetimesEqual(update_record.history_date, datetime.now())
def update_or_create_override(cls, requesting_user, subsection_grade_model, feature=None, action=None, **override_data): """ Creates or updates an override object for the given PersistentSubsectionGrade. Args: requesting_user: The user that is creating the override (so we can record this action in a PersistentSubsectionGradeOverrideHistory record). subsection_grade_model: The PersistentSubsectionGrade object associated with this override. override_data: The parameters of score values used to create the override record. """ override, _ = PersistentSubsectionGradeOverride.objects.update_or_create( grade=subsection_grade_model, defaults=cls._prepare_override_params(subsection_grade_model, override_data), ) update_change_reason(override, feature) action = action or PersistentSubsectionGradeOverrideHistory.CREATE_OR_UPDATE PersistentSubsectionGradeOverrideHistory.objects.create( override_id=override.id, user=requesting_user, feature=feature, action=action, ) return override
def safe_update_change_reason(instance, reason): """ Wrapper around update_change_reason to catch exceptions. .. warning:: The implementation of django-simple-history's `update_change_reason` is very brittle, as it queries for a previous historical record that matches the attributes of the instance to update the ``change_reason``, which could end up updating the wrong record, or not finding it. If you already have control over the object, use `set_change_reason` before updating/deleting the object instead. That's more safe, since the attribute is passed to the signal and used at the creation time of the record. https://django-simple-history.readthedocs.io/en/latest/historical_model.html#change-reason # noqa """ try: update_change_reason(instance=instance, reason=reason) except Exception: log.exception( 'An error occurred while updating the change reason of the instance.', instance=instance, )
def test_delete_verify_change_reason_explicity(self): p = Poll.objects.create(question="what's up?", pub_date=today) poll_id = p.id p.delete() update_change_reason(p, "wrongEntry") delete_record, create_record = Poll.history.all() self.assertRecordValues( create_record, Poll, { "question": "what's up?", "pub_date": today, "id": poll_id, "history_change_reason": None, "history_type": "+", }, ) self.assertRecordValues( delete_record, Poll, { "question": "what's up?", "pub_date": today, "id": poll_id, "history_change_reason": "wrongEntry", "history_type": "-", }, )
def test_update_change_reason_with_excluded_fields(self): poll = PollWithExcludeFields( question="what's up?", pub_date=timezone.now(), place="The Pub" ) poll.save() update_change_reason(poll, "Test change reason.") most_recent = poll.history.order_by("-history_date").first() self.assertEqual(most_recent.history_change_reason, "Test change reason.")
def change_payment_handler(sender, instance, **kwargs): created = kwargs.get('created') instance.invoice.is_invoice_paid = instance.invoice.is_paid instance.invoice.save() instance.invoice.matter.save() if created: update_change_reason(instance, 'Payment was made')
def safe_update_change_reason(instance, reason): """Wrapper around update_change_reason to catch exceptions.""" try: update_change_reason(instance=instance, reason=reason) except Exception: log.exception( 'An error occurred while updating the change reason of the instance: obj=%s', instance, )
def setUp(self): self.supervisor1 = self.crear_supervisor_profile(rol=User.SUPERVISOR) self.supervisor2 = self.crear_supervisor_profile(rol=User.SUPERVISOR) self.agente1 = self.crear_agente_profile() self.agente2 = self.crear_agente_profile() self.campana1 = CampanaFactory(estado=Campana.ESTADO_ACTIVA) self.queue_campana_1 = QueueFactory(campana=self.campana1) QueueMemberFactory(member=self.agente1, queue_name=self.queue_campana_1) self.campana1.supervisors.add(self.supervisor1.user) self.campana2 = CampanaFactory(estado=Campana.ESTADO_ACTIVA) self.queue_campana_2 = QueueFactory(campana=self.campana2) QueueMemberFactory(member=self.agente2, queue_name=self.queue_campana_2) self.campana2.supervisors.add(self.supervisor2.user) self.contacto = ContactoFactory(id_externo='id_ext') self.campana3 = CampanaFactory(estado=Campana.ESTADO_ACTIVA) self.campana3.bd_contacto.genera_contactos([self.contacto]) self.campana3.supervisors.add(self.supervisor1.user) self.opcion_calificacion = OpcionCalificacionFactory( campana=self.campana1, tipo=OpcionCalificacion.GESTION) self.calificacion = CalificacionClienteFactory( opcion_calificacion=self.opcion_calificacion) update_change_reason(self.calificacion, 'calificacion') self.grabacion1 = GrabacionFactory.create( duracion=1, agente=self.agente1, callid=self.calificacion.callid, campana=self.campana1, id_cliente='-1') self.grabacion2 = GrabacionFactory(duracion=1, agente=self.agente1, campana=self.campana1) self.grabacion3 = GrabacionFactory(duracion=1, agente=self.agente1, campana=self.campana1) self.marca_campana1 = GrabacionMarcaFactory( callid=self.grabacion1.callid) self.marca_campana2 = GrabacionMarcaFactory( callid=self.grabacion2.callid) self.grabacion2_1 = GrabacionFactory.create(duracion=1, agente=self.agente2, campana=self.campana2) self.marca_campana2_1 = GrabacionMarcaFactory( callid=self.grabacion2_1.callid) self.grabacion3_1 = GrabacionFactory.create( tel_cliente=self.contacto.telefono, agente=self.agente2, campana=self.campana3)
def save(self): instance = super(CrispyTaskForm, self).save(commit=False) instance.slug = orig = slugify(instance.title) for x in itertools.count(1): if not Task.objects.filter(slug=instance.slug).exists(): break instance.slug = '%s-%d' % (orig, x) instance.save() update_change_reason(instance, 'Initial Task Creation') return instance
def test_asset_history(self): ''' 测试获取资产历史 asset/history ''' asset: Asset = Asset.objects.get(id=1) # 旧资产 asset.description = '修改信息' asset.save() update_change_reason(asset, '修改') response = self.client.post('/api/asset/history', json.dumps({'nid': 1}), content_type='json') self.assertEqual(response.json()['code'], 200)
def create_user(self): """Create the user account and send an invite email.""" user_name = self.cleaned_data["user_name"].strip() user_email = self.cleaned_data["user_email"] user = User.objects.create_user(name=user_name, email=user_email, password="") update_change_reason(user, self.message) if hasattr(user, "invite_user"): user.invite_user() return user
def updateArticleOnStock(stock_id): stock_articles = StockReceiptArticle.objects.filter(stock_receipt=stock_id) for stock_article in stock_articles: article = Article.objects.filter(pk=stock_article.article.id).get() converted_amount = convertUnits(stock_article.amount, stock_article.unit, article.unit) new_total_price = convertUnits(stock_article.total_price_with_vat, stock_article.unit, article.unit) # print("StockReceipt - mnozství: ", article.on_stock, "+", converted_amount, # " - cena: ", article.total_price, "+", new_total_price) article.on_stock += converted_amount article.total_price += new_total_price article.save() update_change_reason(article, 'Příjemka')
def test_datos_reporte_grafico_llamadas_analizan_no_atendidas_que_modifican_calificaciones( self, render_to_png, crea_reporte_pdf, crea_reporte_csv): # simulamos otra llamada a un contacto ya calificado y una modificación en la calificación # existente self.calif_gestion.observaciones = "Nueva observacion" self.calif_gestion.save() update_change_reason(self.calif_gestion, 'recalificacion') url = reverse('campana_reporte_grafico', args=[self.campana_activa.pk]) response = self.client.get(url, follow=True) estadisticas = response.context_data['graficos_estadisticas']['estadisticas'] atendidas_sin_calificacion = len([self.contacto_no_calificado]) self.assertEqual(estadisticas['calificaciones_cantidad'][-1], atendidas_sin_calificacion)
def test_textfield_history_change_reason2(self): # TextField instance is passed in init entry = TextFieldChangeReasonModel2.objects.create( greeting="what's up?") entry.greeting = "what is happening?" entry.save() update_change_reason(entry, 'Change greeting.') history = entry.history.all()[0] field = history._meta.get_field('history_change_reason') self.assertTrue(isinstance(field, models.TextField))
def productSTView(request, pk): log = Logs.objects.get(id=pk) productForm = ProductSTForm( instance = log, initial={'lastStocktakeTime': timezone.now()} ) if request.method == 'POST': productForm = ProductSTForm(request.POST, instance = log) oldAmt = log.productsLeft if productForm.is_valid(): log = productForm.save() newAmt = log.productsLeft #find loss if any loss = 0 if oldAmt <= newAmt: loss = 0 else: loss = (oldAmt - newAmt) log.product.amount = log.product.amount - loss log.product.save() r = getHistoryLabel(log.product) if r == "": r = "Kayıp ürün yok." reasonStr = "{} Tarihli Giriş İçin Sayım: ".format( log.logDate.strftime("%d-%m-%Y") ) + r update_change_reason(log.product, reasonStr ) loss = loss * log.price if loss == 0: r = "Zarar Yok." else: r = str(oldAmt - newAmt) + " adet ürün eksik. Zarar = " + str(loss) + " TL." reason = "*SAYIM: " + getHistoryLabel(log) + r update_change_reason(log, reason) message = str(log.product) + " adlı ürünün sayımı başarılı." messages.success(request, message) return redirect('/stocktakePage/') else: message = str(log.product) + " adlı ürünün sayımı başarısız." messages.warning(request, message) context = { 'form': productForm, } return render(request, 'accounts/updateStocktakeProduct.html', context)
def save(self, force_insert=False, force_update=False, using=None, update_fields=None): if self.id is None: self.reason = 'created' if self.id is not None: if self.reason == ('created' or 'no change reason' or ''): self.reason = 'no change reason' super(Reply, self).save(force_insert, force_update, using, update_fields) update_change_reason(self, self.reason)
def test_charfield_history_change_reason(self): # Default CharField and length entry = CharFieldChangeReasonModel.objects.create( greeting="what's up?") entry.greeting = "what is happening?" entry.save() update_change_reason(entry, "Change greeting.") history = entry.history.all()[0] field = history._meta.get_field("history_change_reason") self.assertTrue(isinstance(field, models.CharField)) self.assertTrue(field.max_length, 100)
def save(self, commit=True): # Get the user if it already exists user = self.get_existing_user() if not user: # Invite the user if they're new user = super().save(commit) user.invite_user() # Track who added this user update_change_reason(user, "Invited via authorized users view") # You will need to add the user to the publisher/advertiser in the view return user
def test_user_textfield_history_change_reason(self): # TextField instance is passed in init entry = UserTextFieldChangeReasonModel.objects.create( greeting="what's up?") entry.greeting = "what is happening?" entry.save() reason = "Change greeting" update_change_reason(entry, reason) history = entry.history.all()[0] field = history._meta.get_field("history_change_reason") self.assertTrue(isinstance(field, models.TextField)) self.assertEqual(history.history_change_reason, reason)
def test_default_textfield_history_change_reason(self): # TextField usage is determined by settings entry = DefaultTextFieldChangeReasonModel.objects.create( greeting="what's up?") entry.greeting = "what is happening?" entry.save() reason = "Change greeting" update_change_reason(entry, reason) history = entry.history.all()[0] field = history._meta.get_field("history_change_reason") self.assertTrue(isinstance(field, models.TextField)) self.assertEqual(history.history_change_reason, reason)
def save(self): """Do the work to save the payout.""" self._send_email() payout = self.publisher.payouts.create( date=timezone.now(), method=self.publisher.payout_method, amount=self.amount, start_date=self.start_date, end_date=self.end_date, status=EMAILED, ) update_change_reason(payout, "Payout via staff interface") return payout
def post(self, request): agenda_id = request.data.get('agenda_id') agente_id = request.data.get('agent_id') try: agenda = AgendaContacto.objects.get( id=agenda_id, tipo_agenda=AgendaContacto.TYPE_PERSONAL) except AgendaContacto.DoesNotExist: return Response(data={ 'status': 'ERROR', 'message': _('ID Agenda incorrecto') }) try: agente = agenda.campana.queue_campana.members.get(id=agente_id) except AgenteProfile.DoesNotExist: return Response(data={ 'status': 'ERROR', 'message': _('ID Agente incorrecto') }) supervisor_profile = self.request.user.get_supervisor_profile() campanas_asignadas_actuales = supervisor_profile.campanas_asignadas_actuales( ) if not campanas_asignadas_actuales.filter( id=agenda.campana.id).exists(): return Response( data={ 'status': 'ERROR', 'message': _('No tiene permiso para editar esta Agenda') }) agenda.agente = agente agenda.save() calificacion = CalificacionCliente.objects.get( contacto=agenda.contacto, opcion_calificacion__campana=agenda.campana) calificacion.agente = agente calificacion.save() update_change_reason(calificacion, 'reasignacion') return Response( data={ 'status': 'OK', 'agenda_id': agenda_id, 'agent_name': agente.user.get_full_name() })
def _calificar_form(self, calificacion_form): calificacion_nueva = False if calificacion_form.instance.pk is None: calificacion_nueva = True self.object_calificacion = calificacion_form.save(commit=False) self.object_calificacion.callid = self._obtener_call_id() self.object_calificacion.agente = self.agente self.object_calificacion.contacto = self.contacto # TODO: Ver si hace falta guardar que es una llamada manual # El parametro manual no viene mas if self.object is None: es_calificacion_manual = 'manual' in self.kwargs and self.kwargs['manual'] self.object_calificacion.es_calificacion_manual = es_calificacion_manual self.object_calificacion.save() # modificamos la entrada de la modificación en la instancia para así diferenciar # cambios realizados directamente desde una llamada de las otras modificaciones update_change_reason(self.object_calificacion, self.kwargs.get('from')) # check metadata en calificaciones de no accion y eliminar self._check_metadata_no_accion_delete(self.object_calificacion) if self.object_calificacion.es_gestion() and \ not self.campana.tiene_interaccion_con_sitio_externo: return redirect(self.get_success_url_venta()) else: message = _('Operación Exitosa! ' 'Se llevó a cabo con éxito la calificación del cliente') messages.success(self.request, message) if self.object_calificacion.es_agenda() and calificacion_nueva: return redirect(self.get_success_url_agenda()) elif self.object_calificacion.es_agenda(): # se esta modificando una calificacion de agenda existente # con una agenda creada agenda_calificacion = AgendaContacto.objects.filter( contacto=self.contacto, campana=self.campana, agente=self.agente).first() if agenda_calificacion is not None: return redirect(self.get_success_url_agenda_update(agenda_calificacion.pk)) else: return redirect(self.get_success_url_agenda()) elif self.kwargs['from'] == 'reporte': return redirect(self.get_success_url_reporte()) else: return redirect(self.get_success_url())
def prefilledAddProduct(request, pk): barcodeInstance = pk product = Product.objects.filter(barcode=barcodeInstance)[0] productForm = ProductForm(initial={ 'editor': request.user.username, 'name': product.name, 'vendor': product.vendor, 'barcode': product.barcode, 'category': product.category, 'brand': product.brand, 'model': product.model, 'description': product.description, 'photo': product.photo, 'code': product.code }) invoiceForm = InvoiceForm() if request.method == 'POST': invoiceForm = InvoiceForm(request.POST) productForm = ProductForm(request.POST, request.FILES) if invoiceForm.is_valid() and productForm.is_valid() : newProduct = productForm.save() update_change_reason(newProduct, "Ürün eklendi.") newInvoice = invoiceForm.save() #fill invoice based on information in newProduct sum = newProduct.price * newProduct.amount newInvoice.sum = sum newInvoice.vendor = newProduct.vendor newInvoice.date = newProduct.dateBought newInvoice.save() #link invoice to product newProduct.invoice = newInvoice newProduct.save() update_change_reason(newProduct, "Fatura eklendi.") message = str(newProduct.name) + " adlı ürün başarıyla eklendi." messages.success(request, message) return redirect('/') else: message = str(product.name) + " adlı ürün eklenemedi." messages.warning(request, message) context = { 'productForm': productForm, 'invoiceForm': invoiceForm } return render(request, 'accounts/product-form.html', context)
def updateArticleOnStock(stock_id, comment, fake): stock_articles = StockIssueArticle.objects.filter(stock_issue=stock_id) messages = '' for stock_article in stock_articles: article = Article.objects.filter(pk=stock_article.article.id).get() converted_amount = convertUnits(stock_article.amount, stock_article.unit, article.unit) if article.on_stock < 0 or article.on_stock - converted_amount < 0: messages += "{} - na výdejce {}, na skladu {}<br/>".format( stock_article.article, converted_amount, article.on_stock) if not fake: new_total_price = convertUnits( stock_article.total_average_price_with_vat, stock_article.unit, article.unit) article.on_stock -= round(converted_amount, 2) article.total_price -= round(new_total_price, 2) article.save() update_change_reason(article, 'Výdej - ' + comment) return messages
def updateProduct(request, pk): product = Product.objects.get(id=pk) productForm = ProductForm(initial={'editor' : request.user.username}, instance = product) if request.method == 'POST': productForm = ProductForm(request.POST, request.FILES, instance = product) if productForm.is_valid(): productForm.save() update_change_reason(product, getHistoryLabel(product)) successMessage = str(product.name) + " adlı ürün başarıyla güncellendi." messages.success(request, successMessage) return redirect('/products/') else: successMessage = str(product.name) + " adlı ürün güncellenemedi." messages.warning(request, failedMessage) context = { 'productForm': productForm } return render(request, 'accounts/product-form.html', context)
def updateArticleOnStock(stock_id, fake): stock_articles = StockIssueArticle.objects.filter(stock_issue=stock_id) messages = '' for stock_article in stock_articles: article = Article.objects.filter(pk=stock_article.article.id).get() converted_amount = convertUnits(stock_article.amount, stock_article.unit, article.unit) if article.on_stock < 0 or article.on_stock - converted_amount < 0: messages += "{} - na výdejce {}, na skladu {}<br/>".format( stock_article.article, converted_amount, article.on_stock) if not fake: new_total_price = convertUnits(stock_article.total_average_price_with_vat, stock_article.unit, article.unit) # print("StockIssue | mnozství: ", article.on_stock, "-", converted_amount, # "| cena:", article.total_price, "-", new_total_price) article.on_stock -= converted_amount article.total_price -= new_total_price article.save() update_change_reason(article, 'Výdejka') return messages
def _calificar_form(self, calificacion_form): self.object_calificacion = calificacion_form.save(commit=False) self.object_calificacion.es_gestion() self.object_calificacion.callid = self._obtener_call_id() self.object_calificacion.agente = self.agente self.object_calificacion.contacto = self.contacto # TODO: Ver si hace falta guardar que es una llamada manual # El parametro manual no viene mas if self.object is None: es_calificacion_manual = 'manual' in self.kwargs and self.kwargs[ 'manual'] self.object_calificacion.es_calificacion_manual = es_calificacion_manual self.object_calificacion.save() # modificamos la entrada de la modificación en la instancia para así diferenciar # cambios realizados directamente desde una llamada de las otras modificaciones update_change_reason(self.object_calificacion, self.kwargs.get('from')) # Finalizar relacion de contacto con agente # Optimizacion: si ya hay calificacion ya se termino la relacion agente contacto antes. if self.campana.type == Campana.TYPE_PREVIEW and self.object is None: self.campana.gestionar_finalizacion_relacion_agente_contacto( self.contacto.id) # check metadata en calificaciones de no accion y eliminar self._check_metadata_no_accion_delete(self.object_calificacion) if self.object_calificacion.es_gestion() and \ not self.campana.tiene_interaccion_con_sitio_externo: return redirect(self.get_success_url_venta()) else: message = _( 'Operación Exitosa! ' 'Se llevó a cabo con éxito la calificación del cliente') messages.success(self.request, message) if self.object_calificacion.es_agenda(): return redirect(self.get_success_url_agenda()) elif self.kwargs['from'] == 'reporte': return redirect(self.get_success_url_reporte()) else: return redirect(self.get_success_url())
def create_publisher(self): """Create the publisher.""" site = self.cleaned_data["site"].strip() keywords = self.cleaned_data["keywords"].strip() publisher = Publisher.objects.create( name=site, slug=slugify(site), default_keywords=keywords, ) # TODO: Allow configuring of publisher groups in form group_obj = PublisherGroup.objects.filter( slug=self.DEFAULT_GROUP).first() if group_obj: group_obj.publishers.add(publisher) update_change_reason(publisher, self.message) return publisher
def test_delete_verify_change_reason_explicity(self): p = Poll.objects.create(question="what's up?", pub_date=today) poll_id = p.id p.delete() update_change_reason(p, 'wrongEntry') delete_record, create_record = Poll.history.all() self.assertRecordValues(create_record, Poll, { 'question': "what's up?", 'pub_date': today, 'id': poll_id, 'history_change_reason': None, 'history_type': "+" }) self.assertRecordValues(delete_record, Poll, { 'question': "what's up?", 'pub_date': today, 'id': poll_id, 'history_change_reason': 'wrongEntry', 'history_type': "-" })
def test_delete_verify_change_reason_explicity(self): p = Poll.objects.create(question="what's up?", pub_date=today) poll_id = p.id p.delete() update_change_reason(p, 'wrongEntry') delete_record, create_record = Poll.history.all() self.assertRecordValues(create_record, Poll, { 'question': "what's up?", 'pub_date': today, 'id': poll_id, 'history_change_reason': None, 'history_type': "+" }) self.assertRecordValues(delete_record, Poll, { 'question': "what's up?", 'pub_date': today, 'id': poll_id, 'history_change_reason': 'wrongEntry', 'history_type': "-" })
def test_update(self): Poll.objects.create(question="what's up?", pub_date=today) p = Poll.objects.get() p.pub_date = tomorrow p.save() update_change_reason(p, 'future poll') update_record, create_record = p.history.all() self.assertRecordValues(create_record, Poll, { 'question': "what's up?", 'pub_date': today, 'id': p.id, 'history_change_reason': None, 'history_type': "+" }) self.assertRecordValues(update_record, Poll, { 'question': "what's up?", 'pub_date': tomorrow, 'id': p.id, 'history_change_reason': 'future poll', 'history_type': "~" }) self.assertDatetimesEqual(update_record.history_date, datetime.now())