def handle(self, *args, **options): now = datetime.datetime.now() dow = now.weekday() begin = now + datetime.timedelta(minutes=WARN_DELAY_MIN) end = now + datetime.timedelta(minutes=WARN_DELAY_MAX) slots = WebclassSlot.published.filter(day=dow, start_hour__gte=begin.time(), start_hour__lt=end.time()) site = Site.objects.all()[0] admin = User.objects.get(username='******') date = now.strftime('%d/%m/%Y') for slot in slots: hour = slot.start_hour.strftime('%Hh%M') print("Sending notifications for %s:%s (%s)" % (slot.webclass.course, slot.start_hour, slot.id)) subject = "Webclass_%s_%s_%s" % (slot.webclass.course, date, hour) body = """Votre Webclasse va commencer.""" users = slot.participants.all() for user in users: print(" => %s" % user) msg = Message(subject=subject, body=body, sender=admin, recipient=user) msg.moderation_status = 'a' msg.save() notify_user(msg, 'acceptance', site)
def send(self): site = Site.objects.all()[0] users = [student.user for student in self.group.students.all()] for user in users: mess = Message(sender=self.sender, recipient=user, subject=self.subject[:119], body=self.message) mess.moderation_status = 'a' mess.save() notify_user(mess, 'acceptance', site)
def create_fake_conversation(user1, user2, user3, items=20): base_time = datetime.datetime(2014, 7, 28, 12, 0, 0, 0, get_current_timezone()) batches = [] flat = [] for i in range(items): step_time = base_time + datetime.timedelta(hours=i) batch = [] m1 = Message(sender=user1, recipient=user2, subject='subject_%s' % i, body='body_a_%s' % i, sent_at=step_time + datetime.timedelta(minutes=0)) m1.save() batch.append(m1) flat.append(m1) m2 = Message(sender=user3, recipient=user1, subject='ignore', body='ignore', sent_at=step_time + datetime.timedelta(minutes=10)) m2.save() batch.append(m2) flat.append(m2) m3 = Message(sender=user2, recipient=user1, subject='subject_%s' % i, body='body_b_%s' % i, sent_at=step_time + datetime.timedelta(minutes=20)) m3.save() batch.append(m3) flat.append(m3) batches.append(batch) transaction.commit() return batches, flat
def reject(self): self.date_marked = datetime.datetime.now() self.date_rejected = datetime.datetime.now() site = Site.objects.all()[0] context = {'script': self, 'site': site} text = render_to_string('exam/messages/script_rejected.txt', context) a = ugettext('Script') v = ugettext('rejected') subject = '%s %s' % (a, v) mess = Message(sender=self.corrector, recipient=self.author, subject=subject[:119], body=text) mess.moderation_status = 'a' mess.save() notify_user(mess, 'acceptance', site)
def pm_write(sender, recipient, subject, body='', skip_notification=False, auto_archive=False, auto_delete=False): """ Write a message to a User. Contrary to pm_broadcast(), the message is archived and/or deleted on the sender side only if requested. Optional arguments: ``skip_notification``: if the normal notification event is not wished ``auto_archive``: to mark the message as archived on the sender side ``auto_delete``: to mark the message as deleted on the sender side """ message = Message(subject=subject, body=body, sender=sender, recipient=recipient, moderation_status=STATUS_ACCEPTED, moderation_date=now()) if auto_archive: message.sender_archived = True if auto_delete: message.sender_deleted_at = now() message.save() if not skip_notification: message.notify_users(STATUS_PENDING)
def pm_broadcast(sender, recipients, subject, body='', skip_notification=False): """ Broadcast a message to multiple Users. For an easier cleanup, all these messages are directly marked as archived and deleted on the sender side. The message is expected to be issued from a trusted application, so moderation is not necessary and the status is automatically set to 'accepted'. Optional argument: ``skip_notification``: if the normal notification event is not wished """ message = Message(subject=subject, body=body, sender=sender, sender_archived=True, sender_deleted_at=now(), moderation_status=STATUS_ACCEPTED, moderation_date=now()) if not isinstance(recipients, (tuple, list)): recipients = (recipients, ) for recipient in recipients: message.recipient = recipient message.pk = None message.save() if not skip_notification: message.notify_users(STATUS_PENDING)
def _send_private_messages_recipient_and_admin(subject, body, recipient): status = STATUS_ACCEPTED sender = User.objects.filter(username='******').first() message_user = Message(subject=subject, body=body, sender=sender, recipient=recipient, moderation_status=status) message_user.save() message_admin = Message(subject=subject, body=body, sender=recipient, recipient=sender, moderation_status=status) message_admin.save()
def pm_write_corp(sender, recipient, subject, body='', msgType=None,auto_moderators=None): if auto_moderators == None: auto_moderators= [mod1] else: auto_moderators.append(mod1) message = Message(subject=subject, body=body, sender=sender, recipient=recipient) initial_status = message.moderation_status if auto_moderators: message.auto_moderate(auto_moderators) else: message.moderation_status = STATUS_ACCEPTED message.clean_moderation(initial_status) message.save() message.notify_users(initial_status,msgType=msgType)
def _setup_test_message(cls, sender): message = Message( subject=cls.faker.sentence(), body=cls.faker.paragraph(), sender=sender, recipient=cls.sender, ) message.auto_moderate([]) message.save() return message
def pm_broadcast(sender, recipients, subject, body='', skip_notification=False): """ Broadcast a message to multiple Users. For an easier cleanup, all these messages are directly marked as archived and deleted on the sender side. The message is expected to be issued from a trusted application, so moderation is not necessary and the status is automatically set to 'accepted'. Optional argument: ``skip_notification``: if the normal notification event is not wished """ message = Message(subject=subject, body=body, sender=sender, sender_archived=True, sender_deleted_at=now(), moderation_status=STATUS_ACCEPTED, moderation_date=now()) if not isinstance(recipients, (tuple, list)): recipients = (recipients,) for recipient in recipients: message.recipient = recipient message.pk = None message.thread_id = None message.save() if not skip_notification: message.notify_users(STATUS_PENDING)
def pm_write(sender, recipient, subject, body='', skip_notification=False, auto_archive=False, auto_delete=False, auto_moderators=None): """ Write a message to a User. Contrary to pm_broadcast(), the message is archived and/or deleted on the sender side only if requested. The message may come from an untrusted application, a gateway for example, so it may be useful to involve some auto moderators in the processing. Optional arguments: ``skip_notification``: if the normal notification event is not wished ``auto_archive``: to mark the message as archived on the sender side ``auto_delete``: to mark the message as deleted on the sender side ``auto_moderators``: a list of auto-moderation functions """ message = Message(subject=subject, body=body, sender=sender, recipient=recipient) initial_status = message.moderation_status if auto_moderators: message.auto_moderate(auto_moderators) else: message.moderation_status = STATUS_ACCEPTED message.clean_moderation(initial_status) if auto_archive: message.sender_archived = True if auto_delete: message.sender_deleted_at = now() message.save() if not skip_notification: message.notify_users(initial_status, _get_site())
def order_notification(cart, order, user): cart_storages = make_cart_storages(cart, user) for cart_storage, items in cart_storages.items(): body = 'Новый заказ от {date} #{order_number}.\r\n\r\nИнформация о заказе:\r\n'.format( date=order.added.strftime('%d.%m.%Y %H:%M'), order_number=order.id) profile = UserProfile.objects.get(user=user) body += 'Заказчик: {name} \r\n'.format( name=profile.fullname or profile) body += 'Код заказчика: {vip_code}\r\n'.format( vip_code=profile.vip_code or 'код заказчика отсутствует') storage = cart_storage order_total = 0 for idx, item in enumerate(items): product = item.item price = product.get_price(user, item.storage) qty = item.quantity order_total += price * qty body += '{idx}. {title} {brand} {sku}, {qty} шт. x {price} руб.., на общую сумму: {line_total} руб.\r\n'.format( idx=idx + 1, title=product.title, brand=product.brand, sku=product.get_sku(), qty=qty, price=price, line_total=qty * price) op = OrderProduct(order=order, item=product, qty=qty, price=price) op.save() body += '\r\nИтого: {total} руб.'.format(total=order_total) body += '\r\nСклад: {storage}'.format(storage=storage.name) body += '\r\n\r\nEmail клиента: {email}'.format(email=user.email) body += '\r\n\r\nКомментарии к заказу:\r\n{comment}'.format( comment=order.comment) subject = 'Сформирован новый заказ от {date} № {order_num}!'.format( date=order.added.strftime("%d.%m.%Y %H:%M"), order_num=order.id) sender = User.objects.filter(username='******').first() recipient = user status = STATUS_ACCEPTED message_user = Message(subject=subject, body=body, sender=sender, recipient=recipient, moderation_status=status) message_user.save() message_admin = Message(subject=subject, body=body, sender=recipient, recipient=sender, moderation_status=status) message_admin.save() # XLS document wb = Workbook() ws = wb.active ws.title = 'Заказ' thin_border = Border(left=Side(style='thin'), right=Side(style='thin'), top=Side(style='thin'), bottom=Side(style='thin')) data = [] for idx, item in enumerate(cart.cartitem_set.all()): product = item.item price = product.get_price(user, item.storage) print(item.storage) print(price) qty = item.quantity coordinate = 'B' + str(idx) article = '%s %s' % (product.brand, product.get_sku()) data.append( [idx + 1, product.title, article, qty, price, qty * price]) ws.append([ '#', 'Товар', 'Брэнд', 'Количество', 'Цена за единицу', 'Цена (общая)' ]) for row in data: ws.append(row) ws.append(['', '', '', '', 'Итого:', order_total]) row_count = ws.max_row + 1 column_count = ws.max_column + 1 for i in range(1, row_count): for j in range(1, column_count): ws.cell(row=i, column=j).border = thin_border ws.column_dimensions["A"].width = 5.0 ws.column_dimensions["B"].width = 17.0 ws.column_dimensions["C"].width = 23.0 ws.column_dimensions["D"].width = 13.0 ws.column_dimensions["E"].width = 18.0 ws.column_dimensions["F"].width = 18.0 email = EmailMessage( subject, body, EMAIL_NOREPLY, [storage.email], EMAIL_BCC, reply_to=EMAIL_NOREPLY_LIST, headers={'Message-ID': 'foo'}, ) output = BytesIO() wb.save(output) email.attach('order.xlsx', output.getvalue(), 'application/excel') email.send() return True
def create_message(sender, recipient, subject, body='', skip_notification=False, auto_archive=False, auto_delete=False, auto_moderators=None, sent_at=None): if not user_is_valid(sender): raise InvalidSenderException() if not user_is_valid(recipient): raise InvalidRecipientException() if subject is None or subject == '': raise NoMessageSubjectException('this message has an empty subject line. Messages without subject cannot be sent') if body is None or body == '': raise NoMessageBodyException('this message has an empty message body. Empty message cannot be sent') message = Message(subject=subject, body=body, sender=sender, recipient=recipient) if not sent_at is None: message.sent_at = sent_at initial_status = message.moderation_status if auto_moderators: message.auto_moderate(auto_moderators) else: message.moderation_status = STATUS_ACCEPTED message.clean_moderation(initial_status) if auto_archive: message.sender_archived = True if auto_delete: message.sender_deleted_at = now() message.save() if not skip_notification: message.notify_users(initial_status, _get_site()) return message
def create(self, validated_data, recipient=None, parent=None, reply_all=None, auto_moderators=[]): """ Save as many messages as there are recipients. Additional actions: - If it's a reply, build a conversation - Call auto-moderators - Notify parties if needed Return False if one of the messages is rejected. """ if validated_data and 'recipients' in validated_data: # action is "create" recipients = validated_data['recipients'] new_messsage = DmMessage(subject=validated_data['subject'], body=validated_data['body'], sender=self.sender, moderation_status=STATUS_ACCEPTED) elif parent: # action is "reply" if reply_all: recipients = validated_data['recipients'] else: recipients = parent.sender quoted = parent.quote(*(format_subject, format_body)) # print quoted, parent.subject sbjct = validated_data['subject'] if ( validated_data and 'subject' in validated_data) else quoted['subject'] # bdy = validated_data['body'] if (validated_data and 'body' in validated_data) else format_body(parent.sender, parent.body) new_messsage = DmMessage(subject=sbjct, body=validated_data['body'], sender=self.sender, moderation_status=STATUS_ACCEPTED) # print type(recipients), new_messsage.subject, new_messsage.body if parent and not parent.thread_id: # at the very first reply, make it a conversation parent.thread = parent parent.save() # but delay the setting of parent.replied_at to the moderation step if parent: new_messsage.parent = parent new_messsage.thread_id = parent.thread_id initial_moderation = new_messsage.get_moderation() initial_dates = new_messsage.get_dates() initial_status = new_messsage.moderation_status if recipient: if isinstance(recipient, get_user_model()) and recipient in recipients: recipients.remove(recipient) recipients.insert(0, recipient) is_successful = True if isinstance(recipients, get_user_model()): # change to list type recipients = [recipients] for r in recipients: usr_model = get_user_model() if isinstance(r, get_user_model()): new_messsage.recipient = r else: new_messsage.recipient = usr_model.objects.get(email=r) new_messsage.pk = None # force_insert=True is not accessible from here new_messsage.auto_moderate(auto_moderators) new_messsage.clean_moderation(initial_status) new_messsage.clean_for_visitor() m = new_messsage.save() if new_messsage.is_rejected(): is_successful = False new_messsage.update_parent(initial_status) # new_messsage.notify_users(initial_status, self.site) # some resets for next reuse if not isinstance(r, get_user_model()): new_messsage.email = '' new_messsage.set_moderation(*initial_moderation) new_messsage.set_dates(*initial_dates) return is_successful
def accept_offer(request, pk, trader_pk): if(request.POST['acceptbtn']): #Close favor post curFavor = Favor.objects.get(pk=pk) curFavor.status = 'closed' curFavor.save() #Create new agreement curAgreement = Agreement() curAgreement.favor = curFavor curAgreement.accepter = User.objects.get(pk=trader_pk) curAgreement.save() #Create message curMessage = Message(subject=curFavor.title, body="Favor agreement has been made. You may now initiate conversation with the other user.", moderation_status='a') curMessage.sender = User.objects.get(pk=trader_pk) curMessage.recipient = curFavor.author curMessage.agreement = curAgreement curMessage.save() curMessage.thread = curMessage curMessage.save() otherMessage = Message(subject=curFavor.title, body="Favor agreement has been made. You may now initiate conversation with the other user.", moderation_status='a') otherMessage.sender = curFavor.author otherMessage.recipient = User.objects.get(pk=trader_pk) otherMessage.thread = curMessage otherMessage.save() return HttpResponseRedirect("/messages/")
def deliver_pending(request): ''' Find notifications in Queue state and deliver to all recipients. We actually do two things here: 1) Created a Delivered record in our own Notifications app, so we have a custom record that can be displayed in the widget, which the user can check off as completed, etc.; and 2) Deliver a system message via Postman. The get_members() method on DynamicList aggregates all logical recipients. Django-Postman lets us save a Message instance and takes care of delivery. This function is never accessed by users - superusers and cron jobs only. Superusers can trigger delivery without cron by accessing /notifications/deliver_pending ''' notifications = Notification.objects.filter(state='queue') for n in notifications: # Find all members associated with this notification's associated dynamic list if n.dlist: recips = n.dlist.get_members() if n.offering: recips = n.offering.get_members() # What if there's both a dlist and an offering? Need a way to combine them here for r in recips: # Create Postman message msg = Message() # Instantiate new message on Postman's Message class msg.subject = 'New %s on CalCentral: %s' % (n.type, n.title) msg.body = n.description msg.sender = n.author msg.recipient = r msg.moderation_status = STATUS_ACCEPTED # a = accepted. Override postman default = all msgs are pending msg.notify_users(STATUS_PENDING,is_auto_moderated=True) msg.save() # Create a Deliver instance for each user d = Delivered() d.notification = n d.user = r d.completed = False d.deliver_date = datetime.datetime.now() d.save() # Move the notification from the queue to the archive n.state = 'arch' n.save() # Since this is not a browser view, just need an empty httpresponse return HttpResponseRedirect(reverse('notifications'))