def activity_play(request, slug): activity_class_path = settings.ACTIVITIES.get(slug) if activity_class_path is None: raise Http404 Activity = load_path_attr(activity_class_path) activity_state = get_activity_state(request.user, slug) if activity_state is None: log( user=request.user, action="ACTIVITY_ERROR", extra={ "error": "not started", "slug": slug, } ) # @@@ user message return redirect("dashboard") activity = Activity(activity_state.latest, activity_state) activity_play_signal.send(sender=request.user, slug=slug, activity_occurrence_state=activity_state.latest, request=request) return activity.handle_request(request)
def user(request, id): context = {} user_ = get_object_or_404(User, id=id) if request.method == 'POST': # make a copy because it's mutable in the form before = copy.copy(user_) # expand the many-to-many field before changing it in the form before.__groups = [unicode(x) for x in before.groups.all()] form = forms.EditUserForm(request.POST, instance=user_) if form.is_valid(): form.save() log(request.user, 'user.edit', { 'change': notice_change(before, user_), 'id': user_.id, }) messages.success( request, 'User %s update saved.' % user_.email ) return redirect('manage:users') else: form = forms.EditUserForm(instance=user_) context['form'] = form context['user'] = user_ return render(request, 'manage/user.html', context)
def update_featured_versions(request): api = ProductVersions() products = set( x['product'] for x in api.get()['hits'] ) data = {} for product in request.POST: if product in products: data[product] = request.POST.getlist(product) featured_api = ReleasesFeatured() success = featured_api.put(**data) if success: messages.success( request, 'Featured versions successfully updated. ' 'Cache might take some time to update.' ) log(request.user, 'featured_versions.update', { 'data': data, 'success': success }) url = reverse('manage:featured_versions') return redirect(url)
def groups(request): context = {} if request.method == 'POST': if request.POST.get('delete'): group = get_object_or_404(Group, pk=request.POST['delete']) group.delete() log(request.user, 'group.delete', {'name': group.name}) messages.success( request, 'Group deleted.' ) return redirect('manage:groups') form = forms.GroupForm(request.POST) if form.is_valid(): group = form.save() log(request.user, 'group.add', { 'id': group.id, 'name': group.name, 'permissions': [x.name for x in group.permissions.all()] }) messages.success( request, 'Group created.' ) return redirect('manage:groups') else: form = forms.GroupForm() context['form'] = form context['groups'] = Group.objects.all().order_by('name') context['permissions'] = Permission.objects.all().order_by('name') return render(request, 'manage/groups.html', context)
def create(self, validated_data): user = validated_data.pop('user') addr = validated_data.pop('company_address') comp_assign = validated_data.pop('assign_optiz') comp = Company.objects.create(company_created_by=user, **validated_data) for optiz in comp_assign: optiz_user = Account.objects.get(id=optiz) comp.company_assigned_to.add(optiz_user) comp.save() comp_addr = Address.objects.create(addr_created_by=user, addr_company=comp, **addr) comp_addr.save() comp.company_address = comp_addr comp.save() log( user=user, company=comp, not_action='company registered', obj=comp, notification=True, extra={ 'company_id':comp.id, 'company_name':comp.name, } ) return comp
def create(self, validated_data): user = validated_data.pop('user') user_company = validated_data.pop('user_company') acct = Account.objects.create_user(**validated_data) acct.user_company = user_company acct.user_created_by = user acct.access_level = validated_data['access_level'] acct.position = validated_data['position'] acct.auth_amount = validated_data['auth_amount'] acct.save() log( user=user, company=user_company, not_action='user created', obj=acct, notification=True, extra={ 'account_id':acct.id, 'account_username':acct.username, 'account_first_name':acct.first_name, 'account_last_name':acct.last_name, } ) registration_email.delay(acct.email, '*****@*****.**') for uc in user_company.wease_company.all(): if uc.id != acct.id and uc.new_user_email: user_email.delay(uc, acct, subj='New WeASe member added', tmp='registration/user_added_email.html') for optiz in user_company.company_assigned_to.all(): if optiz.new_user_email: user_email.delay(optiz, acct, subj='New WeASe member added', tmp='registration/user_added_email.html') return acct
def create(self, validated_data): print "VAL-DATA COMP === %s" % validated_data user = validated_data.pop('user') addr = validated_data.pop('company_address') comp_assign = validated_data.pop('assign_optiz') print "assign_optiz === %s" % comp_assign comp = Company.objects.create(company_created_by=user, **validated_data) for optiz in comp_assign: optiz_user = Account.objects.get(id=optiz) comp.company_assigned_to.add(optiz_user) comp.save() comp_addr = Address.objects.create(addr_created_by=user, addr_company=comp, **addr) comp_addr.save() comp.company_address = comp_addr comp.save() log(user=user, company=comp, not_action='company registered', obj=comp, notification=True, extra={ 'company_id': comp.id, 'company_name': comp.name, }) return comp
def products(request): context = {} api = CurrentProducts() if request.method == 'POST': form = forms.ProductForm(request.POST, existing_products=api.get()['products']) if form.is_valid(): api = CurrentProducts() api.post(product=form.cleaned_data['product'], version=form.cleaned_data['initial_version']) log(request.user, 'product.add', form.cleaned_data) messages.success( request, 'Product %s (%s) added.' % (form.cleaned_data['product'], form.cleaned_data['initial_version'])) return redirect('manage:products') else: product = request.GET.get('product') if product is not None: messages.error( request, 'Product %s not found. Submit the form below to add it.' % (product)) form = forms.ProductForm(initial={ 'product': product, 'initial_version': '1.0' }) context['form'] = form context['page_title'] = "Products" return render(request, 'manage/products.html', context)
def releases(request): context = {} platforms_api = Platforms() platform_names = [x["name"] for x in platforms_api.get()] if request.method == "POST": form = forms.ReleaseForm(request.POST, platforms=platform_names) if form.is_valid(): api = Releases() api.post( product=form.cleaned_data["product"], version=form.cleaned_data["version"], update_channel=form.cleaned_data["update_channel"], build_id=form.cleaned_data["build_id"], platform=form.cleaned_data["platform"], beta_number=form.cleaned_data["beta_number"], release_channel=form.cleaned_data["release_channel"], throttle=form.cleaned_data["throttle"], ) log(request.user, "release.add", form.cleaned_data) messages.success( request, "New release for %s:%s added." % (form.cleaned_data["product"], form.cleaned_data["version"]) ) return redirect("manage:releases") else: form = forms.ReleaseForm( platforms=platform_names, initial={"throttle": 1, "update_channel": "Release", "release_channel": "release"} ) context["form"] = form context["page_title"] = "Releases" return render(request, "manage/releases.html", context)
def create(self, validated_data): order = validated_data.pop('order') goods = validated_data.pop('good') user = validated_data['user'] good = Good.objects.get(id=validated_data['good_id']) if 'item_details' in validated_data: item_details = validated_data.pop('item_details') else: item_details = '' order.order_draft = validated_data['order_draft'] order.save() req_item = ReqItem.objects.create(order=order, good=good, req_domain=goods[0], item_fam=goods[1], item_subfam=goods[2], item_details=item_details) req_item.req_item_created_by = user req_item.save() for k, v in validated_data['prod_details'].iteritems(): req_product = ReqProduct(req_item=req_item, prod_fam=goods[1], prod_subfam=goods[2], prod_title=k, prod_details=v) req_product.save() log( user=user, company=order.order_company, not_action='request item created', obj=order, notification=False, extra={ 'order_id':order.id, 'order_number':order.order_number, 'order_version':order.order_version, 'request_item_id':req_item.id, 'request_item_subfam':req_item.item_subfam, 'order_status':order.order_status, 'order_status_full':order.get_order_status_display(), } ) return req_item
def group(request, id): context = {} group_ = get_object_or_404(Group, id=id) if request.method == 'POST': before = copy.copy(group_) before.__permissions = [x.name for x in before.permissions.all()] # print "permissions before", before.permissions.all() form = forms.GroupForm(request.POST, instance=group_) if form.is_valid(): form.save() # print "permissions after", group_.permissions.all() group_.__permissions = [x.name for x in group_.permissions.all()] log(request.user, 'group.edit', { 'id': group_.id, 'change': notice_change(before, group_), }) messages.success( request, 'Group saved.' ) return redirect('manage:groups') else: form = forms.GroupForm(instance=group_) context['form'] = form context['group'] = group_ return render(request, 'manage/group.html', context)
def update_featured_versions(request): products_api = CurrentProducts() products = products_api.get()['products'] data = {} for product in request.POST: if product in products: data[product] = request.POST.getlist(product) featured_api = ReleasesFeatured() success = featured_api.put(**data) if success: messages.success( request, 'Featured versions successfully updated. ' 'Cache might take some time to update.' ) log(request.user, 'featured_versions.update', { 'data': data, 'success': success }) url = reverse('manage:featured_versions') return redirect(url)
def user(request, id): context = {} user_ = get_object_or_404(User, id=id) if request.method == 'POST': # make a copy because it's mutable in the form before = copy.copy(user_) # expand the many-to-many field before changing it in the form before.__groups = [unicode(x) for x in before.groups.all()] form = forms.EditUserForm(request.POST, instance=user_) if form.is_valid(): form.save() log(request.user, 'user.edit', { 'change': notice_change(before, user_), 'id': user_.id, }) messages.success( request, 'User %s update saved.' % user_.email ) return redirect('manage:users') else: form = forms.EditUserForm(instance=user_) context['form'] = form context['edit_user'] = user_ return render(request, 'manage/user.html', context)
def save(self, **kwargs): if not self.id: log(user=self.created_by, action='NEW TRANSACTION ADDED', obj=self, extra={ "milestone": str(self.milestone), "transaction_date": str(self.date), "transaction_amount": self.amount, "provider_organization_name": self.provider_org_name, "receiver_organization_name": self.receiver_org_name, "amendment_changes": self.changes, }) else: log(user=self.updated_by, action='UPDATED TRANSACTION', obj=self, extra={ "milestone": str(self.milestone), "transaction_date": str(self.date), "transaction_amount": self.amount, "provider_organization_name": self.provider_org_name, "receiver_organization_name": self.receiver_org_name, "changes": self.changes, }) super(Transaction, self).save(kwargs)
def save(self, *args, **kwargs): if not self.id: log(user=self.usuario, action='ADD_PACIENTE', extra={"cedula": self.cedula,"Usuario": self.usuario.username }) else: log(user = self.usuario, action='UPDATE_PACIENTE', extra={"cedula": self.cedula,"Usuario": self.usuario.username}) super(Paciente, self).save(args, kwargs)
def reprocessing(request): if request.method == 'POST': form = forms.ReprocessingForm(request.POST) if form.is_valid(): crash_id = form.cleaned_data['crash_id'] url = reverse('manage:reprocessing') worked = Reprocessing().post(crash_ids=[crash_id]) if worked: url += '?crash_id={}'.format(crash_id) messages.success( request, '{} sent in for reprocessing.'.format(crash_id) ) else: messages.error( request, 'Currently unable to send in the crash ID ' 'for reprocessing.' ) log(request.user, 'reprocessing', { 'crash_id': crash_id, 'worked': worked, }) return redirect(url) else: form = forms.ReprocessingForm() context = { 'form': form, 'crash_id': request.GET.get('crash_id'), } return render(request, 'manage/reprocessing.html', context)
def reprocessing(request): if request.method == 'POST': form = forms.ReprocessingForm(request.POST) if form.is_valid(): crash_id = form.cleaned_data['crash_id'] url = reverse('manage:reprocessing') worked = Reprocessing().post(crash_ids=[crash_id]) if worked: url += '?crash_id={}'.format(crash_id) messages.success( request, '{} sent in for reprocessing.'.format(crash_id)) else: messages.error( request, 'Currently unable to send in the crash ID ' 'for reprocessing.') log(request.user, 'reprocessing', { 'crash_id': crash_id, 'worked': worked, }) return redirect(url) else: form = forms.ReprocessingForm() context = { 'form': form, 'crash_id': request.GET.get('crash_id'), } return render(request, 'manage/reprocessing.html', context)
def save(self, logging=True, *args, **kwargs): # Automatic change Task.exec_status when Execution has changed if self.exec_status in [Execution.InProgress, Execution.OnChecking] and self.task.exec_status == Task.ToDo: self.task.exec_status = Task.InProgress self.task.save(logging=False) # Automatic change Executions.exec_status when Task has Done if self.task.exec_status in [Task.Done, Task.Sent] and self.exec_status != Execution.Done: self.exec_status = Execution.Done # Automatic set finish_date when Execution has done if self.exec_status in [Execution.OnChecking, Execution.Done] and self.finish_date is None: self.finish_date = date.today() elif self.exec_status in [Execution.ToDo, Execution.InProgress] and self.finish_date is not None: self.finish_date = None # Logging if logging: title = self.task.object_code + ' ' + \ self.task.project_type.price_code + ' ' + self.part_name if not self.pk: log(user=get_current_user(), action='Додана частина проекту', extra={"title": title}) else: log(user=get_current_user(), action='Оновлена частина проекту', extra={"title": title}) super(Execution, self).save(*args, **kwargs)
def groups(request): context = {} if request.method == 'POST': if request.POST.get('delete'): group = get_object_or_404(Group, pk=request.POST['delete']) group.delete() log(request.user, 'group.delete', {'name': group.name}) messages.success(request, 'Group deleted.') return redirect('manage:groups') form = forms.GroupForm(request.POST) if form.is_valid(): group = form.save() log( request.user, 'group.add', { 'id': group.id, 'name': group.name, 'permissions': [x.name for x in group.permissions.all()] }) messages.success(request, 'Group created.') return redirect('manage:groups') else: form = forms.GroupForm() context['form'] = form context['groups'] = Group.objects.all().order_by('name') context['permissions'] = Permission.objects.all().order_by('name') return render(request, 'manage/groups.html', context)
def products(request): context = {} api = CurrentProducts() if request.method == 'POST': form = forms.ProductForm( request.POST, existing_products=api.get()['products'] ) if form.is_valid(): api = CurrentProducts() api.post( product=form.cleaned_data['product'], version=form.cleaned_data['initial_version'] ) log(request.user, 'product.add', form.cleaned_data) messages.success( request, 'Product %s (%s) added.' % ( form.cleaned_data['product'], form.cleaned_data['initial_version'] ) ) return redirect('manage:products') else: form = forms.ProductForm(initial={ 'initial_version': '1.0' }) context['form'] = form context['page_title'] = "Products" return render(request, 'manage/products.html', context)
def releases(request): context = {} platforms_api = Platforms() platform_names = [x['name'] for x in platforms_api.get()] if request.method == 'POST': form = forms.ReleaseForm(request.POST, platforms=platform_names) if form.is_valid(): api = Releases() api.post( product=form.cleaned_data['product'], version=form.cleaned_data['version'], update_channel=form.cleaned_data['update_channel'], build_id=form.cleaned_data['build_id'], platform=form.cleaned_data['platform'], beta_number=form.cleaned_data['beta_number'], release_channel=form.cleaned_data['release_channel'], throttle=form.cleaned_data['throttle'], ) log(request.user, 'release.add', form.cleaned_data) messages.success( request, 'New release for %s:%s added.' % (form.cleaned_data['product'], form.cleaned_data['version'])) return redirect('manage:releases') else: form = forms.ReleaseForm(platforms=platform_names, initial={ 'throttle': 1, 'update_channel': 'Release', 'release_channel': 'release', }) context['form'] = form context['page_title'] = "Releases" return render(request, 'manage/releases.html', context)
def update(self, instance, validated_data): val_data = validated_data.pop("data") user = validated_data["user"] order = validated_data.pop("order") order.order_draft = val_data["order_draft"] order.order_modified_by = user order.save() instance.req_item_modified_by = user instance.item_details = val_data.get("item_details", instance.item_details) for item in val_data["req_product"]: req_product = ReqProduct( id=item["id"], prod_title=item["prod_title"], prod_details=item["prod_details"], req_item=instance ) req_product.save() instance.save() log( user=user, company=order.order_company, not_action="request item updated", obj=order, notification=False, extra={ "order_id": order.id, "order_number": order.order_number, "order_version": order.order_version, "request_item_id": instance.id, "request_item_subfam": instance.item_subfam, "order_status": order.order_status, "order_status_full": order.get_order_status_display(), }, ) return instance
def handle_user_login_attempt(sender, **kwargs): log(user=None, action="LOGIN_ATTEMPTED", extra={ "username": kwargs.get("username"), "result": kwargs.get("result") })
def availability_changed(user, event, bartender, old_availability, new_availability): log(user, 'MODIFIED_AVAILABILITY', { "pk": event.pk, "bartender": bartender.get_full_name(), "old_availability": old_availability.__str__(), "new_availability": new_availability.__str__(), })
def login_view(request): mensaje = "" next = request.POST.get('next', request.GET.get('next', '')) if request.user.is_authenticated(): return HttpResponseRedirect("/corazon/home/") else: if request.method == "POST": form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] usuario = authenticate(username=username, password=password) if usuario is not None and usuario.is_active: log(user=usuario, action='LOGIN', extra={"apellido": usuario.last_name, "nombre": usuario.first_name}) login(request,usuario) if next: return HttpResponseRedirect(next)# a la raiz return HttpResponseRedirect('/corazon/home') else: mensaje = "usuario y/o password incorrecto" else: print "La url es %s" %next form = LoginForm() ctx = {'form':form,'mensaje':mensaje, 'next': next} return render_to_response('login.html',ctx,context_instance=RequestContext(request))
def save(self, *args, **kwargs): if not self.id: log(user=self.usuario, action='ADD_DOCTOR', extra={"cedula": self.cedula}) else: log(user = self.usuario, action='UPDATE_DOCTOR', extra={"cedula": self.cedula}) super(Doctor, self).save(args, kwargs)
def groups(request): context = {} if request.method == "POST": if request.POST.get("delete"): group = get_object_or_404(Group, pk=request.POST["delete"]) group.delete() log(request.user, "group.delete", {"name": group.name}) messages.success(request, "Group deleted.") return redirect("manage:groups") form = forms.GroupForm(request.POST) if form.is_valid(): group = form.save() log( request.user, "group.add", {"id": group.id, "name": group.name, "permissions": [x.name for x in group.permissions.all()]}, ) messages.success(request, "Group created.") return redirect("manage:groups") else: form = forms.GroupForm() context["form"] = form context["groups"] = Group.objects.all().order_by("name") context["permissions"] = Permission.objects.all().order_by("name") return render(request, "manage/groups.html", context)
def save(self, *args, **kwargs): self.time_zone = timezone.get_current_timezone_name() if not self.pk: log(user=self.user, action='ADD_USERP', extra={'id': self.id, 'user_name': self.user.username}) else: log(user=self.user, action='UPD_USERP', extra={'id': 0, 'user_name': self.user.username}) return super(UserProfile, self).save(*args, **kwargs)
def update(self, instance, validated_data): val_data = validated_data.pop('data') user = validated_data['user'] order = validated_data.pop('order') order.order_draft = val_data['order_draft'] order.order_modified_by = user order.save() instance.req_item_modified_by = user instance.item_details = val_data.get('item_details', instance.item_details) for item in val_data['req_product']: req_product = ReqProduct(id=item['id'], prod_title=item['prod_title'], prod_details=item['prod_details'], req_item=instance) req_product.save() instance.save() log( user=user, company=order.order_company, not_action='request item updated', obj=order, notification=False, extra={ 'order_id':order.id, 'order_number':order.order_number, 'order_version':order.order_version, 'request_item_id':instance.id, 'request_item_subfam':instance.item_subfam, 'order_status':order.order_status, 'order_status_full':order.get_order_status_display(), } ) return instance
def handle_user_sign_up_attempt(sender, **kwargs): log(user=None, action="SIGNUP_ATTEMPTED", extra={ "username": kwargs.get("username"), "email": kwargs.get("email"), "result": kwargs.get("result") })
def handle_user_login_attempt(sender, **kwargs): log( user=None, action="LOGIN_ATTEMPTED", extra={ "username": kwargs.get("username"), "result": kwargs.get("result") } )
def send_feedback_notfication(sender, instance, created, **kwargs): if created: log(user=instance.user, action="FEEDBACK", extra={}) admin_user = User.objects.get(id=settings.ADMIN_USER_ID) notify.send(instance.user, recipient=admin_user, verb=_('feedback'), action_object=instance, description=instance.text)
def status_message(request): if request.method == 'POST': form = forms.StatusMessageForm(request.POST) if form.is_valid(): data = form.cleaned_data status = StatusMessage.objects.create( message=data['message'], severity=data['severity'], ) log(request.user, 'status_message.create', { 'user': request.user.email, 'severity': status.severity, }) messages.success( request, 'Status Message created. ' ) return redirect('manage:status_message') else: form = forms.StatusMessageForm() try: page = int(request.GET.get('page', 1)) assert page >= 1 except (ValueError, AssertionError): return http.HttpResponseBadRequest('invalid page') statuses = ( StatusMessage.objects.all().order_by('-created_at') ) count = statuses.count() batch_size = settings.STATUS_MESSAGE_ADMIN_BATCH_SIZE m = (page - 1) * batch_size n = page * batch_size current_query = request.GET.copy() if 'page' in current_query: del current_query['page'] current_url = '{}?{}'.format( reverse('manage:status_message'), current_query.urlencode() ) context = { 'form': form, 'statuses': statuses[m:n], 'pagination_data': { 'page': page, 'current_url': current_url, 'total_pages': int(math.ceil(float(count) / batch_size)), 'total_count': count, } } return render(request, 'manage/status_message.html', context)
def graphics_devices(request): context = {} form = forms.GraphicsDeviceForm() upload_form = forms.GraphicsDeviceUploadForm() if request.method == 'POST' and 'file' in request.FILES: upload_form = forms.GraphicsDeviceUploadForm( request.POST, request.FILES ) if upload_form.is_valid(): if upload_form.cleaned_data['database'] == 'pcidatabase.com': function = utils.pcidatabase__parse_graphics_devices_iterable else: function = utils.pci_ids__parse_graphics_devices_iterable payload = list(function(upload_form.cleaned_data['file'])) api = GraphicsDevices() result = api.post(data=payload) log(request.user, 'graphicsdevices.post', { 'success': result, 'database': upload_form.cleaned_data['database'], 'no_lines': len(payload), }) messages.success( request, 'Graphics device CSV upload successfully saved.' ) return redirect('manage:graphics_devices') elif request.method == 'POST': form = forms.GraphicsDeviceForm(request.POST) if form.is_valid(): payload = [{ 'vendor_hex': form.cleaned_data['vendor_hex'], 'adapter_hex': form.cleaned_data['adapter_hex'], 'vendor_name': form.cleaned_data['vendor_name'], 'adapter_name': form.cleaned_data['adapter_name'], }] api = GraphicsDevices() result = api.post(data=payload) log(request.user, 'graphicsdevices.add', { 'payload': payload, 'success': result }) if result: messages.success( request, 'Graphics device saved.' ) return redirect('manage:graphics_devices') context['page_title'] = "Graphics Devices" context['form'] = form context['upload_form'] = upload_form return render(request, 'manage/graphics_devices.html', context)
def update(self, instance, validated_data): user = validated_data.pop('user') req = self.context.get('request') instance.is_active = validated_data.get('is_active', instance.is_active) instance.username = validated_data.get('username', instance.username) instance.email = validated_data.get('email', instance.email) instance.first_name = validated_data.get('first_name', instance.first_name) instance.last_name = validated_data.get('last_name', instance.last_name) instance.tagline = validated_data.get('tagline', instance.tagline) instance.optiz = validated_data.get('optiz', instance.optiz) instance.lang = validated_data.get('lang', instance.lang) instance.position = validated_data.get('position', instance.position) instance.access_level = validated_data.get('access_level', instance.access_level) instance.auth_amount = validated_data.get('auth_amount', instance.auth_amount) instance.street_addr1 = validated_data.get('street_addr1', instance.street_addr1) instance.street_addr2 = validated_data.get('street_addr2', instance.street_addr2) instance.city = validated_data.get('city', instance.city) instance.post_code = validated_data.get('post_code', instance.post_code) instance.country = validated_data.get('country', instance.country) instance.phone_main = validated_data.get('phone_main', instance.phone_main) instance.phone_mobile = validated_data.get('phone_mobile', instance.phone_mobile) instance.user_pic = validated_data.get('user_pic', instance.user_pic) instance.request_email = validated_data.get('request_email', instance.request_email) instance.refused_email = validated_data.get('refused_email', instance.refused_email) instance.offer_email = validated_data.get('offer_email', instance.offer_email) instance.order_email = validated_data.get('order_email', instance.order_email) instance.approval_email = validated_data.get('approval_email', instance.approval_email) instance.validated_email = validated_data.get('validated_email', instance.validated_email) instance.canceled_email = validated_data.get('canceled_email', instance.canceled_email) instance.new_user_email = validated_data.get('new_user_email', instance.new_user_email) instance.info_change_email = validated_data.get('info_change_email', instance.info_change_email) instance.user_updated_by = user instance.save() password = validated_data.get('password', None) confirm_password = validated_data.get('confirm_password', None) if password and confirm_password and password == confirm_password: instance.set_password(password) instance.save() update_session_auth_hash(self.context.get('request'), instance) log( user=user, company=instance.user_company, not_action='user updated', obj=instance, notification=False, extra={ 'account_id':instance.id, 'account_first_name':instance.first_name, 'account_last_name':instance.last_name, } ) if instance.info_change_email: user_email.delay(instance, obj=None, subj='WeASe profile updated', tmp='registration/user_update.html') return instance
def graphics_devices(request): context = {} form = forms.GraphicsDeviceForm() upload_form = forms.GraphicsDeviceUploadForm() if request.method == 'POST' and 'file' in request.FILES: upload_form = forms.GraphicsDeviceUploadForm( request.POST, request.FILES ) if upload_form.is_valid(): if upload_form.cleaned_data['database'] == 'pcidatabase.com': function = utils.pcidatabase__parse_graphics_devices_iterable else: function = utils.pci_ids__parse_graphics_devices_iterable payload = list(function(upload_form.cleaned_data['file'])) api = GraphicsDevices() result = api.post(json.dumps(payload)) log(request.user, 'graphicsdevices.post', { 'success': result, 'database': upload_form.cleaned_data['database'], 'no_lines': len(payload), }) messages.success( request, 'Graphics device CSV upload successfully saved.' ) return redirect('manage:graphics_devices') elif request.method == 'POST': form = forms.GraphicsDeviceForm(request.POST) if form.is_valid(): payload = [{ 'vendor_hex': form.cleaned_data['vendor_hex'], 'adapter_hex': form.cleaned_data['adapter_hex'], 'vendor_name': form.cleaned_data['vendor_name'], 'adapter_name': form.cleaned_data['adapter_name'], }] api = GraphicsDevices() result = api.post(json.dumps(payload)) log(request.user, 'graphicsdevices.add', { 'payload': payload, 'success': result }) if result: messages.success( request, 'Graphics device saved.' ) return redirect('manage:graphics_devices') context['page_title'] = "Graphics Devices" context['form'] = form context['upload_form'] = upload_form return render(request, 'manage/graphics_devices.html', context)
def save(self, logging=True, *args, **kwargs): title = self.task.object_code + ' ' + self.task.project_type.price_code if logging: if not self.pk: log(user=get_current_user(), action='Доданий підрядник по проекту', extra={"title": title}) else: log(user=get_current_user(), action='Оновлений підрядник по проекту', extra={ "title": title}) super(Order, self).save(*args, **kwargs)
def save(self, *args, **kwargs): if not self.pk: self.creator = get_current_user() if not self.pk: log(user=get_current_user(), action='Додана новина', extra={"title": self.title}) else: log(user=get_current_user(), action='Оновлена новина', extra={"title": self.title}) super(News, self).save(*args, **kwargs)
def save(self, *args, **kwargs): if not self.id: # Change self.author to the name of the users currently logged in log(user=self.author, action='Added a Task', extra={"title": self.name}) else: log(user=self.author, action='Changed a Task', extra={"title": self.name}) super(Task, self).save(*args, **kwargs)
def handle_user_sign_up_attempt(sender, **kwargs): log( user=None, action="SIGNUP_ATTEMPTED", extra={ "username": kwargs.get("username"), "email": kwargs.get("email"), "result": kwargs.get("result") } )
def send_feedback_notfication(sender, instance, created, **kwargs): if created: log( user=instance.user, action="FEEDBACK", extra={} ) admin_user = User.objects.get(id=settings.ADMIN_USER_ID) notify.send(instance.user, recipient=admin_user, verb=_('feedback'), action_object=instance, description=instance.text)
def skiplist_delete(request): form = forms.SkipListForm(request.POST) if form.is_valid(): category = form.cleaned_data["category"] rule = form.cleaned_data["rule"] else: return http.HttpResponseBadRequest(str(form.errors)) api = SkipList() success = api.delete(category=category, rule=rule) log(request.user, "skiplist.delete", {"data": {"category": category, "rule": rule}, "success": success}) return success
def save(self, logging=True, *args, **kwargs): self.next_date = self.next_repeat() if not self.pk: self.creator = get_current_user() if logging: if not self.pk: log(user=get_current_user(), action='Додана подія', extra={"title": self.title}) else: log(user=get_current_user(), action='Оновлена подія', extra={"title": self.title}) super(Event, self).save(*args, **kwargs)
def handle_user_signed_up(sender, **kwargs): user = kwargs.get("user") log( user=user, action="USER_SIGNED_UP", extra={} ) admins = User.objects.filter(is_superuser=True) if len(admins) > 0: admin = admins[0] profile = user.get_profile() notify.send(user, recipient=admin, verb=_(' signed up '), action_object=profile, description=_("Please review this user %s") % profile.realm)
def api_tokens_delete(request): if not request.POST.get('id'): return http.HttpResponseBadRequest('No id') token = get_object_or_404(Token, id=request.POST['id']) log( request.user, 'api_token.delete', { 'user': token.user.email, 'permissions': ', '.join(x.name for x in token.permissions.all()), 'notes': token.notes, }) token.delete() return True
def save(self, *args, **kwargs): if not hasattr(self, 'site'): self.site = Site.objects.get_current() user = get_current_user() user_model = get_user_model() if not isinstance(user, user_model): user = user_model.objects.first() # if no user available then assume 1st user is superuser self.updated_by = user if not self.pk: self.created_by = user log(user=user, action='ADD_RULE', extra={'id': self.id, 'start_sort': self.start_sort}) else: log(user=user, action='UPDATE_RULE', extra={'id': 0, 'start_sort': self.start_sort}) return super(Rule, self).save(*args, **kwargs)
def status_message(request): if request.method == 'POST': form = forms.StatusMessageForm(request.POST) if form.is_valid(): data = form.cleaned_data status = StatusMessage.objects.create( message=data['message'], severity=data['severity'], ) log(request.user, 'status_message.create', { 'user': request.user.email, 'severity': status.severity, }) messages.success(request, 'Status Message created. ') return redirect('manage:status_message') else: form = forms.StatusMessageForm() try: page = int(request.GET.get('page', 1)) assert page >= 1 except (ValueError, AssertionError): return http.HttpResponseBadRequest('invalid page') statuses = (StatusMessage.objects.all().order_by('-created_at')) count = statuses.count() batch_size = settings.STATUS_MESSAGE_ADMIN_BATCH_SIZE m = (page - 1) * batch_size n = page * batch_size current_query = request.GET.copy() if 'page' in current_query: del current_query['page'] current_url = '{}?{}'.format(reverse('manage:status_message'), current_query.urlencode()) context = { 'form': form, 'statuses': statuses[m:n], 'pagination_data': { 'page': page, 'current_url': current_url, 'total_pages': int(math.ceil(float(count) / batch_size)), 'total_count': count, } } return render(request, 'manage/status_message.html', context)
def status_message_disable(request, id): status = get_object_or_404(StatusMessage, id=id) log(request.user, 'status_message.disable', { 'user': request.user.email, 'id': status.id, }) status.enabled = False status.save() messages.success(request, 'Status message successfully disabled.') return redirect(reverse('manage:status_message'))
def delete(self, *args, **kwargs): # Automatic changing of Task.exec_status when sendings was deleted sendings = self.task.sending_set.aggregate(Sum('copies_count'))['copies_count__sum'] or 0 sendings -= self.copies_count if self.task.exec_status == Task.Sent and sendings < self.task.project_type.copies_count: self.task.exec_status = Task.Done self.task.sending_date = None self.task.save(logging=False) # Logging title = f"{self.task.object_code} {self.task.project_type.price_code}" log(user=get_current_user(), action='Видалена відправка проекту', extra={"title": title}) super(Sending, self).delete(*args, **kwargs)
def authenticate(self, username=None, password=None, **kwargs): try: user = User.objects.get(email=username) except User.MultipleObjectsReturned: log(user=User.objects.filter( email=username).order_by('id').first(), action='USER_MULTIPLE_OBJECTS_ERROR') return User.objects.filter(email=username).order_by('id').first() except User.DoesNotExist: return None if getattr(user, 'is_active') and user.check_password(password): return user return None
def api_tokens(request): all_possible_permissions = Permission.objects.filter(content_type__model="").order_by("name") possible_permissions = [] for permission in all_possible_permissions: possible_permissions.append(permission) expires_choices = ( (1, "1 day"), (7, "1 week"), (30, "1 month"), (30 * 3, "3 months"), (365, "1 year"), (365 * 10, "10 years"), ) if request.method == "POST": form = forms.APITokenForm( request.POST, possible_permissions=possible_permissions, expires_choices=expires_choices ) if form.is_valid(): data = form.cleaned_data token = Token.objects.create(user=data["user"], notes=data["notes"], expires=data["expires"]) for permission in data["permissions"]: token.permissions.add(permission) log( request.user, "api_token.create", { "user": token.user.email, "expires": token.expires, # Do this reverse trick to avoid microseconds rounding it # down to 6 days. "expires_days": (timezone.now() - token.expires).days * -1, "notes": token.notes, "permissions": ", ".join(x.name for x in token.permissions.all()), }, ) messages.success(request, "API Token for %s created. " % token.user.email) return redirect("manage:api_tokens") else: form = forms.APITokenForm( possible_permissions=possible_permissions, expires_choices=expires_choices, initial={"expires": settings.TOKENS_DEFAULT_EXPIRATION_DAYS}, ) context = {"form": form, "filter_form": forms.FilterAPITokensForm(request.GET)} return render(request, "manage/api_tokens.html", context)
def supersearch_field_update(request): field_data = _get_supersearch_field_data(request.POST) if isinstance(field_data, basestring): return http.HttpResponseBadRequest(field_data) api = SuperSearchField() api.put(field_data) log(request.user, 'supersearch_field.put', field_data) # Refresh the cache for the fields service. SuperSearchFields().get(refresh_cache=True) return redirect(reverse('manage:supersearch_fields'))
def api_tokens_delete(request): if not request.POST.get('id'): return http.HttpResponseBadRequest('No id') token = get_object_or_404(Token, id=request.POST['id']) log(request.user, 'api_token.delete', { 'user': token.user.email, 'permissions': ', '.join( x.name for x in token.permissions.all() ), 'notes': token.notes, }) token.delete() return True
def supersearch_field_delete(request): field_name = request.GET.get('name') if not field_name: return http.HttpResponseBadRequest('A "name" is needed') api = SuperSearchField() api.delete(name=field_name) log(request.user, 'supersearch_field.delete', {'name': field_name}) # Refresh the cache for the fields service. SuperSearchFields().get(refresh_cache=True) url = reverse('manage:supersearch_fields') return redirect(url)
def create(self, validated_data): user = validated_data['user'] if 'blank_offer' in validated_data: company = Company.objects.get(id=validated_data['offer_company']) address = Address.objects.get(id=validated_data['delivery_address']) order = Order.objects.create(order_company=company, delivery_address=address, order_created_by=user, order_status_change_date = timezone.now()) yr = str(date.today().year)[2:] order.order_number = ''.join(["0",yr,str(order.id)]) order.order_version = 01 if 'reference_number' in validated_data: order.reference_number = validated_data['reference_number'] else: order = Order.objects.get(id=validated_data['order']) order.order_status_change_date = timezone.now() if order.offer_version >= 01: order.order_version = order.order_version+1 order.offer_version = order.offer_version+1 order.order_offer = True order.order_total = validated_data['offer_total'] order.modified_by = user order.order_status_change_by = user order.order_status = 'OFR' order.optiz_status = 'OSB' order.optiz_status_change_by = user order.optiz_status_change_date = timezone.now() order.save() offer = Offer.objects.create(order=order, offer_version=order.offer_version, offer_created_by=user, offer_total=validated_data['offer_total'], offer_terms=validated_data['offer_terms'], offer_domain=validated_data['offer_domain']) offer.save() for item in validated_data['offer_item']: offer_item = OfferItem(offer=offer, **item) offer_item.save() log( user=user, company=order.order_company, not_action='offer created', obj=order, notification=True, extra={ 'order_id':order.id, 'order_number':order.order_number, 'order_version':order.offer_version, 'offer_total':offer.offer_total, 'order_status':order.order_status, 'order_status_full':order.get_order_status_display(), } ) return offer
def status_message_disable(request, id): status = get_object_or_404(StatusMessage, id=id) log(request.user, 'status_message.disable', { 'user': request.user.email, 'id': status.id, }) status.enabled = False status.save() messages.success( request, 'Status message successfully disabled.' ) return redirect(reverse('manage:status_message'))