def get_wallet_info(self, request): _wallet = Wallet.get_object(**{'user_id': request.user.id}) if isinstance(_wallet, Exception): initial_dict = {'user_id': request.user.id, 'balance': '0'} _wallet = Wallet(**initial_dict) return _wallet
def register_view(request): try: request_data = json.loads(request.body) logger.info("Register API Accessed: /") validations = validate_form(request_data) if validations[1]: raise ValidationError(validations[1]) form = CreateCustomerForm(request_data) customer = form.save() wallet = Wallet(customer=customer) wallet.save() dto = { 'username': customer.username, 'email': customer.email, 'customer_id': str(customer.cxid), 'wallet_id': str(wallet.wxid) } return JsonResponse(dto, json_dumps_params=JSON_PARAMS) except json.decoder.JSONDecodeError as e: logger.error('Error in Registration : Malformed Request Body ' + str(e.args[0])) return JsonResponse( {"Message": 'Malformed request body ' + str(e.args[0])}, json_dumps_params=JSON_PARAMS) except ValidationError as e: logger.error('Form Validation Failed. Fields = ' + str(e)) return JsonResponse({"Message": 'Missing Field: ' + str(e)}, json_dumps_params=JSON_PARAMS) except ValueError as e: logger.error('Error in Save : DB Error' + str(e.args[0])) return JsonResponse({"Message": 'Error in DB Save. ' + str(e.args[0])}, json_dumps_params=JSON_PARAMS)
def has_enough_balance(self, request, amount_of_money): """ 余额是否充足 """ if not Wallet.can_withdraw(request): return False return Wallet.has_enough_balance(request, amount_of_money)
def add_wallet(request): if request.method == 'POST': name = request.POST['name'] balance = request.POST['balance'] wallet = Wallet(name=name, balance=balance, begin=balance) if wallet: wallet.save() return redirect('transection') return render(request, 'wallet/add-wallet.html')
def save(self, request): adapter = get_adapter() user = adapter.new_user(request) self.cleaned_data = self.get_cleaned_data() adapter.save_user(request, user, self) setup_user_email(request, user, []) # save new account user.save() # new wallet user_wallet = Wallet(user=user, current_balance=0.00) user_wallet.save() return user
def signup(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') password = form.cleaned_data.get('password1') user = authenticate(username=username, password=password) login(request, user) current = Wallet(user=request.user, balance=0) current.save() return redirect('dashboard') else: form = UserCreationForm() return render(request, 'registration/signup.html', {'form': form})
def create_user(self, email, password=None, **kwargs): if not email: raise ValidationError(_('ایمیل اجباری می باشد'), code='null') user = self.model(email=self.normalize_email(email), **kwargs) user.set_password(password) user.activation_code = uuid.uuid4() w = Wallet() w.save() user.wallet_id = w.id user.save(using=self._db) senders.send_email('activate', 'تایید حساب کاربری دنگ پرداز', {'code': user.activation_code}, user.email) return user
def create(self, validated_data): request = self.context.get("request") wallet = request.user.profile.wallet if wallet: return wallet return update_object(Wallet(profile=request.user.profile), validated_data)
def get_context_data(self, **kwargs): context = super(LipaView, self).get_context_data(**kwargs) if self.request.user.id: context['bookings'] = Booking.objects.filter( user=self.request.user).order_by('-created') context['wallet_transactions'] = Transaction.objects.filter( wallet__owner=self.request.user).order_by('-created') context['balance'] = Wallet.user_balance(self.request.user) return context
def save(self, request, amount_of_money, **kwargs): # 此处需要添加回滚操作 # 冻结相应金额 result = Wallet.update_blocked_money(request, amount_of_money) if isinstance(result, Exception): return result try: return super(WithdrawSerializer, self).save(**kwargs) except Exception as e: return e
def safe_use(self, request): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) with transaction.atomic(): Wallet.safe_use_1(request.user.wallet, serializer.validated_data['point']) return Response()
def get_wallet_info(self, request): return Wallet.get_object(**{'user_id': request.user.id})
def get_wallet_object(self, request): return Wallet.get_object(user_id=request.user.id)
def make_payment(request): if request.method == 'POST': date_of_travel = request.POST.get('date_of_travel') travel_class = request.POST.get('travel_class') trip = request.POST.get('trip') # validation if not date_of_travel: return HttpResponseBadRequest('Date of Travel is required') if not travel_class: return HttpResponseBadRequest('The class is required') if not trip: print(trip) return HttpResponseBadRequest('Trip is required') if date_of_travel: date_of_travel = datetime.datetime.strptime( date_of_travel, '%d/%m/%Y') booking = Booking.objects.create(date_of_travel=date_of_travel, travel_class=travel_class, user=request.user) if travel_class == Booking.TRAVEL_CLASSES.economy: amount = 100 elif travel_class == Booking.TRAVEL_CLASSES.first_class: amount = 300 # Check if user has enough in wallet wallet_balance = Wallet.user_balance(request.user) if wallet_balance >= amount: # Pay via wallet Wallet.debit_user(request.user, amount, travel_class + ' ticket') booking.payment_reference = str( Transaction.objects.filter( wallet__owner=request.user).last().id) booking.status = Booking.STATUS.paid else: # Pay directly from MM wallet response = do_merchant_payment( request.user.phone_number.as_e164.replace('+', ''), amount).json() if response['transactionStatus'] == '200': booking.payment_reference = response['transactionReference'] booking.status = Booking.STATUS.paid # send_sms(request.user.phone_number.as_e164, # "Thanks you for using LipaME. Your ticket number is TKT#{}".format(booking.id), # None) else: booking.status = Booking.STATUS.failed # send_sms(request.user.phone_number.as_e164, # "Thanks you for using LipaME. Your ticket number is TKT#{}".format(booking.id), # None) send_mail( "Thanks you for using LipaME. Your ticket number is TKT#{}".format( booking.id), 'Your Madaraka Express Tickets', '*****@*****.**', [request.user.email], fail_silently=False, ) booking.save() response_data = {} response_data['result'] = 'Create Payment successful!' response_data['booking'] = booking.id return JsonResponse(response_data) else: return JsonResponse({"nothing to see": "this isn't happening"})