Exemplo n.º 1
0
def invite_contractor(request, task_id, contractor_id):
    user = request.user
    contractor = UserProfile.objects.get(pk=contractor_id)
    task = Task.objects.get(pk=task_id)

    # try:
    if contractor.email:
        from views import email_html
        subject = 'invitation to a shoghlanah'
        to = [contractor.email]
        msg = 'please have a look at this shoghlanah, I thought you might be interested in'
        dic = {'task': task}
        email_html(subject=subject, to=to, msg=msg, dic=dic)

    from ShoghlanahProject import settings
    DEPLOYED_ADDRESS = getattr(settings, 'DEPLOYED_ADDRESS', '')

    receivers = [contractor]
    sender = user
    label = 'invite_to_task'
    the_message = 'Invitation to a Shoghlanah'
    message_arabic = 'دعوة عمل علي شغلانة'
    the_link = DEPLOYED_ADDRESS + 'task/' + task_id
    send_now(users=receivers,
             sender=sender,
             label=label,
             the_message=the_message,
             message_arabic=message_arabic,
             the_link=the_link)

    return HttpResponse("invitation sent to " + contractor.first_name + ' ' +
                        contractor.last_name)
Exemplo n.º 2
0
def accept_bid(request, bid_id):
    bid = Bid.objects.get(id=bid_id)
    task = Task.objects.get(id=bid.task.id)
    if task.user.id == request.user.id and task.status == "New":
        task.status = "close"
        task.save()
        bid.isAccepted = True
        bid.save()
        # Put notify user (Target user = bid.user)
        sender_profile = UserProfile.objects.get(pk=request.user.id)
        if sender_profile.gender == "F":
            sender = User.objects.get(pk=request.user.id)
            the_message = sender.first_name + ' accepted your bid on "' + task.title + '"'
            the_message_arabic = sender.first_name + ' قبلت المزايدة على "'.decode("utf-8") + task.title + '"'
            receivers = [User.objects.get(id=bid.user.id)]
            the_link = '/task/' + str(task.id)
            send_now(receivers, sender, 'post_task', the_message, the_message_arabic, the_link)
            notices = Notice.objects.filter(recipient=bid.user, sender=sender, message=the_message, message_arabic=the_message_arabic, link=the_link)
            p['channel_' + str(bid.user.username)].trigger('notification', {
                'message': sender.first_name + ' ' + sender.last_name + ' accepted your bid on  <a href="/task/' + str(task.id) + '/">' + task.title + '</a>',
                'name': sender.first_name + ' ' + sender.last_name,
                'translated': ' accepted your bid on ',
                'link': '<a href="/notifications/' + str(notices[0].id) + '/">' + task.title + '</a>',
                'the_title': sender.first_name,
                'the_title_translated': 'accepted your bid',
            })
        else:
            sender = User.objects.get(pk=request.user.id)
            the_message = sender.first_name + ' accepted your bid on "' + task.title + '"'
            the_message_arabic = sender.first_name + ' قبل المزايدة على "'.decode("utf-8") + task.title + '"'
            receivers = [User.objects.get(id=bid.user.id)]
            the_link = '/task/' + str(task.id)
            send_now(receivers, sender, 'post_task', the_message, the_message_arabic, the_link)
            notices = Notice.objects.filter(recipient=bid.user, sender=sender, message=the_message, message_arabic=the_message_arabic, link=the_link)
            p['channel_' + str(bid.user.username)].trigger('notification', {
                'message': sender.first_name + ' ' + sender.last_name + ' accepted your bid on  <a href="/task/' + str(task.id) + '/">' + task.title + '</a>',
                'name': sender.first_name + ' ' + sender.last_name,
                'translated': 'accepted your bid on',
                'link': '<a href="/notifications/' + str(notices[0].id) + '/">' + task.title + '</a>',
                'the_title': sender.first_name,
                'the_title_translated': 'accepted your bid',
            })
        p['channel_bid' + str(task.id)].trigger('accept_bid', {'bid': bid.isAccepted});
        # thereceiver = UserProfile.objects.get(id=bid.user.id)
        # if thereceiver.email_bid_accepted:
        from shoghlanah.views import email_html
        subject = "Bid Accepted"
        to = [bid.user.email]
        from_email = settings.EMAIL_HOST_USER
        msg = ' accepted your bid on the shoghlanah '
        dic = {}
        dic['bid'] = bid
        email_html(subject=subject, from_email=from_email, to=to, msg=msg, dic=dic)
    return HttpResponse('')
Exemplo n.º 3
0
    def save(self, product_id, user_id):
        try:
            quantity = self.cleaned_data['quantity']
            payment_choice = self.cleaned_data['payment_choice']
            buyer = UserProfile.objects.get(id=user_id)
            product = Product.objects.get(id=product_id)
            seller = product.user  #Seller is obtained from the product.
            city = self.cleaned_data['city']
            region = self.cleaned_data['region']
            address = self.cleaned_data['address']
            mobile_number = self.cleaned_data['mobile_number']
            special_notes = self.cleaned_data['special_notes']
            price = product.price * quantity

            order = Order.objects.create(quantity=quantity,
                                         price=price,
                                         payment_choice=payment_choice,
                                         seller=seller,
                                         product=product,
                                         buyer=buyer,
                                         mobile_number=mobile_number,
                                         address=address,
                                         city=city,
                                         region=region,
                                         special_notes=special_notes)
            order.save()

            # Email sent to product owner, & also to [email protected]
            subject = "An order has been made on one of your products!"
            to = [seller.email, '*****@*****.**']
            from_email = settings.EMAIL_HOST_USER
            msg = 'ordered your product!'
            dic = {}
            dic['order'] = order
            email_html(subject=subject,
                       from_email=from_email,
                       to=to,
                       msg=msg,
                       dic=dic)

            return HttpResponse("Created Successfully!")
        except ObjectDoesNotExist:
            return HttpResponse("Hacker!")
Exemplo n.º 4
0
    def save(self, product_id, user_id):
        try:
            quantity = self.cleaned_data['quantity']
            payment_choice = self.cleaned_data['payment_choice']
            buyer = UserProfile.objects.get(id=user_id)
            product = Product.objects.get(id=product_id)
            seller = product.user #Seller is obtained from the product.
            city = self.cleaned_data['city']
            region = self.cleaned_data['region']
            address = self.cleaned_data['address']
            mobile_number = self.cleaned_data['mobile_number']
            special_notes = self.cleaned_data['special_notes']
            price = product.price * quantity

            order = Order.objects.create(
                quantity = quantity,
                price = price,
                payment_choice = payment_choice,
                seller = seller,
                product = product,
                buyer=buyer,
                mobile_number=mobile_number,
                address = address,
                city = city,
                region = region,
                special_notes = special_notes)
            order.save()

            # Email sent to product owner, & also to [email protected]
            subject = "An order has been made on one of your products!"
            to = [seller.email, '*****@*****.**']
            from_email = settings.EMAIL_HOST_USER
            msg = 'ordered your product!'
            dic = {}
            dic['order'] = order
            email_html(subject=subject, from_email=from_email, to=to, msg=msg, dic=dic)

            return HttpResponse("Created Successfully!")
        except ObjectDoesNotExist:
            return HttpResponse("Hacker!")
Exemplo n.º 5
0
def post_task(request):
    """
    This method is called when the user posts a task

    The information taken from the html form and creates a task
    with the data entered in the postTask modal

    The Task created is assigned to the user currently login

    After the task is saved in the database, the user is redirected
    to the page the posttask action wast triggered from

    Variable:
    next : is the variable which contains the name of the page
    the posttask was triggered from.
    """

    if request.method == 'POST':
        try:
            # price = request.POST['price']
            # if price == 'Reward':
            #     reward_id = request.POST['reward']
            #     reward = Reward.objects.get(pk = reward_id)
            #     price = None
            # else:
            price = int(request.POST['sliderInput'])
            reward = None
            if isinstance(price, int):
                price = price
            else:
                raise ValueError('Invalid price')
            # if price == None and reward == None:
            if price is None:
                raise ValidationError(
                    u'You have to enter price or reward of the task')
            longitude = request.POST['long']
            latitude = request.POST['lat']
            latitude = latitude.replace(',', '.')
            longitude = longitude.replace(',', '.')
            if longitude == '' or latitude == '':
                longitude = 200.0
                latitude = 200.0
            user = UserProfile.objects.get(id=request.user.id)
            location = request.POST['where']
            if location is not None and len(location) > 0:
                temp_loc = location.split(',')
                if len(temp_loc) > 1:
                    city = temp_loc[len(temp_loc) - 2].strip()
                else:
                    city = temp_loc[0].strip()
                if city.endswith('Governorate'):
                    city = city[:-len('Governorate')].strip()
            else:
                raise ValueError('Empty location')

            title = request.POST['task_name']
            if title is not None and len(title) > 0 and not title.isspace():
                if (len(title) <= 128):
                    title = title.strip()
                else:
                    raise ValueError('Title Too long')
            else:
                raise ValueError('Empty Title')
            task = Task.objects.create(
                title=title,
                address=location,
                city=city,
                price=price,
                reward=reward,
                description=request.POST['task_desc'],
                user=user,
                longitude=float(longitude),
                latitude=float(latitude),
                status='New',
                start_date=datetime.datetime.now(),
            )

            task.tags = ',' + request.POST['skills']
            if 'got_started' in request.POST:

                user.got_started = True
                user.save()
            task.save()
            add_action(user, "task_post", task, "", user)
            # sender = []
            # for tag in task.tags:
            #     sender.append(User.objects.filter(tag__contains=tag))
            sender_profile = UserProfile.objects.get(pk=request.user.id)
            sender = User.objects.get(pk=request.user.id)
            the_message = sender.first_name + ' needs "' + task.title + '"'
            if sender_profile.gender == 'F':
                the_message_arabic = sender.first_name + ' تريد "'.decode(
                    "utf-8") + task.title + '"'
            else:
                the_message_arabic = sender.first_name + ' يريد "'.decode(
                    "utf-8") + task.title + '"'
            receivers = [
                UserProfile.objects.get(id=item.object_id)
                for skill in task.tags
                for item in TaggedItem.objects.filter(tag=skill.id)
                if item.content_type.name == u'user profile'
                and item.object_id != request.user.id
            ]
            the_link = '/task/' + str(task.id)
            send_now(receivers, sender, 'post_task', the_message,
                     the_message_arabic, the_link)

            for receiver in receivers:
                if not receiver.id == request.user.id:
                    notices = Notice.objects.filter(
                        recipient=receiver,
                        sender=sender,
                        message=the_message,
                        message_arabic=the_message_arabic,
                        link=the_link)
                    p['channel_' + str(receiver.username)].trigger(
                        'notification', {
                            'message':
                            sender.first_name + ' ' + sender.last_name +
                            ' needs  ' + '<a href="/task/' + str(task.id) +
                            '/">' + task.title + '</a>',
                            'name':
                            sender.first_name + ' ' + sender.last_name,
                            'translated':
                            'needs',
                            'link':
                            '<a href="/notifications/' + str(notices[0].id) +
                            '/">' + task.title + '</a>',
                            'the_title_translated':
                            'A New shoghlanah is Posted',
                            'the_title':
                            ' ',
                        })

            from shoghlanah.views import email_html
            subject = "A new shoghlanah is posted"
            to = []
            for receiver in receivers:
                # thereceiver = UserProfile.objects.get(id=receiver.id)
                # if thereceiver.email_new_shoghlanah:
                to.append(receiver.email)
            from_email = settings.EMAIL_HOST_USER
            msg = ' shoghlanah is posted.'
            dic = {}
            dic['task'] = task
            email_html(subject=subject,
                       from_email=from_email,
                       to=to,
                       msg=msg,
                       dic=dic)

            # if user.complete_profile <= 100:
            #     return redirect() #to complete hos profile

            if 'facebook' in request.POST:
                post_task_fb(task=task, request=request)
            if 'twitter' in request.POST:
                tweet(request,
                      status="i posted a task on #Shoghlanah " +
                      DEPLOYED_ADDRESS + "task/" + str(task.id) + '/')
            # if 'google' in request.POST:

            messages.info(request,
                          translation.gettext("Created a task successfully"))
            return redirect('/task/' + str(task.id),
                            context_instance=RequestContext(request))
        except:
            messages.warning(
                request,
                translation.gettext("Failed to post a task, try again"))
            return redirect(request.GET['next'],
                            context_instance=RequestContext(request))
Exemplo n.º 6
0
def message(request, receiver_id, task_id, bid_id=None):
    """
        this method is accessed when a user enter a message in the input field
        and the ajax function in message.html POST the data here after getting
        the data from the form, it saves the text in the database then trigger
        an event called 'message' to the pusher channel to allow any user
        subscribed to this channel to recieve this event with the data passed too
    """
    stamp = datetime.datetime.now()
    timestamp = stamp.strftime("%b %d, %Y | %I:%M %p")
    sender = UserProfile.objects.get(id=request.user.id)
    receiver = UserProfile.objects.get(id=receiver_id)
    task = Task.objects.get(id=task_id)
    msg = request.POST.get('message')
    if msg == ' ':
        return HttpResponse('')
    if bid_id is None:
        bids = Bid.objects.filter(task=task_id).filter(user=request.user.id)
        if bids:
            bid = bids[0]
            bid.last_msg = datetime.datetime.now()
        else:
            bid = None
            if task.price is None:
                bid = Bid.objects.create(task=task,
                                         user=sender,
                                         message=task.reward,
                                         last_msg=datetime.datetime.now())
            else:
                bid = Bid.objects.create(task=task,
                                         user=sender,
                                         message=task.price,
                                         last_msg=datetime.datetime.now())

            # if receiver.email_bid_placed:
            from shoghlanah.views import email_html
            subject = "A bid on your shoghlanah"
            to = [receiver.email]
            from_email = settings.EMAIL_HOST_USER
            msg = 'bidded on your shoghlanah '
            dic = {}
            dic['bid'] = bid
            email_html(subject=subject,
                       from_email=from_email,
                       to=to,
                       msg=msg,
                       dic=dic)
        bid.save()
    else:
        bid = Bid.objects.get(id=bid_id)
        bid.last_msg = datetime.datetime.now()
        bid.save()
    if request.POST.get('message'):
        p['channel_chat' + str(receiver_id) + str(sender.id) +
          str(task_id)].trigger(
              'message', {
                  'message': request.POST.get('message'),
                  'user': sender.username,
                  'id': str(sender.id),
                  'name': sender.first_name + " " + sender.last_name,
                  'timestamp': timestamp,
              })
        p['channel_chat' + str(sender.id) + str(receiver_id) +
          str(task_id)].trigger(
              'message', {
                  'message': request.POST.get('message'),
                  'user': sender.username,
                  'id': str(sender.id),
                  'name': sender.first_name + " " + sender.last_name,
                  'timestamp': timestamp,
              })
        Discussion.objects.create(message=request.POST.get('message'),
                                  sender=sender,
                                  receiver=receiver,
                                  time=datetime.datetime.now(),
                                  bid=bid)
        if sender.gender == "F":
            if bid_id is None:
                # Put notify user (Target user = receiver)
                sender = UserProfile.objects.get(id=request.user.id)
                the_message = sender.first_name + ' bidded on your task "' + task.title + '"'
                the_message_arabic = sender.first_name + ' وضعت مزايدة على "'.decode(
                    "utf-8") + task.title + '"'
                receivers = [UserProfile.objects.get(id=receiver_id)]
                the_link = '/task/' + str(task.id)
                try:
                    send_now(receivers, sender, 'post_task', the_message,
                             the_message_arabic, the_link)
                    notices = Notice.objects.filter(
                        recipient=receiver,
                        sender=sender,
                        message=the_message,
                        message_arabic=the_message_arabic,
                        link=the_link)
                except:
                    pass
                p['channel_' + str(receiver.username)].trigger(
                    'notification', {
                        'message':
                        sender.first_name + ' ' + sender.last_name +
                        ' bidded on your task  <a href="/task/' +
                        str(task.id) + '/">' + task.title + '</a>',
                        'name':
                        sender.first_name + ' ' + sender.last_name,
                        'translated':
                        ' bidded on your task ',
                        'link':
                        '<a href="/notifications/' + str(notices[0].id) +
                        '/">' + task.title + '</a>',
                        'the_title':
                        sender.first_name,
                        'the_title_translated':
                        'bidded on your task',
                    })
            else:
                sender = UserProfile.objects.get(id=request.user.id)
                the_message = sender.first_name + ' discussed "' + task.title + '"'
                the_message_arabic = sender.first_name + ' ناقشت "'.decode(
                    "utf-8") + task.title + '"'
                receivers = [UserProfile.objects.get(id=receiver_id)]
                the_link = '/task/' + str(task.id)
                # Notice.objects.filter(recipient=receiver, sender=sender, link=the_link).delete()
                try:
                    send_now(receivers, sender, 'post_task', the_message,
                             the_message_arabic, the_link)
                    notices = Notice.objects.filter(
                        recipient=receiver,
                        sender=sender,
                        message=the_message,
                        message_arabic=the_message_arabic,
                        link=the_link)
                except:
                    pass
                p['channel_' + str(receiver.username)].trigger(
                    'notification', {
                        'message':
                        sender.first_name + ' ' + sender.last_name +
                        ' sent a message on your task  <a href="/task/' +
                        str(task.id) + '/">' + task.title + '</a>',
                        'name':
                        sender.first_name + ' ' + sender.last_name,
                        'translated':
                        ' sent a message on your task ',
                        'link':
                        '<a href="/notifications/' + str(notices[0].id) +
                        '/">' + task.title + '</a>',
                        'the_title':
                        sender.first_name,
                        'the_title_translated':
                        'is chatting with you',
                    })
                # thereceiver = UserProfile.objects.get(id=receiver.id)
                # if thereceiver.email_discuss_shoghlanah:
                from shoghlanah.views import email_html
                ########################### BEGIN CURRENT TEMPLATE CHECK #####################
                from currentTemplate.models import UserActivity
                import re
                thirty_minutes = datetime.datetime.now() - datetime.timedelta(
                    minutes=30)
                sql_datetime = datetime.datetime.strftime(
                    thirty_minutes, '%Y-%m-%d %H:%M:%S')
                users = UserActivity.objects.filter(
                    latest_activity__gte=sql_datetime,
                    user__is_active__exact=1,
                )
                send = True
                for user in users:
                    template = user.current_template
                    task_id = re.findall(r'/task/(.*?)/', template)
                    if task_id and user.user.username == receiver.username:
                        send = False
                ######################### END CURRENT TEMPLATE CHECK ############################
                if send:
                    subject = "Discussion on your shoghlanah"
                    to = [receiver.email]
                    from_email = settings.EMAIL_HOST_USER
                    msg = ' sent you a message on your shoghlanah '
                    dic = {}
                    dic['bid'] = bid
                    email_html(subject=subject,
                               from_email=from_email,
                               to=to,
                               msg=msg,
                               dic=dic)
        else:
            if bid_id is None:
                # Put notify user (Target user = receiver)
                sender = UserProfile.objects.get(id=request.user.id)
                the_message = sender.first_name + ' bidded on your task "' + task.title + '"'
                the_message_arabic = sender.first_name + ' وضع مزايدة على "'.decode(
                    "utf-8") + task.title + '"'
                receivers = [UserProfile.objects.get(id=receiver_id)]
                the_link = '/task/' + str(task.id)
                try:
                    send_now(receivers, sender, 'post_task', the_message,
                             the_message_arabic, the_link)
                    notices = Notice.objects.filter(
                        recipient=receiver,
                        sender=sender,
                        message=the_message,
                        message_arabic=the_message_arabic,
                        link=the_link)
                except:
                    pass
                p['channel_' + str(receiver.username)].trigger(
                    'notification', {
                        'message':
                        sender.first_name + ' ' + sender.last_name +
                        ' bidded on your task  <a href="/task/' +
                        str(task.id) + '/">' + task.title + '</a>',
                        'name':
                        sender.first_name + ' ' + sender.last_name,
                        'translated':
                        'bidded on your task',
                        'link':
                        '<a href="/notifications/' + str(notices[0].id) +
                        '/">' + task.title + '</a>',
                        'the_title':
                        sender.first_name,
                        'the_title_translated':
                        'bidded on your task',
                    })
            else:
                sender = UserProfile.objects.get(id=request.user.id)
                the_message = sender.first_name + ' discussed "' + task.title + '"'
                the_message_arabic = sender.first_name + ' ناقش "'.decode(
                    "utf-8") + task.title + '"'
                receivers = [UserProfile.objects.get(id=receiver_id)]
                the_link = '/task/' + str(task.id)
                # Notice.objects.filter(recipient=receiver, sender=sender, link=the_link).delete()
                try:
                    send_now(receivers, sender, 'post_task', the_message,
                             the_message_arabic, the_link)
                    notices = Notice.objects.filter(
                        recipient=receiver,
                        sender=sender,
                        message=the_message,
                        message_arabic=the_message_arabic,
                        link=the_link)
                except:
                    pass
                p['channel_' + str(receiver.username)].trigger(
                    'notification', {
                        'message':
                        sender.first_name + ' ' + sender.last_name +
                        ' sent a message on your task  <a href="/task/' +
                        str(task.id) + '/">' + task.title + '</a>',
                        'name':
                        sender.first_name + ' ' + sender.last_name,
                        'translated':
                        'sent a message on your task',
                        'link':
                        '<a href="/notifications/' + str(notices[0].id) +
                        '/">' + task.title + '</a>',
                        'the_title':
                        sender.first_name,
                        'the_title_translated':
                        'is chatting with you',
                    })
                # thereceiver = UserProfile.objects.get(id=receiver.id)
                # if thereceiver.email_discuss_shoghlanah:
                from shoghlanah.views import email_html
                ########################### BEGIN CURRENT TEMPLATE CHECK #####################
                from currentTemplate.models import UserActivity
                import re
                thirty_minutes = datetime.datetime.now() - datetime.timedelta(
                    minutes=30)
                sql_datetime = datetime.datetime.strftime(
                    thirty_minutes, '%Y-%m-%d %H:%M:%S')
                users = UserActivity.objects.filter(
                    latest_activity__gte=sql_datetime,
                    user__is_active__exact=1,
                )
                send = True
                for user in users:
                    template = user.current_template
                    task_id = re.findall(r'/task/(.*?)/', template)
                    if task_id and user.user.username == receiver.username:
                        send = False
                ######################### END CURRENT TEMPLATE CHECK ############################
                if send:
                    subject = "Discussion on your shoghlanah"
                    to = [receiver.email]
                    from_email = settings.EMAIL_HOST_USER
                    msg = ' sent you a message on your shoghlanah '
                    dic = {}
                    dic['bid'] = bid
                    email_html(subject=subject,
                               from_email=from_email,
                               to=to,
                               msg=msg,
                               dic=dic)

    return HttpResponse('')