def generateSalesReport(userid, fromDate, toDate): periodOfSales = Sale.objects.filter(datetime__range=[fromDate, toDate]) headers = ['ID', 'Date', 'Customer Name', 'Quantity', 'Price'] wb = Workbook() ws1 = wb.active # Sheet 1 sales report overview ws1.title = "Sales Report Overview" ws1.append(headers) for sale in periodOfSales: saleItems = SaleItem.objects.filter(sale_id=sale.id) currentPrice = 0 currentQuantity = 0 for items in saleItems: currentPrice = currentPrice + (items.sale_price * items.quantity) currentQuantity = currentQuantity + items.quantity customer = Customer.objects.get(user_id=sale.customer_id) customerName = customer.full_name currentRow = [ sale.id, sale.datetime, customerName, currentQuantity, convertToPoundsStr(currentPrice) ] ws1.append(currentRow) # Sheet 2 sales report details headers = [ 'Sale ID', 'Item Code', 'Item Name', 'Quantity', 'Price', 'Returned', 'Date', 'Department', 'Customer Name' ] ws2 = wb.create_sheet(title="Weekly Sales Item Report") ws2.title = "Sales Report Details" ws2.append(headers) for sale in periodOfSales: saleItems = SaleItem.objects.filter(sale_id=sale.id) currentPrice = 0 currentQuantity = 0 customer = Customer.objects.get(user_id=sale.customer_id) for items in saleItems: itemDetails = Item.objects.get(id=items.item_id) currentRow = [ sale.id, itemDetails.code, itemDetails.name, items.quantity, convertToPoundsStr(item.items.sale_price), items.returned_quantity, sale.datetime, customer.dept_id, customer.full_name ] ws2.append(currentRow) filename = "Sales_Report" + str( timezone.now().strftime("%Y%m%d-%H%M%S")) + ".xlsx" wb.save(REPORT_DIR + filename) reportMessage = "Sales Report Ready" report = Report(user_id=userid, filename=filename, created_date=timezone.now(), report_type="SA") report.save() notify = Notification(user_id=userid, text=reportMessage, notification_type="RE", link="/staff/reports/?id=" + str(report.id), seen=False) notify.save()
def AddVote(request): """!@brief Function to add a vote to some answer @details takes a vote object as part of the request body, extracts the vote object and creates a new entry in the vote table. Also, updates the total votes for the answer and the total votes for the user who gave the answer. Also creates a new notification for the user who gave the answer. @post New entries have been created in the vote and the notification table. Also updated the answer and user tables. @return returns the modified question object """ serializer = VoteSerializer(data=request.data) if serializer.is_valid(): serializer.save() vote = serializer.validated_data answer = vote['answer'] receiver = answer.user sender = vote['user'] question = answer.question u_d = vote['upvote_downvote'] if u_d: answer.votes = answer.votes + 1 receiver.totalvotes = receiver.totalvotes + 1 code = 1 else: answer.votes = answer.votes - 1 receiver.totalvotes = receiver.totalvotes - 1 code = 2 notification = Notification(receiver=receiver, sender=sender, sendername=sender.name, question=question, code=code) notification.save() answer.save() receiver.save() questionid = question.id return QuestionResponse(sender.id, questionid) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def add_notification(initiator_user, destined_user, text, notification_type=NotificationTypeChoice.COMMON.value, trip=None): """ Add Notification for user :param request: :param initiator_user: :param destined_user: :param text: :param notification_type: :param trip: Optional Parameter :return: True if notification created :return: False if error occurs """ try: notification = Notification( initiator_user=initiator_user, destined_user=destined_user, text=text, notification_type=notification_type, ) if notification_type == NotificationTypeChoice.TRIP.value: notification.trip = trip notification.save() except Exception: return False # Failed to create notification return True # Notification successfully Created
def PostAnswer(request): """!@brief Function for posting an answer which is part of the request body @details this function extracts the answer details from the request body, then creates a new entry in the answer table with the corresponding details. It also creates a notification for a user whose question has been provided an answer and increase the field numAnswers for that question by 1 @post New entries have been created in the answer table as well as the notification table along with an update in th question table to accomodate for the new changes @return returns the updated question object """ serializer = AnswerSerializer(data=request.data) if serializer.is_valid(): ans = serializer.validated_data sender = ans['user'] question = ans['question'] receiver = question.user answer = Answer(user=sender, username=sender.name, userdepartment=sender.department, userbio=sender.bio, userdegree=sender.degree, userspecialization=sender.specialization, content=ans['content'], question=question) answer.save() notification = Notification(receiver=receiver, sender=sender, sendername=sender.name, question=question, code=3) notification.save() #print(question.numAnswers) question.numAnswers = question.numAnswers + 1 question.save() return QuestionResponse(sender.id, question.id) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def send_notification(silo_name, level, topic): title = silo_name body = f"The level is below {level}%" notification = Notification(title=title, body=body) notification.save() fcm_send_topic_message(topic_name=topic, sound='default', message_body=body, message_title=title, data_message={"body": body, "title": title})
def generateStockReport(userid, includeChecks, fromDate="", toDate=""): items = Item.objects.all() headers = [ 'Item ID', 'Item Code', 'Item Name', 'Item Price', 'Quantity', 'Warning Quantity', 'Is Chemical', 'Pack Size', 'For Sale' ] wb = Workbook() ws1 = wb.active ws1.title = "Stock Report" ws1.append(headers) for item in items: currentRow = [ item.id, item.code, item.name, convertToPoundsStr(item.price), item.quantity, item.warning_quantity, item.is_chemical, item.pack_size, item.for_sale ] ws1.append(currentRow) # Optional Stock Checks if includeChecks: # Sheet 2 stocks checks headers = [ 'Date', 'Staff Member', 'Item Code', 'Item Name', 'Observed Quantity', 'Expected Quantity', 'Warning Quantity' ] ws2 = wb.create_sheet(title="Stock Check Report") ws2.title = "Stock Check Report" ws2.append(headers) for check in StockCheck.objects.filter( datetime__range=[fromDate, toDate]): checkStaff = Staff.objects.get(user_id=check.staff_id) checkedItem = StockCheckItem.objects.get(id=check.id) itemDetails = Item.objects.get(id=checkedItem.item_id) currentRow = [ check.datetime, checkStaff.full_name, itemDetails.code, itemDetails.name, checkedItem.observed_quantity, checkedItem.expected_quantity, itemDetails.warning_quantity ] ws2.append(currentRow) filename = "Stock_Report" + str( timezone.now().strftime("%Y%m%d-%H%M%S")) + ".xlsx" wb.save(REPORT_DIR + filename) reportMessage = "Stock Report Ready" report = Report(user_id=userid, filename=filename, created_date=timezone.now(), report_type="ST") report.save() notify = Notification(user_id=userid, text=reportMessage, notification_type="RE", link="/staff/reports/?id=" + str(report.id), seen=False) notify.save()
def generateSalesReport(userId, fromDate, toDate): thisWeeksSales = Sale.objects.filter(datetime__range=[fromDate, toDate]) headers = ['ID', 'Date', 'Customer Name', 'Quantity', 'Price'] wb = Workbook() ws1 = wb.active ws1.title = "Weekly Sales Report" ws1.append(headers) for sale in thisWeeksSales: saleItems = SaleItem.objects.filter(sale_id=sale.id) currentPrice = 0 currentQuantity = 0 for items in saleItems: currentPrice = currentPrice + (items.sale_price * items.quantity) currentQuantity = currentQuantity + items.quantity customer = Customer.objects.get(user_id=sale.customer_id) customerName = customer.full_name currentRow = [ sale.id, sale.datetime, customerName, currentQuantity, currentPrice ] ws1.append(currentRow) wb.save("week_sales_" + str(uuid.uuid4()) + ".xlsx") return 0 #TODO: Genereate detailed report on sheet 2 #SaleItem sheet ws2 = wb.create_sheet(title="Weekly Sales Item Report") wb.save("sample.xlsx") reportMessage = "Weekly Sales Report" #TODO: generate links for reports via routes notify = Notification(user_id=userId, text=reportMessage, notification_type="RE", link="NotImplemented")
def create_notification(user, verb, target=None): now = timezone.now() last_minute = now - datetime.timedelta(seconds=60) similar_notifications = Notification.objects.filter( user_id=user.id, verb=verb, created__gte=last_minute) if target: target_ct = ContentType.objects.get_for_model(target) similar_notifications = similar_notifications.filter( target_ct=target_ct, target_id=target.id) if not similar_notifications: notification = Notification(user=user, verb=verb, target=target) notification.save() return True return False
def post(self): try: data = request.get_json() recognized_objects = data.get("recognized_objects") camera_id = data.get("camera_id") video_filename = data.get("filename") log = Log() log.camera_id = camera_id log.recognized_objects = recognized_objects log.video_filename = video_filename db.session.add(log) db.session.flush() log_id = log.id notification = Notification(content=recognized_objects, log_id=log_id) db.session.add(notification) message = json.dumps({ "type": "camera_log", "link": f"{CLIENT_APP_BASE_URL}/logs/camera_logs/{log_id}", "message": recognized_objects }) notify_about_warning(message) db.session.commit() except Exception as e: print(e) return "Internal Server Error", 500
def form_valid(self, form): client = Client.objects.get(id=self.kwargs['pk']) payload = { 'id': 0, 'contact_type': 'mitc', 'contact_name': 'MitC', 'data': [ { 'type': 'NAME', 'value': form.cleaned_data['display_name'] }, { 'type': 'PHONE', 'value': form.cleaned_data['phone_number'] }, ] } print("payload:" + repr(payload)) Notification(client=client, data={ 'action': 'contact.new', 'payload': json.dumps(payload) }).save() messages.success(self.request, "Create request sent") return super(ContactCreate, self).form_valid(form)
def generateReturnsReport(userid, fromDate, toDate): periodOfReturns = Return.objects.filter(datetime__range=[fromDate, toDate]) headers = [ 'Return ID', 'Sale ID', 'Item ID', 'Item Name', 'Customer Name', 'Staff Name', 'Quantity', 'Reason', 'Date' ] wb = Workbook() ws1 = wb.active ws1.title = "Return Report" ws1.append(headers) for ret in periodOfReturns: saleItem = SaleItem.objects.get(id=ret.sale_item_id) item = Item.objects.get(id=saleItem.item_id) sale = Sale.objects.get(id=saleItem.sale_id) staff = Staff.objects.get(user_id=ret.staff_id) customer = Customer.objects.get(user_id=sale.customer_id) currentRow = [ ret.id, sale.id, item.id, item.name, customer.full_name, staff.full_name, ret.quantity, ret.reason, ret.datetime ] ws1.append(currentRow) filename = "Return_Report" + str( timezone.now().strftime("%Y%m%d-%H%M%S")) + ".xlsx" wb.save(REPORT_DIR + filename) reportMessage = "Return Report Ready" report = Report(user_id=userid, filename=filename, created_date=timezone.now(), report_type="RE") report.save() notify = Notification(user_id=userid, text=reportMessage, notification_type="RE", link="/staff/reports/?id=" + str(report.id), seen=False) notify.save()
def post(self, request, pk, *args, **kwargs): contact = self.get_object() client = Client.objects.get(id=pk) Notification(client=client, data={ 'action': 'contact.del', 'contact_id': contact.contact_id, 'contact_key': contact.contact_key }).save() messages.success(request, "Deletion request sent") return redirect(to='show_client', pk=pk)
def form_valid(self, form): client = Client.objects.get(id=self.kwargs['pk']) contact = client.contacts.get(id=self.kwargs['cid']) target = form.cleaned_data['endpoint'] Notification(client=client, data={ 'action': 'contact.dup', 'contact_id': contact.contact_id, 'contact_key': contact.contact_key, 'target': target.number }).save() messages.success(self.request, "Contact Cloned") return super().form_valid(form)
def form_valid(self, form): client = Client.objects.get(id=self.kwargs['pk']) target = form.cleaned_data['client'] payload = RawContactSerializer( target.profile.raw_contacts.first()).data print("payload:" + repr(payload)) Notification(client=client, data={ 'action': 'contact.new', 'payload': payload }).save() messages.success(self.request, "Link request sent") return super().form_valid(form)
def run_mail_sending_job(target_users=None, is_event=True): users = target_users if target_users is None or is_event: users = _find_target_users() for user in users: template_name = _determine_template(user) if (template_name is None or user.notifications.filter( email_template__name=template_name).exists() # NO double send ): continue template = EmailNotificationTemplate.objects.filter( name=template_name).first() logger.debug("Sending template %s to user %s", template, user.email) notification = Notification.create_user_email_notification( user=user, template=template, ) notification.send() notification.save() _handle_side_effects(user, template_name)
def webhooks_view(request): """ @params: None @return: HttpResponse @desc: Listen to Stripe events in order to take further actions """ payload = request.body event = None try: event = stripe.Event.construct_from( json.loads(payload), stripe.api_key ) except ValueError as e: return HttpResponse(status=400) #Handle Event if event.type == 'invoice.created': invoice = event.data.object client = Client.objects.get(customer_id=invoice.customer) client.statut = 'R' client.save() info = None if client.iban: info = client.iban else: info = client.card content = f'{datetime.fromtimestamp(invoice.created)} - {client.societe} - Demande de prélèvement pourble compte {info} {invoice.number}' notification = Notification(content=content) notification.save() send_mail('Statut Paiement', notification.content, settings.EMAIL_HOST_USER, [settings.EMAIL_HOST_USER], fail_silently=False) elif event.type == 'invoice.payment_succeeded': print("Invoice payment succceeded") invoice = event.data.object client = Client.objects.get(customer_id=invoice.customer) client.statut = 'R' client.save() content = f'{datetime.fromtimestamp(invoice.created)} - {client.societe} - Retour API concernant la transaction {invoice.number} Paiement OK' notification = Notification(content=content) notification.save() send_mail('Statut Paiement', notification.content, settings.EMAIL_HOST_USER, [settings.EMAIL_HOST_USER], fail_silently=False) if event.type == 'invoice.payment_succeeded': print("Invoice payment succceeded") invoice = event.data.object client = Client.objects.get(customer_id=invoice.customer) client.statut = 'R' client.save() content = f'{datetime.fromtimestamp(invoice.created)} - {client.societe} - Retour API concernant la transaction {invoice.number} Paiement OK' notification = Notification(content=content) notification.save() send_mail('Statut Paiement', notification.content, settings.EMAIL_HOST_USER, [settings.EMAIL_HOST_USER], fail_silently=False) elif event.type == 'invoice.payment_failed': invoice = event.data['object'] customer_id = invoice['customer'] client = Client.objects.get(customer_id=customer_id) client.statut = 'N' client.save() content = f'{datetime.fromtimestamp(invoice.created)} - {client.societe} - Retour API concernant la transaction {invoice.number} Echec Paiement' notification = Notification(content=content) notification.save() elif event.type == 'charge.succeeded': print('Charge succeed') elif event.type == 'charge.failed': print('Charge failed') elif event.type == 'payment_intent.succeeded': payment_intent = event.data['object'] customer_id = payment_intent['customer'] client = Client.objects.get(customer_id=customer_id) client.statut = 'R' new_date = int(client.date_reglement.timestamp() + (DAYS[client.periodicite] * 24 * 3600)) client.date_reglement = datetime.fromtimestamp(new_date) client.save() content = f'{datetime.fromtimestamp(payment_intent.created)} - {client.societe} - Retour API concernant la transaction {payment_intent.number} Echec' notification = Notification(content=content) notification.save() elif event.type == 'payment_intent.created': print('Payment intent created') elif event.type == 'payment_intent.payment_failed': payment_intent = event.data['object'] customer_id = payment_intent['customer'] client = Client.objects.get(customer_id=customer_id) client.statut = 'N' client.save() content = f'{datetime.fromtimestamp(payment_intent.created)} - {client.societe} - Retour API concernant la transaction {payment_intent.number} Echec' notification = Notification(content=content) notification.save() else: return HttpResponse(status=400) return HttpResponse(status=200)
def blog_comments(request): token = request.POST.get('token') blog_id = request.POST.get('id') comments = request.POST.get('comments') comments_id = request.POST.get('comments_id') if token != '': try: obj_token = Token.objects.get(token=token) try: data = {} _id = int(blog_id) blog = Blog.objects.get(pk=_id) # create comment comment_blog = Comment(blog=blog, user=obj_token.user, comments=comments, status=1) if comments_id != None: try: comment_reply_obj = Comment.objects.get(pk=comments_id) comment_blog.comments_reply = comment_reply_obj comment_blog.save() except Comment.DoesNotExist: response = { 'result': 0, 'message': 'Error comments id' } return JsonResponse(response) else: comment_blog.save() if obj_token.user != blog.author: # create notification notifi = Notification(blog=blog, user=obj_token.user, comment=comment_blog) notifi.save() # create notification count try: notifi_count = NotificationCount.objects.get( user=blog.author) notifi_count.count += 1 notifi_count.save() except NotificationCount.DoesNotExist: notifi_count = NotificationCount(user=blog.author, count=1) notifi_count.save() data = { 'id': notifi.id, 'user_id': notifi.user.id, 'username': notifi.user.username, 'firstName': notifi.user.first_name, 'lastName': notifi.user.last_name, 'blog_id': notifi.blog.id, 'blog_title': notifi.blog.title, 'blog_author': get_token_user(notifi.blog.author.username), 'comments_name': notifi.comment.comments, 'status': notifi.status, 'comments_id': notifi.comment.id, 'created_by_image': get_profile_image(notifi.user.username) } response = {'result': 1, 'data': data, 'message': 'success'} except Blog.DoesNotExist: response = {'result': 0, 'message': 'Error id'} except Exception as e: response = {'result': 0, 'message': 'Error token'} else: response = {'result': 0, 'message': '403'} return JsonResponse(response)
def post(self): """ Принять данные с датчика, проверить на уровень опасности, сгенерировать случай/событие :return: Tuple(JSON Object, HTTP Status Code) """ try: sensor_data = request.get_json() lpg_value = sensor_data.get('LPG') co_value = sensor_data.get('CO') smoke_value = sensor_data.get('Smoke') device_id = sensor_data.get('device_id') # последние данные с датчиков last_mq2data = MQ2Data.query.order_by(MQ2Data.date_time.desc()).first() last_dhtdata = DHTData.query.order_by(DHTData.date_time.desc()).first() device = Device.query.get(device_id) # проверяем на уровень опасности level = check_gas_level(lpg_value, co_value, smoke_value) if level != 0: mq2data = MQ2Data(lpg=lpg_value, co=co_value, smoke=smoke_value, device_id=device_id) db.session.add(mq2data) db.session.commit() # разница во времени между последней и текущей зафиксированной инф-и о детекции газа time_diff = mq2data.date_time - last_mq2data.date_time note = f"Warning! Gas detected! " \ f"Location: {device.location}. " \ f"Gas concentration - LPG: {lpg_value} ppm - CO: {co_value} ppm - Smoke: {smoke_value} ppm." # если разница больше чем 30 if time_diff.seconds > 30: # создаем новый случай case = Case() case.note = note case.level = LevelType(level) case.dht_data.append(last_dhtdata) case.mq2_data.append(mq2data) db.session.flush() case_id = case.id notification = Notification(content=note, case_id=case_id) db.session.add_all([case, notification]) # делаем рассылку уведомлений message = json.dumps({ "type": "case", "link": f"{CLIENT_APP_BASE_URL}/logs/cases/{case_id}", "message": note }) notify_about_warning(message) else: # в противном случае связываем информацию с датчиков в последний случай last_case = Case.query.order_by(Case.date_time.desc()).first() last_case.dht_data.append(last_dhtdata) last_case.mq2_data.append(mq2data) db.session.commit() return 200