def __init__(self, kwargs): kwargs = kwargs or {} self._id = kwargs.get('_id') self.code = kwargs.get('code', self.INVALID_CODE_VALUE) self.promotion_id = kwargs.get('promotion_id') self.company_id = kwargs.get('company_id') self.used_date = kwargs.get('used_date') self.price = kwargs.get('price', Currency.russian_roubles(0)) if self.price and not isinstance(self.price, Currency): self.price = Currency(self.price)
def test_create_registration_promotion(self): self.assertLessEqual(Promotion.objects.count(), 0) self.assertLessEqual(RegistrationPromoCode.objects.count(), 0) create_reg_promotion(timezone.now(), 30, "test promo", Currency.russian_roubles(1000), 20) self.assertEqual(Promotion.objects.count(), 1) self.assertEqual(RegistrationPromoCode.objects.count(), 20)
def test_register_with_promo(self): call_command("init_billing_accounts") promotion = Promotion({'count' : 1, 'start_date' : timezone.now() - timedelta(days=1), 'expires_date' : timezone.now() + timedelta(days=1)}) promotion.save() promo_code = RegistrationPromoCode({'code' : 12345678, 'promotion_id' : promotion._id, 'price' : Currency.russian_roubles(100)}) promo_code.save() self.assertEqual(len(mail.outbox), 0) response = self.client.post('/', { 'email' : '*****@*****.**', 'brand_name' : 'Company brand name', 'password' : 'aaabbb', 'promo_code_part1' : unicode(promo_code.code)[:4], 'promo_code_part2' : unicode(promo_code.code)[4:], 'join' : 'join' }) self.assertEqual(response.status_code, 200) company = Company.objects.get({})[0] self.assertEqual(len(mail.outbox), 2) self.assertEqual(len(RegistrationPromoCode.objects.get({'company_id' : company._id})), 1) code = RegistrationPromoCode.objects.get({'company_id' : company._id})[0] self.assertIsNotNone(code) self.assertTrue(code.used) self.assertRaises(KeyError, response.context.__getitem__, 'promo_code_error')
def test_register_with_not_active_promo(self): call_command("init_billing_accounts") promotion = Promotion({ 'count': 1, 'start_date': timezone.now() - timedelta(days=1), 'expires_date': timezone.now() - timedelta(days=1) }) promotion.save() promo_code = RegistrationPromoCode({ 'code': 12345678, 'promotion_id': promotion._id, 'price': Currency.russian_roubles(100) }) promo_code.save() response = self.client.post( '/', { 'email': '*****@*****.**', 'brand_name': 'Company brand name', 'password': '******', 'promo_code_part1': unicode(promo_code.code)[:4], 'promo_code_part2': unicode(promo_code.code)[4:], 'join': 'join' }) self.assertEqual(response.status_code, 200) self.assertIn('promo_code_error', response.context) self.assertEqual(response.context['promo_code_error'], True)
def test_use_reg_promo(self): self.register() create_reg_promotion(timezone.now(), 30, "test promo", Currency.russian_roubles(1000), 1) code = RegistrationPromoCode.objects.get({})[0] self.assertIsNotNone(code) company = Company.objects.get({})[0] code.use(company._id)
def post(self, request): errors = {} if not request.POST.has_key('add_promo_action'): return HttpResponseBadRequest("Do not know what to do.") comment = request.POST.get('comment', '').strip() start_date = request.POST.get('start_date', '').strip() duration = request.POST.get('duration', '').strip() amount = request.POST.get('amount', '').strip() count = request.POST.get('count', '').strip() start_date_obj = None duration_int = 0 amount_dec = Decimal(0) count_int = 0 if not len(comment): errors['comment'] = 'Поле не может быть пустым' try: start_date_obj = datetime.strptime(start_date, '%d-%m-%Y') except Exception: errors['start_date'] = 'Некорректная дата' try: duration_int = int(duration) if duration_int <= 0: raise ValueError() except ValueError: errors['duration'] = 'Введите число > 0' try: count_int = int(count) if count_int <= 0 or count_int > 100000000: raise ValueError() except ValueError: errors['count'] = 'Введите число > 0' try: amount_dec = Decimal(amount) if amount_dec <= Decimal(0) or amount_dec > Decimal(1000000000): raise Exception() except Exception: errors['amount'] = 'Введите сумму в рублях.копейках (напр. 1000 или 10.22)' if not len(errors): create_reg_promotion(start_date_obj, duration_int, comment, Currency.russian_roubles(amount_dec), count_int) return HttpResponseRedirect('/ads/view_promo_actions/') return render_to_response('ads/add_promo_action.html', {'errors' : errors, 'comment' : comment, 'start_date' : start_date, 'duration' : duration, 'amount' : amount, 'count' : count}, context_instance=RequestContext(request))
def test_register_with_used_promo(self): call_command("init_billing_accounts") promotion = Promotion({ 'count': 1, 'start_date': timezone.now() - timedelta(days=1), 'expires_date': timezone.now() + timedelta(days=1) }) promotion.save() promo_code = RegistrationPromoCode({ 'code': 12345678, 'promotion_id': promotion._id, 'price': Currency.russian_roubles(100) }) promo_code.save() response = self.client.post( '/', { 'email': '*****@*****.**', 'brand_name': 'Company brand name', 'password': '******', 'promo_code_part1': unicode(promo_code.code)[:4], 'promo_code_part2': unicode(promo_code.code)[4:], 'join': 'join' }) self.assertEqual(response.status_code, 200) self.assertRaises(KeyError, response.context.__getitem__, 'promo_code_error') company = Company.objects.get({})[0] self.assertEqual( len(RegistrationPromoCode.objects.get({'company_id': company._id})), 1) code = RegistrationPromoCode.objects.get({'company_id': company._id})[0] self.assertIsNotNone(code) self.assertTrue(code.used) response = self.client.post( '/', { 'email': '*****@*****.**', 'brand_name': 'Company brand name2', 'password': '******', 'promo_code_part1': unicode(promo_code.code)[:4], 'promo_code_part2': unicode(promo_code.code)[4:], 'join': 'join' }) self.assertEqual(response.status_code, 200) self.assertLessEqual(len(Company.objects.get({})), 1) self.assertEqual(response.context['promo_code_error'], True)
def set_paid(invoice, payment_order_number, payment_order_date, payment_order_comment): if not payment_order_number or not len( payment_order_number ) or not payment_order_date or not payment_order_comment or not len( payment_order_comment): raise Exception('Insufficient data to process payment') if invoice.status != InvoiceStatusEnum.CREATED: raise Exception('Incorrect invoice status') company = Company.objects.get_one({'_id': invoice.payer}) if not company: raise Exception("Can't find payer company with id %s" % unicode(invoice.payer)) company_account = Account.objects.get_one({ 'type': Account.TYPE_COMPANY, 'details.subject_id': company._id }) if not company_account: raise Exception('Failed to find payer company account') bank_account = Account.objects.get_one( {'system_id': Account.FIXED_BANK_ACCOUNT_ID}) if not bank_account: raise Exception('Failed to find bank system account') # todo: wrap with transaction tr = Transaction({ 'source': bank_account._id, 'dest': company_account._id, 'amount': Currency.russian_roubles(invoice.price), 'comment': u"%s Банковский перевод. Платежка N %s от %s." % (payment_order_comment, unicode(payment_order_number), payment_order_date.strftime('%d-%m-%Y')) }) tr.save() tr.apply() invoice.status = InvoiceStatusEnum.PAID invoice.objects.update({'_id': invoice._id}, {'$set': { 'status': invoice.status }})
def test_register_with_not_active_promo(self): call_command("init_billing_accounts") promotion = Promotion({'count' : 1, 'start_date' : timezone.now() - timedelta(days=1), 'expires_date' : timezone.now() - timedelta(days=1)}) promotion.save() promo_code = RegistrationPromoCode({'code' : 12345678, 'promotion_id' : promotion._id, 'price' : Currency.russian_roubles(100)}) promo_code.save() response = self.client.post('/', { 'email' : '*****@*****.**', 'brand_name' : 'Company brand name', 'password' : 'aaabbb', 'promo_code_part1' : unicode(promo_code.code)[:4], 'promo_code_part2' : unicode(promo_code.code)[4:], 'join' : 'join' }) self.assertEqual(response.status_code, 200) self.assertIn('promo_code_error', response.context) self.assertEqual(response.context['promo_code_error'], True)
def post(self, request): errors = {} amount_data_dec = None data = {'errors': errors} company_rek_id = request.POST.get('company_rek_id', '').strip() amount = request.POST.get('amount', '').strip() comment = request.POST.get('comment', '').strip() if not len(amount): errors['amount'] = 'Введите корректную сумму' else: try: amount_data_dec = Decimal(amount) amount_data = Currency.russian_roubles(amount_data_dec) except Exception: errors['amount'] = 'Введите корректную сумму' if not len(comment): errors['comment'] = 'Поле не может быть пустым' company = None if not len(company_rek_id): errors['company_rek_id'] = 'Введите корректный rek-номер компании' else: company = Company.objects.get_one({'rek_id': company_rek_id}) if not company: errors['company_rek_id'] = u'Не удалось найти компанию' if not len(errors) and company: #noinspection PyUnboundLocalVariable company_account = Account.objects.get_one({ 'type': Account.TYPE_COMPANY, 'details.subject_id': company._id }) if not company_account: errors['general'] = 'Не найден счет компании' else: promo_account = Account.objects.get_one( {'system_id': Account.FIXED_BANK_ACCOUNT_ID}) admin_user = get_company_admin_user(company) if not admin_user: errors[ 'general'] = 'Не найден пользователь компании для отправки письма!' else: if not promo_account: errors[ 'general'] = 'Не найден системный банковский счет' else: #noinspection PyUnboundLocalVariable transaction = Transaction({ 'source': promo_account._id, 'dest': company_account._id, 'amount': amount_data, 'comment': comment }) transaction.save() transaction.apply() self.send_deposit_transaction_msg( admin_user.email, transaction._id, amount_data_dec) return HttpResponseRedirect('/finances/') data['company_rek_id'] = company_rek_id data['amount'] = amount data['comment'] = comment return render_to_response('finances/deposit_transfer.html', data, context_instance=RequestContext(request))
company_account = Account.objects.get_one({ 'type': Account.TYPE_COMPANY, 'details.subject_id': self.company._id }) self.assertIsNotNone(company_account) bank_account = Account.objects.get_one( {'system_id': Account.FIXED_BANK_ACCOUNT_ID}) tr = Transaction.objects.get_one({ 'source': bank_account._id, 'dest': company_account._id }) self.assertIsNotNone(tr) self.assertEqual(tr.amount, Currency.russian_roubles(invoice.price)) invoice = Invoice.objects.get_one({'_id': invoice._id}) self.assertEqual(invoice.status, InvoiceStatusEnum.PAID) def test_rot(self): self.register(verified=False) invoice = Invoice({ 'payer': self.company._id, 'number': u'КЦ-123', 'recipient': u'ООО "РЕК1.РУ"', 'address': u'192102, Санкт-Петербург, ул. Салова, д.55, корп. 5, лит. А', 'account': u'30101810000000000201', 'account_name': u'ИНН/КПП 7816469431/781601001 ООО "РЕК1.РУ"', 'bank_name': u'ОАО АКБ "Авангард" г.Москва',
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
class RegistrationPromoCode(SimpleModel): INVALID_CODE_VALUE = 0 MIN_CODE_VALUE = 11111111 MAX_CODE_VALUE = 99999999 def __init__(self, kwargs): kwargs = kwargs or {} self._id = kwargs.get('_id') self.code = kwargs.get('code', self.INVALID_CODE_VALUE) self.promotion_id = kwargs.get('promotion_id') self.company_id = kwargs.get('company_id') self.used_date = kwargs.get('used_date') self.price = kwargs.get('price', Currency.russian_roubles(0)) if self.price and not isinstance(self.price, Currency): self.price = Currency(self.price) def _is_used(self): if self.used_date and self.company_id: return True else: return False used = property(_is_used) def _is_active(self): if self.used: return False promo = Promotion.objects.get_one({'_id' : self.promotion_id}) return promo is not None and promo.active active = property(_is_active) def use(self, company_id): if self.code < self.MIN_CODE_VALUE or self.code > self.MAX_CODE_VALUE: raise Exception('Invalid code id: %s. Can not use.' % unicode(self.code)) if not isinstance(company_id, ObjectId): raise Exception('Invalid company id: %s' % unicode(company_id)) if self.used: raise Exception('Promo code %s already used by company %s on %s.' % (unicode(self.code), unicode(self.company_id), unicode(self.used_date))) self.used_date = timezone.now() self.company_id = company_id if not self._id: self.save() else: self.objects.update({'_id' : self._id}, {'$set' : {'used_date' : self.used_date, 'company_id' : self.company_id}}) def _fields(self): return { 'code' : self.code, 'promotion_id' : self.promotion_id, 'company_id' : self.company_id, 'used_date' : self.used_date, 'price' : self.price.fields() } @classmethod def generate_unique_code(cls): while True: promo_code = random.randrange(10000000,99999999) if not cls.objects.get_one({'code' : promo_code}): return promo_code
def post(self, request): errors = {} if not request.POST.has_key('add_promo_action'): return HttpResponseBadRequest("Do not know what to do.") comment = request.POST.get('comment', '').strip() start_date = request.POST.get('start_date', '').strip() duration = request.POST.get('duration', '').strip() amount = request.POST.get('amount', '').strip() count = request.POST.get('count', '').strip() start_date_obj = None duration_int = 0 amount_dec = Decimal(0) count_int = 0 if not len(comment): errors['comment'] = 'Поле не может быть пустым' try: start_date_obj = datetime.strptime(start_date, '%d-%m-%Y') except Exception: errors['start_date'] = 'Некорректная дата' try: duration_int = int(duration) if duration_int <= 0: raise ValueError() except ValueError: errors['duration'] = 'Введите число > 0' try: count_int = int(count) if count_int <= 0 or count_int > 100000000: raise ValueError() except ValueError: errors['count'] = 'Введите число > 0' try: amount_dec = Decimal(amount) if amount_dec <= Decimal(0) or amount_dec > Decimal(1000000000): raise Exception() except Exception: errors[ 'amount'] = 'Введите сумму в рублях.копейках (напр. 1000 или 10.22)' if not len(errors): create_reg_promotion(start_date_obj, duration_int, comment, Currency.russian_roubles(amount_dec), count_int) return HttpResponseRedirect('/ads/view_promo_actions/') return render_to_response('ads/add_promo_action.html', { 'errors': errors, 'comment': comment, 'start_date': start_date, 'duration': duration, 'amount': amount, 'count': count }, context_instance=RequestContext(request))
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