예제 #1
0
    def testAcceptRec(self):
        SettingsManager.set_property('rnes', 3)
        self.register()
        requester_company, requester_employee, requester_user, request = self.register_verification_requesters(self.company, 3)[0]

        self.login()
        mail.outbox = []

        self.assertEqual(RecommendationRequest.objects.count(), 3)

        response = self.client.post('/recommendations/accept/%s/' % str(request._id))
        self.assertEqual(response.status_code, 200)

        data = simplejson.loads(response.content)
        self.assertTrue(isinstance(data, dict))
        self.assertIn('error', data)
        self.assertFalse(data['error'])

        self.assertEqual(len(mail.outbox), 0)

        request_post = RecommendationRequest.objects.get_one({'_id' : request._id})
        self.assertIsNotNone(request_post)
        self.assertEqual(request_post.status, RecommendationStatusEnum.ACCEPTED)
        self.assertEqual(request_post.requester, requester_company._id)
        self.assertEqual(request_post.recipient, self.company._id)
        self.assertEqual(request_post.viewed, False)
        self.assertEqual(request_post.requester_email, requester_user.email)

        self.assertEqual(RecommendationRequest.objects.count(), 3)
예제 #2
0
    def test_twice_register_after_invite(self):
        SettingsManager.set_property('rnes', 3)
        self.register()
        self.login()

        data = {'msg' : 'Come on! Join us now!',
                'email' : '*****@*****.**'}

        notifications = Notification.objects.get({})
        self.assertEqual(len(notifications), 0)

        response = self.client.post('/invites/send/', data)
        self.assertEquals(response.status_code, 200)

        invites = Invite.objects.get({})
        self.assertEqual(len(invites), 1)
        invite = invites[0]
        self.assertEqual(invite.message, 'Come on! Join us now!')
        self.assertEqual(invite.email, '*****@*****.**')

        data = simplejson.loads(response.content)
        self.assertTrue(isinstance(data, dict))
        self.assertIn('success', data)
        self.assertTrue(data['success'])

        self.logout()
        response = self.client.get(u'/invites/join/%s/' % invite.cookie_code)
        self.assertEquals(response.status_code, 302)
        self.assertTrue(self.client.cookies.has_key('invite'))

        self.assertEqual(Company.objects.count(), 1)
        self.assertEqual(RecommendationRequest.objects.count(), 0)
        self.register(email="*****@*****.**", verified=False)
        self.login()
        self.assertEqual(Company.objects.count(), 2)

        invite = Invite.objects.get_one({})
        self.assertEqual(RecommendationRequest.objects.count(), 1)
        self.assertEqual(invite.rec_request, RecommendationRequest.objects.get_one({})._id)

        user = User(User.collection.find_one({'email' : "*****@*****.**"}))
        company = get_user_company(user)
        self.assertEqual(company.account_status, CompanyAccountStatus.JUST_REGISTERED)

        self.logout()
        self.client = Client()
        response = self.client.get(u'/invites/join/%s/' % invite.cookie_code)
        self.assertEquals(response.status_code, 302)
        self.assertFalse(self.client.cookies.has_key('invite'))

        self.assertEqual(Company.objects.count(), 2)
        self.assertEqual(RecommendationRequest.objects.count(), 1)
        self.register(email="*****@*****.**", verified=False)
        self.login()
        self.assertEqual(Company.objects.count(), 3)

        self.assertEqual(RecommendationRequest.objects.count(), 1)

        trans = Transaction.objects.get_one({})
        self.assertIsNone(trans)
예제 #3
0
    def test_remove_old_recommendations_timeout(self):
        SettingsManager.set_property('rtimeout', 24 * 10)
        r = RecommendationRequest({'requester' : ObjectId(),
                                   'recipient' : ObjectId(),
                                   'message' : 'message',
                                   'requester_email' : '*****@*****.**',
                                   'status' : RecommendationStatusEnum.DECLINED,
                                   'send_date' : timezone.now() - timedelta(days = 1)})
        r.save()

        rr = RecommendationRequest.objects.get_one({'_id' : r._id})
        self.assertIsNotNone(rr)
        self.assertEqual(rr.status, RecommendationStatusEnum.DECLINED)

        task = RemoveOldRecRequestsTask()
        task.execute()

        rr = RecommendationRequest.objects.get_one({'_id' : r._id})
        self.assertIsNotNone(rr)

        SettingsManager.set_property('rtimeout', 1)

        task.execute()

        rr = RecommendationRequest.objects.get_one({'_id' : r._id})
        self.assertIsNone(rr)
예제 #4
0
    def test_register_after_invite_and_verify(self):
        account = Account({"system_id" : Account.FIXED_PROMO_ACCOUNT_ID,
                           "name" : "Счет промо-акцийг",
                           "type" : Account.TYPE_VIRTUAL})
        account.save()

        SettingsManager.set_property('rnes', 1)
        self.register()
        self.login()

        data = {'msg' : 'Come on! Join us now!',
                'email' : '*****@*****.**'}

        notifications = Notification.objects.get({})
        self.assertEqual(len(notifications), 0)

        response = self.client.post('/invites/send/', data)
        self.assertEquals(response.status_code, 200)

        invites = Invite.objects.get({})
        self.assertEqual(len(invites), 1)
        invite = invites[0]
        self.assertEqual(invite.message, 'Come on! Join us now!')
        self.assertEqual(invite.email, '*****@*****.**')

        data = simplejson.loads(response.content)
        self.assertTrue(isinstance(data, dict))
        self.assertIn('success', data)
        self.assertTrue(data['success'])

        self.logout()
        response = self.client.get(u'/invites/join/%s/' % invite.cookie_code)
        self.assertEquals(response.status_code, 302)
        self.assertTrue(self.client.cookies.has_key('invite'))

        self.assertEqual(Company.objects.count(), 1)
        self.assertEqual(RecommendationRequest.objects.count(), 0)
        self.register(email="*****@*****.**", verified=False)
        self.login()
        self.assertEqual(Company.objects.count(), 2)

        invite = Invite.objects.get_one({})
        self.assertEqual(RecommendationRequest.objects.count(), 1)
        self.assertEqual(invite.rec_request, RecommendationRequest.objects.get_one({})._id)

        user = User(User.collection.find_one({'email' : "*****@*****.**"}))
        company = get_user_company(user)
        self.assertEqual(company.account_status, CompanyAccountStatus.VERIFIED)

        trans = Transaction.objects.get_one({})
        self.assertIsNotNone(trans)
        self.assertEqual(trans.state, Transaction.STATE_DONE)
        self.assertEqual(trans.amount.amount, SettingsManager.get_property('invite_bonus'))
        self.assertEqual(trans.source_account, account._id)
        dest_account = Account.objects.get_one({'type' : Account.TYPE_COMPANY,
                                                'details.subject_id' : invite.sender})
        self.assertEqual(trans.dest_account, dest_account._id)
예제 #5
0
    def post(self, request):
        if not hasattr(request, 'company') or not hasattr(request, 'employee'):
            raise Http404()

        bills_count = Invoice.objects.count({
            'expire_date': {
                '$gte': timezone.now()
            },
            'payer': request.company._id,
            'status': InvoiceStatusEnum.CREATED
        })
        if bills_count:
            return HttpResponse(simplejson.dumps({
                'error':
                True,
                'error_message':
                "Такой счет уже существует."
            }),
                                mimetype='application/javascript')

        rekvizitka_bank_account = SettingsManager.get_property(
            'rekvizitka_bank_account')
        bill_data = {
            'payer':
            request.company._id,
            'number':
            u'КЦ-%d' %
            SettingsManager.inc_and_return_property('bill_auto_index'),
            'position':
            u'Верификация в информационной системе',
            'status':
            InvoiceStatusEnum.CREATED,
            'duration_days':
            30,
            'price':
            SettingsManager.get_property('verify_bill_price')
        }
        bill_data.update(rekvizitka_bank_account)
        new_bill = Invoice(bill_data)
        new_bill.save()

        employee = request.employee
        employee_tz = employee.get_tz()
        issued = new_bill.create_date.astimezone(employee_tz)

        return HttpResponse(simplejson.dumps({
            'error': False,
            'bill': {
                'id': unicode(new_bill._id),
                'service_title': bill_data['position'],
                'price': bill_data['price'],
                'status': bill_data['status'],
                'issued': issued.strftime('%d.%m.%Y %H:%M'),
                'number': new_bill.number
            }
        }),
                            mimetype='application/javascript')
예제 #6
0
 def update_int_setting(self, setting_name, string_val, min_value, max_value, errors_dict, data_dict, error_msg = None):
     try:
         val_i = int(string_val)
         if val_i < min_value or val_i > max_value:
             raise Exception()
         if val_i != SettingsManager.get_property(setting_name):
             SettingsManager.set_property(setting_name, val_i)
             data_dict[setting_name] = val_i
     except Exception:
         errors_dict[setting_name] = "Введите целочисленное значение [%d - %d]" % (min_value, max_value) if not error_msg else error_msg
예제 #7
0
    def testAcceptRecAndVerify(self):
        SettingsManager.set_property('rnes', 3)
        self.register()
        requesters = self.register_verification_requesters(self.company, 1)
        requester_company, requester_employee, requester_user, request = requesters[0]

        self.login()
        mail.outbox = []

        response = self.client.post('/recommendations/accept/%s/' % str(request._id))
        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(mail.outbox), 0)
        company_data = Company.objects.collection.find_one({'_id' : requester_company._id}, {'account_status' : 1})
        self.assertEqual(company_data['account_status'], CompanyAccountStatus.JUST_REGISTERED)

        self.logout()
        self.register(email='*****@*****.**')
        request = RecommendationRequest({'requester' : requester_company._id,
                                         'recipient' : self.company._id,
                                         'status' : RecommendationStatusEnum.RECEIVED,
                                         'message' : 'Please recommend me.',
                                         'requester_email' : '*****@*****.**'})
        request.save()

        self.login_as(email='*****@*****.**')

        mail.outbox = []

        response = self.client.post('/recommendations/accept/%s/' % str(request._id))
        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(mail.outbox), 0)
        company_data = Company.objects.collection.find_one({'_id' : requester_company._id}, {'account_status' : 1})
        self.assertEqual(company_data['account_status'], CompanyAccountStatus.JUST_REGISTERED)

        self.logout()
        self.register(email='*****@*****.**')
        request = RecommendationRequest({'requester' : requester_company._id,
                                         'recipient' : self.company._id,
                                         'status' : RecommendationStatusEnum.RECEIVED,
                                         'message' : 'Please recommend me.',
                                         'requester_email' : '*****@*****.**'})
        request.save()

        self.login_as(email='*****@*****.**')

        mail.outbox = []

        response = self.client.post('/recommendations/accept/%s/' % str(request._id))
        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(mail.outbox), 1)
        company_data = Company.objects.collection.find_one({'_id' : requester_company._id}, {'account_status' : 1})
        self.assertEqual(company_data['account_status'], CompanyAccountStatus.VERIFIED)
예제 #8
0
 def get(self, request):
     errors = {}
     data = {'company_auto_index' : SettingsManager.get_property('company_auto_index'),
             'bill_auto_index' : SettingsManager.get_property('bill_auto_index'),
             'verify_bill_price' : SettingsManager.get_property('verify_bill_price'),
             'registration_promo_action_amount' : SettingsManager.get_property('registration_promo_action_amount'),
             'rnes' : SettingsManager.get_property('rnes'),
             'rmax' : SettingsManager.get_property('rmax'),
             'rtimeout' : SettingsManager.get_property('rtimeout'),
             'verifylettercount' : SettingsManager.get_property('verifylettercount'),
             'verifyletterdelaydays' : SettingsManager.get_property('verifyletterdelaydays'),
             'invite_bonus' : SettingsManager.get_property('invite_bonus'),
             'errors' : errors}
     return render_to_response('settings/manage_settings.html', data, context_instance=RequestContext(request))
예제 #9
0
    def testInitialModuleDataAccept(self):
        SettingsManager.set_property('rnes', 3)
        self.register()
        requesters = self.register_verification_requesters(self.company, 3)
        requester_company, requester_employee, requester_user, request = requesters[0]

        self.login()
        mail.outbox = []

        self.assertEqual(RecommendationRequest.objects.count(), 3)

        response = self.client.post('/recommendations/accept/%s/' % str(request._id))
        self.assertEqual(response.status_code, 200)

        data = simplejson.loads(response.content)
        self.assertTrue(isinstance(data, dict))
        self.assertIn('error', data)
        self.assertFalse(data['error'])

        self.assertEqual(len(mail.outbox), 0)

        request_post = RecommendationRequest.objects.get_one({'_id' : request._id})
        self.assertIsNotNone(request_post)
        self.assertEqual(request_post.status, RecommendationStatusEnum.ACCEPTED)
        self.assertEqual(request_post.requester, requester_company._id)
        self.assertEqual(request_post.recipient, self.company._id)
        self.assertEqual(request_post.viewed, False)
        self.assertEqual(request_post.requester_email, requester_user.email)

        self.assertEqual(RecommendationRequest.objects.count(), 3)

        data = RecommendInitialsView.generate_data_obj(self.company, self.company, self.employee)
        self.assertIsNotNone(data)
        self.assertIn('sent_not_accepted_list', data)
        self.assertIn('sent_accepted_list', data)
        self.assertIn('received_accepted', data)
        self.assertIn('received_not_accepted', data)
        self.assertIn('max_req_count_reached', data)

        sent_not_accepted_list = data['sent_not_accepted_list']
        sent_accepted_list = data['sent_accepted_list']
        received_accepted = data['received_accepted']
        received_not_accepted = data['received_not_accepted']
        max_req_count_reached = data['max_req_count_reached']

        self.assertEqual(max_req_count_reached, False)
        self.assertEqual(len(sent_not_accepted_list), 0)
        self.assertEqual(len(sent_accepted_list), 0)
        self.assertEqual(len(received_accepted), 1)
        self.assertEqual(len(received_not_accepted), 2)
예제 #10
0
    def generate_verification_letters(self, email, company_id):
        letters_count = SettingsManager.get_property('verifylettercount')
        interval_days = SettingsManager.get_property('verifyletterdelaydays')
        subject = u"Пройдите верификацию вашей компании в Реквизитке"

        mail_context = {'SITE_DOMAIN_NAME' : settings.SITE_DOMAIN_NAME}

        text = render_to_string('mails/periodic_verify_letter.txt', dictionary=mail_context)
        html = render_to_string('mails/periodic_verify_letter.html', dictionary=mail_context)

        action_id = create_action_id(actions.VERIFICATION_PERIODIC, unicode(company_id))
        for day in xrange(letters_count):
            delay = interval_days * (day + 1) * 60 * 24
            notification_manager.add(action_id, email, subject, text, html, delay)
예제 #11
0
    def execute(self):
        print >> sys.stdout, 'Executing RemoveOldRecRequestsTask'

        query = {
            'status': {'$ne': RecommendationStatusEnum.ACCEPTED},
            'send_date': {'$lte': timezone.now() - timedelta(seconds=SettingsManager.get_property('rtimeout') * 3600)}
        }
        items_to_remove = RecommendationRequest.objects.get(query)
        if not len(items_to_remove):
            return

        requested_companies = {}
        for item in items_to_remove:
            requester = item.requester
            recipient = item.recipient
            if recipient not in requested_companies:
                requested_companies[recipient] = set([requester])
            else:
                requested_companies[recipient].add(requester)

        for requested_company in requested_companies:
            requester_list = requested_companies[requested_company]
            Company.objects.update({'_id' : requested_company},
                                   {'$pullAll' : {'rec_requesters' : list(requester_list)}})

        RecommendationRequest.objects.collection.remove(query)
예제 #12
0
    def execute(self):
        print >> sys.stdout, 'Executing RemoveOldRecRequestsTask'

        query = {
            'status': {
                '$ne': RecommendationStatusEnum.ACCEPTED
            },
            'send_date': {
                '$lte':
                timezone.now() - timedelta(
                    seconds=SettingsManager.get_property('rtimeout') * 3600)
            }
        }
        items_to_remove = RecommendationRequest.objects.get(query)
        if not len(items_to_remove):
            return

        requested_companies = {}
        for item in items_to_remove:
            requester = item.requester
            recipient = item.recipient
            if recipient not in requested_companies:
                requested_companies[recipient] = set([requester])
            else:
                requested_companies[recipient].add(requester)

        for requested_company in requested_companies:
            requester_list = requested_companies[requested_company]
            Company.objects.update(
                {'_id': requested_company},
                {'$pullAll': {
                    'rec_requesters': list(requester_list)
                }})

        RecommendationRequest.objects.collection.remove(query)
예제 #13
0
    def testInitialModuleDataRequest(self):
        SettingsManager.set_property('rnes', 3)
        SettingsManager.set_property('rmax', 3)
        self.register(verified=False)

        self.login()
        mail.outbox = []

        companies = self.register_companies(3)

        response = self.client.post('/recommendations/ask/%(rek_id)s/' % {'rek_id' : companies[0].rek_id}, {'message' : "!"})
        self.assertEqual(response.status_code, 200)
        self.assertEqual(RecommendationRequest.objects.count(), 1)

        response = self.client.post('/recommendations/ask/%(rek_id)s/' % {'rek_id' : companies[1].rek_id}, {'message' : "!"})
        self.assertEqual(response.status_code, 200)
        self.assertEqual(RecommendationRequest.objects.count(), 2)

        response = self.client.post('/recommendations/ask/%(rek_id)s/' % {'rek_id' : companies[2].rek_id}, {'message' : "!"})
        self.assertEqual(response.status_code, 200)
        self.assertEqual(RecommendationRequest.objects.count(), 3)

        RecommendationRequest.objects.update({'_id' : RecommendationRequest.objects.get_one({})._id},
                                             {'$set' : {'status' : RecommendationStatusEnum.ACCEPTED}})


        data = RecommendInitialsView.generate_data_obj(self.company, self.company, self.employee)
        self.assertIsNotNone(data)
        self.assertIn('sent_not_accepted_list', data)
        self.assertIn('sent_accepted_list', data)
        self.assertIn('received_accepted', data)
        self.assertIn('received_not_accepted', data)
        self.assertIn('max_req_count_reached', data)

        sent_not_accepted_list = data['sent_not_accepted_list']
        sent_accepted_list = data['sent_accepted_list']
        received_accepted = data['received_accepted']
        received_not_accepted = data['received_not_accepted']
        max_req_count_reached = data['max_req_count_reached']

        self.assertEqual(max_req_count_reached, True)
        self.assertEqual(len(sent_not_accepted_list), 2)
        self.assertEqual(len(sent_accepted_list), 1)
        self.assertEqual(len(received_accepted), 0)
        self.assertEqual(len(received_not_accepted), 0)
예제 #14
0
    def test_register_after_invite(self):
        SettingsManager.set_property('rnes', 3)
        self.register()
        self.login()

        data = {'msg': 'Come on! Join us now!', 'email': '*****@*****.**'}

        notifications = Notification.objects.get({})
        self.assertEqual(len(notifications), 0)

        response = self.client.post('/invites/send/', data)
        self.assertEquals(response.status_code, 200)

        invites = Invite.objects.get({})
        self.assertEqual(len(invites), 1)
        invite = invites[0]
        self.assertEqual(invite.message, 'Come on! Join us now!')
        self.assertEqual(invite.email, '*****@*****.**')

        data = simplejson.loads(response.content)
        self.assertTrue(isinstance(data, dict))
        self.assertIn('success', data)
        self.assertTrue(data['success'])

        self.logout()
        response = self.client.get(u'/invites/join/%s/' % invite.cookie_code)
        self.assertEquals(response.status_code, 302)
        self.assertTrue(self.client.cookies.has_key('invite'))

        self.assertEqual(Company.objects.count(), 1)
        self.assertEqual(RecommendationRequest.objects.count(), 0)
        self.register(email="*****@*****.**", verified=False)
        self.login()
        self.assertEqual(Company.objects.count(), 2)

        invite = Invite.objects.get_one({})
        self.assertEqual(RecommendationRequest.objects.count(), 1)
        self.assertEqual(invite.rec_request,
                         RecommendationRequest.objects.get_one({})._id)

        user = User(
            User.collection.find_one({'email': "*****@*****.**"}))
        company = get_user_company(user)
        self.assertEqual(company.account_status,
                         CompanyAccountStatus.JUST_REGISTERED)
예제 #15
0
    def testRequestMaxNumOfRecs(self):
        SettingsManager.set_property('rnes', 3)
        SettingsManager.set_property('rmax', 3)
        message = "Could you please recommend me."
        self.register(verified=False)
        self.login()
        companies = self.register_companies(6)

        for x in xrange(3):
            company = companies[x]
            response = self.client.post('/recommendations/ask/%(rek_id)s/' % {'rek_id' : company.rek_id}, {'message' : message})
            self.assertEqual(response.status_code, 200)
            self.assertEqual(RecommendationRequest.objects.count(), x + 1)

        company = companies[-1]
        response = self.client.post('/recommendations/ask/%(rek_id)s/' % {'rek_id' : company.rek_id}, {'message' : message})
        self.assertEqual(response.status_code, 403)
        self.assertEqual(RecommendationRequest.objects.count(), 3)
예제 #16
0
    def generate_verification_letters(self, email, company_id):
        letters_count = SettingsManager.get_property('verifylettercount')
        interval_days = SettingsManager.get_property('verifyletterdelaydays')
        subject = u"Пройдите верификацию вашей компании в Реквизитке"

        mail_context = {'SITE_DOMAIN_NAME': settings.SITE_DOMAIN_NAME}

        text = render_to_string('mails/periodic_verify_letter.txt',
                                dictionary=mail_context)
        html = render_to_string('mails/periodic_verify_letter.html',
                                dictionary=mail_context)

        action_id = create_action_id(actions.VERIFICATION_PERIODIC,
                                     unicode(company_id))
        for day in xrange(letters_count):
            delay = interval_days * (day + 1) * 60 * 24
            notification_manager.add(action_id, email, subject, text, html,
                                     delay)
예제 #17
0
    def test_remove_old_recommendations_not_old(self):
        SettingsManager.set_property('rtimeout', 1)
        r = RecommendationRequest({'requester' : ObjectId(),
                                   'recipient' : ObjectId(),
                                   'message' : 'message',
                                   'requester_email' : '*****@*****.**'})
        r.save()

        rr = RecommendationRequest.objects.get_one({'_id' : r._id})
        self.assertIsNotNone(rr)
        self.assertEqual(rr.status, RecommendationStatusEnum.RECEIVED)

        task = RemoveOldRecRequestsTask()
        task.execute()

        rr = RecommendationRequest.objects.get_one({'_id' : r._id})
        self.assertIsNotNone(rr)
        self.assertEqual(rr.status, RecommendationStatusEnum.RECEIVED)
예제 #18
0
 def testPlaceABill(self):
     self.register(verified=False)
     self.login()
     response = self.client.get('/verification/place_bill/')
     self.assertEqual(response.status_code, 405)
     response = self.client.post('/verification/place_bill/')
     self.assertEqual(response.status_code, 200)
     self.assertEqual(self.collections['bill_items'].count(), 1)
     bill = self.collections['bill_items'].find_one()
     self.assertIsNotNone(bill)
     self.assertIn('_id', bill)
     self.assertEqual(bill['price'], SettingsManager.get_property('verify_bill_price'))
예제 #19
0
    def post(self, request):
        if not hasattr(request, 'company') or not hasattr(request, 'employee'):
            raise Http404()

        bills_count = Invoice.objects.count({'expire_date' : {'$gte' : timezone.now()},
                                             'payer' : request.company._id,
                                             'status' : InvoiceStatusEnum.CREATED})
        if bills_count:
            return HttpResponse(simplejson.dumps({'error' : True,
                                                  'error_message' : "Такой счет уже существует."}),
                                                  mimetype='application/javascript')

        rekvizitka_bank_account = SettingsManager.get_property('rekvizitka_bank_account')
        bill_data = {
            'payer' : request.company._id,
            'number' : u'КЦ-%d' % SettingsManager.inc_and_return_property('bill_auto_index'),
            'position' : u'Верификация в информационной системе',
            'status' : InvoiceStatusEnum.CREATED,
            'duration_days':30,
            'price' : SettingsManager.get_property('verify_bill_price')
        }
        bill_data.update(rekvizitka_bank_account)
        new_bill = Invoice(bill_data)
        new_bill.save()

        employee = request.employee
        employee_tz = employee.get_tz()
        issued = new_bill.create_date.astimezone(employee_tz)

        return HttpResponse(simplejson.dumps({'error' : False,
                                              'bill' : {'id' : unicode(new_bill._id),
                                                        'service_title' : bill_data['position'],
                                                        'price' : bill_data['price'],
                                                        'status' : bill_data['status'],
                                                        'issued' : issued.strftime('%d.%m.%Y %H:%M'),
                                                        'number' : new_bill.number}}),
                            mimetype='application/javascript')
예제 #20
0
    def testPlaceSecondBill(self):
        self.register(verified=False)
        self.login()
        response = self.client.post('/verification/place_bill/')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(self.collections['bill_items'].count(), 1)
        bill = self.collections['bill_items'].find_one()
        self.assertIsNotNone(bill)
        self.assertIn('_id', bill)
        self.assertEqual(bill['price'], SettingsManager.get_property('verify_bill_price'))

        response = self.client.post('/verification/place_bill/')
        self.assertEqual(response.status_code, 200)
        data = simplejson.loads(response.content)
        self.assertTrue(isinstance(data, dict))
        self.assertIn('error', data)
        self.assertTrue(data['error'])
예제 #21
0
    def can_ask_recommendation(self, company_to_ask, result_dict = None):
        result_dict = result_dict or {}

        if not self.user.is_authenticated():
            result_dict['unauthorized'] = True
            return False

        user_company = self.company
        if not user_company or not self.employee:
            result_dict['not_verified'] = True
            return False

        recommendations_count = RecommendationRequest.objects.count({'requester' : user_company._id})
        if not self.company.is_verified() and recommendations_count >= SettingsManager.get_property('rmax'):
            result_dict['max_reached'] = True
            return False

        return True
예제 #22
0
    def can_ask_recommendation(self, company_to_ask, result_dict=None):
        result_dict = result_dict or {}

        if not self.user.is_authenticated():
            result_dict['unauthorized'] = True
            return False

        user_company = self.company
        if not user_company or not self.employee:
            result_dict['not_verified'] = True
            return False

        recommendations_count = RecommendationRequest.objects.count(
            {'requester': user_company._id})
        if not self.company.is_verified(
        ) and recommendations_count >= SettingsManager.get_property('rmax'):
            result_dict['max_reached'] = True
            return False

        return True
예제 #23
0
    def post(self, request, recommendation_id):
        # mustdo: add transaction
        company = request.company
        try:
            recommendation_id_obj = bson.ObjectId(recommendation_id)
        except Exception:
            return HttpResponse(simplejson.dumps({'error' : True,
                                                  'error_message' : "Запрос не найден."}),
                mimetype='application/javascript')

        recommendation = RecommendationRequest.objects.get_one({'_id' : recommendation_id_obj,
                                                                'recipient' : company._id,
                                                                'status' : RecommendationStatusEnum.RECEIVED})

        if not recommendation:
            return HttpResponse(simplejson.dumps({'error' : True,
                                                  'error_message' : "Запрос не найден."}),
                                                   mimetype='application/javascript')

        RecommendationRequest.objects.update({'_id' : recommendation_id_obj},
                                             {'$set' : {'status' : RecommendationStatusEnum.ACCEPTED}})

        company_to_recommend = recommendation.requester
        Company.objects.update({'_id' : recommendation.recipient}, {'$pull' : {'rec_requesters' : company_to_recommend}})
        accepted_requests_count = RecommendationRequest.objects.count({'status' : RecommendationStatusEnum.ACCEPTED,
                                                                       'requester' : company_to_recommend})
        if accepted_requests_count >= SettingsManager.get_property('rnes'):
            requester_company = Company.objects.get_one({'_id' : company_to_recommend})
            if requester_company.account_status == CompanyAccountStatus.JUST_REGISTERED:
                Company.objects.update({'_id' : company_to_recommend},
                                       {'$set' : {'account_status' : CompanyAccountStatus.VERIFIED}})
                notification_manager.remove(create_action_id(actions.VERIFICATION_PERIODIC, unicode(company_to_recommend)))

                self.send_accepted_message(recommendation.requester_email, company.brand_name)

        return HttpResponse(simplejson.dumps({'error' : False,
                                              'success_message' : "Рекомендация подтверждена."}),
                                               mimetype='application/javascript')
예제 #24
0
    def post(self, request, code):
        try:
            rec_message = request.POST['message']
        except Exception:
            return HttpResponseBadRequest("No message field")

        company_to_ask = Company.get_active_company_by_rek_id(code)
        if not company_to_ask:
            return HttpResponseNotFound("Company with rec id %s can not be found." % code)
        my_company = request.company
        employee = request.employee

        check = CompanyPermission(request.user, employee, my_company)
        result_dict = {}
        if not check.can_ask_recommendation(company_to_ask, result_dict):
            if len(result_dict):
                result_dict['error'] = True
                return HttpResponse(simplejson.dumps(result_dict), mimetype='application/javascript')
            return HttpResponseForbidden("Can't ask for a recommendation")

        rec = RecommendationRequest({'requester' : my_company._id,
                                     'recipient' : company_to_ask._id,
                                     'message' : rec_message,
                                     'requester_email' : request.user.email})
        rec.save()
        if my_company._id not in company_to_ask.rec_requesters:
            company_to_ask.rec_requesters.append(my_company._id)
            Company.objects.collection.update({'_id' : company_to_ask._id}, {'$push' : {'rec_requesters' : my_company._id} })

        admin_user, admin_employee = company_to_ask.get_admin_user()

        requester_brand_name = my_company.brand_name
        recipient_rek_id = code
        self.send_rec_message(admin_user.email, rec_message, rec._id, recipient_rek_id, requester_brand_name)

        return HttpResponse(simplejson.dumps({'success' : True,
                                              'max_req_count_reached' : RecommendationRequest.objects.count({'requester' : my_company._id}) >= SettingsManager.get_property('rmax')        }),
                                               mimetype='application/javascript')
예제 #25
0
    def generate_data_obj(cls, company, my_company, employee = None):
        own = False
        if my_company and company.rek_id == my_company.rek_id:
            own = True

        if not own and not company.is_active():
            return {}

        data = {"categoryText" : company.category_text or "",
                "brandName" : company.brand_name,
                "rek_id" : company.rek_id,
                "own" : own,
                "verify_rec_number" : SettingsManager.get_property("rnes"),
                "company_logo" : company.get_logo_url(),
                "authorized" : my_company is not None,
                "verified" : CompanyAccountStatus.is_active_account(company.account_status),
                "employee_id" : unicode(employee) if employee else u""}

        company_id = company._id
        if own:
            invoice = Invoice.objects.get_one({'expire_date' : {'$gte' : timezone.now()},
                                               'payer' : my_company._id,
                                               'status' : InvoiceStatusEnum.CREATED})
            if invoice:
                employee_tz = utc
                issued = invoice.create_date.astimezone(employee_tz)
                data['bill'] = {'id' : unicode(invoice._id),
                                 'service_title' : invoice.position,
                                 'price' : invoice.price,
                                 'status' : invoice.status,
                                 'issued' : issued.strftime('%d.%m.%Y %H:%M'),
                                 'number' : invoice.number}

        corresponding_rec_reqs = RecommendationRequest.objects.get({'$or' : [{'requester' : company_id},
                                                                             {'recipient' : company_id}]})

        sent_not_accepted_list = []
        sent_accepted_list = []
        received_accepted = []
        received_not_accepted = []

        max_req_count = 0

        for rec in corresponding_rec_reqs:
            if rec.requester == company_id:
                acceptor = Company.objects.get_one({'_id' : rec.recipient})
                max_req_count += 1
                if acceptor:
                    if rec.status == RecommendationStatusEnum.RECEIVED:
                        sent_not_accepted_list.append({
                            'rek_id' : acceptor.rek_id,
                            'brand_name' : acceptor.brand_name
                        })
                    elif rec.status == RecommendationStatusEnum.ACCEPTED:
                        sent_accepted_list.append({
                            'rek_id' : acceptor.rek_id,
                            'brand_name' : acceptor.brand_name,
                            'logo' : acceptor.get_some_logo_url(kind='list_logo'),
                            'kind_of_activity' : acceptor.category_text
                        })
            elif rec.recipient == company_id:
                sender = Company.objects.get_one({'_id' : rec.requester})
                if sender:
                    if rec.status == RecommendationStatusEnum.ACCEPTED:
                        received_accepted.append({'rek_id' : sender.rek_id,
                                                  'brand_name' : sender.brand_name})
                    elif rec.status == RecommendationStatusEnum.RECEIVED:
                        received_not_accepted.append({
                            'rek_id' : sender.rek_id,
                            'brand_name' : sender.brand_name,
                            'logo' : sender.get_some_logo_url(kind='list_logo'),
                            'kind_of_activity' : sender.category_text,
                            'request_id' : unicode(rec._id),
                            'msg' : rec.message
                        })

        max_req_count_reached = max_req_count >= SettingsManager.get_property('rmax')

        data.update({'sent_accepted_list' : sent_accepted_list,
                     'received_accepted' : received_accepted})

        if own:
            data.update({'sent_not_accepted_list' : sent_not_accepted_list,
                         'received_not_accepted' : received_not_accepted,
                         'max_req_count_reached' : max_req_count_reached})

        if own:
            my_company_id = my_company._id
            sent_invites_obj_list = Invite.objects.get({'sender' : my_company_id})
            sent_invites_not_used = []
            sent_invites_used = []
            for invite_obj in sent_invites_obj_list:
                if invite_obj.rec_request:
                    invited_rec = RecommendationRequest.objects.get_one({'_id' : invite_obj.rec_request})
                    if not invited_rec:
                        continue
                    invited_company = Company.objects.get_one({'_id' : invited_rec.requester})
                    if not invited_company:
                        continue
                    sent_invites_used.append({
                        'brand_name' : invited_company.brand_name,
                        'rek_id' : invited_company.rek_id
                    })
                else:
                    sent_invites_not_used.append({
                        'email' : invite_obj.email,
                        'date' : invite_obj.created.strftime('%d.%m.%Y')
                    })

            data.update({'sent_invites' : sent_invites_not_used,
                         'sent_registered_invites' : sent_invites_used})
        return data
예제 #26
0
    def post(self, request):
        if 'save_settings' not in request.POST:
            return HttpResponseBadRequest()
        errors = {}
        data = {'company_auto_index' : SettingsManager.get_property('company_auto_index'),
                'bill_auto_index' : SettingsManager.get_property('bill_auto_index'),
                'verify_bill_price' : SettingsManager.get_property('verify_bill_price'),
                'registration_promo_action_amount' : SettingsManager.get_property('registration_promo_action_amount'),
                'rnes' : SettingsManager.get_property('rnes'),
                'rmax' : SettingsManager.get_property('rmax'),
                'rtimeout' : SettingsManager.get_property('rtimeout'),
                'verifylettercount' : SettingsManager.get_property('verifylettercount'),
                'verifyletterdelaydays' : SettingsManager.get_property('verifyletterdelaydays'),
                'invite_bonus' : SettingsManager.get_property('invite_bonus'),
                'errors' : errors}

        verify_bill_price = request.POST.get('verify_bill_price').strip()
        registration_promo_action_amount = request.POST.get('registration_promo_action_amount').strip()

        if len(verify_bill_price):
            try:
                verify_bill_price_int = int(verify_bill_price)
                if verify_bill_price_int <= 0 or verify_bill_price_int > 1000000:
                    raise Exception()
                if verify_bill_price_int != data['verify_bill_price']:
                    SettingsManager.set_property('verify_bill_price', verify_bill_price_int)
                    data['verify_bill_price'] = verify_bill_price_int
            except ValueError:
                errors['verify_bill_price'] = "Введите корректную сумму"

        if len(registration_promo_action_amount):
            try:
                registration_promo_action_amount_int = int(registration_promo_action_amount)
                if registration_promo_action_amount_int <= 0 or registration_promo_action_amount_int > 1000000:
                    raise Exception()
                if registration_promo_action_amount_int != data['registration_promo_action_amount']:
                    SettingsManager.set_property('registration_promo_action_amount', registration_promo_action_amount_int)
                    data['registration_promo_action_amount'] = registration_promo_action_amount_int
            except ValueError:
                errors['registration_promo_action_amount'] = "Введите корректную сумму"

        rnes = request.POST.get('rnes', '').strip()
        rmax = request.POST.get('rmax', '').strip()
        rtimeout = request.POST.get('rtimeout', '').strip()
        verifylettercount = request.POST.get('verifylettercount', '').strip()
        verifyletterdelaydays = request.POST.get('verifyletterdelaydays', '').strip()
        invite_bonus = request.POST.get('invite_bonus', '').strip()

        self.update_int_setting('rnes', rnes, 1, 100, errors, data)
        self.update_int_setting('rmax', rmax, 1, 100, errors, data)
        self.update_int_setting('rtimeout', rtimeout, 1, 24 * 365, errors, data)

        self.update_int_setting('verifylettercount', verifylettercount, 0, 100, errors, data)
        self.update_int_setting('verifyletterdelaydays', verifyletterdelaydays, 1, 366, errors, data)
        self.update_int_setting('invite_bonus', invite_bonus, 0, 3000, errors, data)

        if not len(errors):
            return HttpResponseRedirect(request.path)

        return render_to_response('settings/manage_settings.html', data, context_instance=RequestContext(request))
예제 #27
0
    def test_register_after_invite_and_verify(self):
        account = Account({
            "system_id": Account.FIXED_PROMO_ACCOUNT_ID,
            "name": "Счет промо-акцийг",
            "type": Account.TYPE_VIRTUAL
        })
        account.save()

        SettingsManager.set_property('rnes', 1)
        self.register()
        self.login()

        data = {'msg': 'Come on! Join us now!', 'email': '*****@*****.**'}

        notifications = Notification.objects.get({})
        self.assertEqual(len(notifications), 0)

        response = self.client.post('/invites/send/', data)
        self.assertEquals(response.status_code, 200)

        invites = Invite.objects.get({})
        self.assertEqual(len(invites), 1)
        invite = invites[0]
        self.assertEqual(invite.message, 'Come on! Join us now!')
        self.assertEqual(invite.email, '*****@*****.**')

        data = simplejson.loads(response.content)
        self.assertTrue(isinstance(data, dict))
        self.assertIn('success', data)
        self.assertTrue(data['success'])

        self.logout()
        response = self.client.get(u'/invites/join/%s/' % invite.cookie_code)
        self.assertEquals(response.status_code, 302)
        self.assertTrue(self.client.cookies.has_key('invite'))

        self.assertEqual(Company.objects.count(), 1)
        self.assertEqual(RecommendationRequest.objects.count(), 0)
        self.register(email="*****@*****.**", verified=False)
        self.login()
        self.assertEqual(Company.objects.count(), 2)

        invite = Invite.objects.get_one({})
        self.assertEqual(RecommendationRequest.objects.count(), 1)
        self.assertEqual(invite.rec_request,
                         RecommendationRequest.objects.get_one({})._id)

        user = User(
            User.collection.find_one({'email': "*****@*****.**"}))
        company = get_user_company(user)
        self.assertEqual(company.account_status, CompanyAccountStatus.VERIFIED)

        trans = Transaction.objects.get_one({})
        self.assertIsNotNone(trans)
        self.assertEqual(trans.state, Transaction.STATE_DONE)
        self.assertEqual(trans.amount.amount,
                         SettingsManager.get_property('invite_bonus'))
        self.assertEqual(trans.source_account, account._id)
        dest_account = Account.objects.get_one({
            'type':
            Account.TYPE_COMPANY,
            'details.subject_id':
            invite.sender
        })
        self.assertEqual(trans.dest_account, dest_account._id)
예제 #28
0
 def setUp(self):
     super(InvitesTestCase, self).setUp()
     SettingsManager.set_property('verifylettercount', 0)
예제 #29
0
def generate_rek_id():
    if settings.TEST_RUN:
        return 'CK1'
    return integer_to_code(
        SettingsManager.inc_and_return_property('company_auto_index'))
예제 #30
0
 def setUp(self):
     super(InvitesRecsTestCase, self).setUp()
     SettingsManager.set_property('verifylettercount', 0)
예제 #31
0
def generate_rek_id():
    if settings.TEST_RUN:
        return 'CK1'
    return integer_to_code(SettingsManager.inc_and_return_property('company_auto_index'))
예제 #32
0
def create_new_account(email, password, brand_name, promo_code = None, invite_cookie = None):
    # mustdo: add "transaction"
    created_user = User.create_user(email, password)
    if not created_user:
        raise Exception('failed to create user')

    activation_link = UserActivationLinks({'user' : created_user._id})
    activation_link.save()

    new_employee = CompanyEmployee({'user_id':created_user._id, 'timezone' : 'Europe/Moscow'})
    new_employee.save()

    new_company = Company({'rek_id':generate_rek_id(),
                           'owner_employee_id':new_employee._id,
                           'brand_name' : brand_name})
    new_company.save()

    new_billing_account = Account({'type' : Account.TYPE_COMPANY,
                                   'name' : "Счет компании",
                                   'details' : {'subject_id' : new_company._id}})
    new_billing_account.save()

    if promo_code:
        promo_code.use(new_company._id)
        promo_account = Account.objects.get_one({'system_id' : Account.FIXED_PROMO_ACCOUNT_ID})
        transaction = Transaction({'source' : promo_account._id,
                                   'dest' : new_billing_account._id,
                                   'amount' : Currency.russian_roubles(SettingsManager.get_property("registration_promo_action_amount")),
                                   'comment' : u"Бонус при регистрации компании по промо-коду %s" % unicode(promo_code.code)})
        transaction.save()
        transaction.apply()

    new_employee.set(company_id=new_company._id)

    if invite_cookie and len(invite_cookie):
        invite = Invite.objects.get_one({'cookie_code' : invite_cookie})
        if invite:
            rec_request = RecommendationRequest({'requester' : new_company._id,
                                                 'recipient' : invite.sender,
                                                 'status' : RecommendationStatusEnum.ACCEPTED,
                                                 'message' : u'Регистрация по приглашению: %s' % invite.message,
                                                 'viewed' : True,
                                                 'requester_email' : '*****@*****.**'})
            rec_request.save()
            invite.rec_request = rec_request._id
            invite.save()
            if SettingsManager.get_property('rnes') < 2:
                new_company.objects.update({'_id' : new_company._id}, {'$set' : {'account_status' : CompanyAccountStatus.VERIFIED}})
                new_company.account_status = CompanyAccountStatus.VERIFIED

                dest_account = Account.objects.get_one({'type' : Account.TYPE_COMPANY,
                                                        'details.subject_id' : invite.sender})

                if dest_account:
                    promo_account = Account.objects.get_one({'system_id' : Account.FIXED_PROMO_ACCOUNT_ID})
                    if promo_account:
                        new_trans = Transaction({'source' : promo_account._id,
                                                 'dest' : dest_account._id,
                                                 'amount' : Currency.russian_roubles(SettingsManager.get_property('invite_bonus')),
                                                 'comment' : u'Бонус за приглашение компании "%s" (%s)' % (brand_name, new_company.rek_id)})
                        new_trans.save()
                        new_trans.apply()
    return created_user, password, new_company, activation_link
예제 #33
0
def create_new_account(email,
                       password,
                       brand_name,
                       promo_code=None,
                       invite_cookie=None):
    # mustdo: add "transaction"
    created_user = User.create_user(email, password)
    if not created_user:
        raise Exception('failed to create user')

    activation_link = UserActivationLinks({'user': created_user._id})
    activation_link.save()

    new_employee = CompanyEmployee({
        'user_id': created_user._id,
        'timezone': 'Europe/Moscow'
    })
    new_employee.save()

    new_company = Company({
        'rek_id': generate_rek_id(),
        'owner_employee_id': new_employee._id,
        'brand_name': brand_name
    })
    new_company.save()

    new_billing_account = Account({
        'type': Account.TYPE_COMPANY,
        'name': "Счет компании",
        'details': {
            'subject_id': new_company._id
        }
    })
    new_billing_account.save()

    if promo_code:
        promo_code.use(new_company._id)
        promo_account = Account.objects.get_one(
            {'system_id': Account.FIXED_PROMO_ACCOUNT_ID})
        transaction = Transaction({
            'source':
            promo_account._id,
            'dest':
            new_billing_account._id,
            'amount':
            Currency.russian_roubles(
                SettingsManager.get_property(
                    "registration_promo_action_amount")),
            'comment':
            u"Бонус при регистрации компании по промо-коду %s" %
            unicode(promo_code.code)
        })
        transaction.save()
        transaction.apply()

    new_employee.set(company_id=new_company._id)

    if invite_cookie and len(invite_cookie):
        invite = Invite.objects.get_one({'cookie_code': invite_cookie})
        if invite:
            rec_request = RecommendationRequest({
                'requester':
                new_company._id,
                'recipient':
                invite.sender,
                'status':
                RecommendationStatusEnum.ACCEPTED,
                'message':
                u'Регистрация по приглашению: %s' % invite.message,
                'viewed':
                True,
                'requester_email':
                '*****@*****.**'
            })
            rec_request.save()
            invite.rec_request = rec_request._id
            invite.save()
            if SettingsManager.get_property('rnes') < 2:
                new_company.objects.update({'_id': new_company._id}, {
                    '$set': {
                        'account_status': CompanyAccountStatus.VERIFIED
                    }
                })
                new_company.account_status = CompanyAccountStatus.VERIFIED

                dest_account = Account.objects.get_one({
                    'type':
                    Account.TYPE_COMPANY,
                    'details.subject_id':
                    invite.sender
                })

                if dest_account:
                    promo_account = Account.objects.get_one(
                        {'system_id': Account.FIXED_PROMO_ACCOUNT_ID})
                    if promo_account:
                        new_trans = Transaction({
                            'source':
                            promo_account._id,
                            'dest':
                            dest_account._id,
                            'amount':
                            Currency.russian_roubles(
                                SettingsManager.get_property('invite_bonus')),
                            'comment':
                            u'Бонус за приглашение компании "%s" (%s)' %
                            (brand_name, new_company.rek_id)
                        })
                        new_trans.save()
                        new_trans.apply()
    return created_user, password, new_company, activation_link