def saveAdditionalInfo(request, form, model, *args, **kwargs): """Save the third register page - Additional info.""" if model is None: return None initParam = kwargs.get('initParam') # The app in status=3 can not be edit. if model.status == 3: return redirect( reverse(initParam.get('nextPage'), kwargs={'pk': model.id})) model.description = form.cleaned_data['description'] pathList = request.FILES.getlist('path') if pathList: maxNum = common.getSystemParam(key='max_num_attachment', default=50) attachments = appModels.Attachment.objects.filter(app_id=model.id) if len(pathList) + len(attachments) > string.atoi(maxNum): initParam['attachmentError'] = _( 'The attachment number can not be more than %(number)s.') % { 'number': maxNum[0].value } return None attachmentSize = common.getSystemParam(key='attachment_size', default=50000000) for path in pathList: attachment = appModels.Attachment(path=path) attachment.name = path.name if path.name.endswith( '.txt') and path.content_type == 'text/plain': attachment.type = 1 elif path.content_type.startswith('image'): attachment.type = 2 elif path.name.endswith( '.pdf') and path.content_type == 'application/pdf': attachment.type = 3 # elif path.name.endswith('.doc') and path.content_type == 'application/msword': # attachment.type = 4 # elif path.name.endswith('.xls') and path.content_type == 'application/vnd.ms-excel': # attachment.type = 4 # elif path.name.endswith('.ppt') and path.content_type == 'application/vnd.ms-powerpoint': # attachment.type = 4 else: initParam['attachmentError'] = _( 'The file type of %(param)s does not supported.') % { 'param': path.name } return None if path.size > string.atof(attachmentSize): initParam['attachmentError'] = _( 'The file can not be more than %(number)M.') % { 'number': attachmentSize / 000000 } return None attachment.app = model attachment.save() model.save() return redirect(reverse(initParam.get('nextPage'), kwargs={'pk': model.id}))
def executeOnePriceBuy(*args, **kwargs): """The operation of one price buy, after buyer payed successfully.""" initParam = kwargs.get('initParam') transaction = initParam.get('transaction') if transaction: transaction.status = 3 transaction.is_active = True txn_expiry_date = string.atoi( common.getSystemParam(key='txn_expiry_date', default=15)) transaction.end_time = datetime.datetime.now() + datetime.timedelta( days=txn_expiry_date) transaction.buyer_account = initParam.get('buyer_account') acceptGateways = paymentModels.AcceptGateway.objects.filter( user_id=transaction.seller.id, type_id=transaction.gateway.id, is_active=True) transaction.seller_account = acceptGateways[0].value transaction.appswalk_account = settings.APPSWALK_ACCOUNT txn_fee_pct = string.atof( common.getSystemParam(key='txn_fee_pct', default=0.01)) transaction.appswalk_price = transaction.price * txn_fee_pct transaction.seller_price = transaction.price * (1 - txn_fee_pct) transaction.save() #Log transaction transactionsLog = models.TransactionLog() transactionsLog.transaction = transaction transactionsLog.app = transaction.app transactionsLog.status = transaction.status transactionsLog.buyer = transaction.buyer transactionsLog.price = transaction.price transactionsLog.buyer_account = transaction.buyer_account transactionsLog.seller_account = transaction.seller_account transactionsLog.appswalk_account = transaction.appswalk_account transactionsLog.gateway = transaction.gateway transactionsLog.appswalk_price = transaction.appswalk_price transactionsLog.seller_price = transaction.seller_price transactionsLog.pay_key = transaction.pay_key transactionsLog.save() #Update app status and end_date. app = transaction.app if app.status == 2: app.status = 3 app.end_date = datetime.datetime.now() app.save() #Send email to seller notificationViews.onePriceBuyInformSellerEmail(transaction=transaction) log.info( _('The transaction of one price buy with id %(param1)s is payed by %(param2)s.' ) % { 'param1': transaction.id, 'param2': transaction.buyer.username }) return transaction return None
def saveAdditionalInfo(request, form, model, *args, **kwargs): """Save the third register page - Additional info.""" if model is None: return None initParam = kwargs.get("initParam") # The app in status=3 can not be edit. if model.status == 3: return redirect(reverse(initParam.get("nextPage"), kwargs={"pk": model.id})) model.description = form.cleaned_data["description"] pathList = request.FILES.getlist("path") if pathList: maxNum = common.getSystemParam(key="max_num_attachment", default=50) attachments = appModels.Attachment.objects.filter(app_id=model.id) if len(pathList) + len(attachments) > string.atoi(maxNum): initParam["attachmentError"] = _("The attachment number can not be more than %(number)s.") % { "number": maxNum[0].value } return None attachmentSize = common.getSystemParam(key="attachment_size", default=50000000) for path in pathList: attachment = appModels.Attachment(path=path) attachment.name = path.name if path.name.endswith(".txt") and path.content_type == "text/plain": attachment.type = 1 elif path.content_type.startswith("image"): attachment.type = 2 elif path.name.endswith(".pdf") and path.content_type == "application/pdf": attachment.type = 3 # elif path.name.endswith('.doc') and path.content_type == 'application/msword': # attachment.type = 4 # elif path.name.endswith('.xls') and path.content_type == 'application/vnd.ms-excel': # attachment.type = 4 # elif path.name.endswith('.ppt') and path.content_type == 'application/vnd.ms-powerpoint': # attachment.type = 4 else: initParam["attachmentError"] = _("The file type of %(param)s does not supported.") % { "param": path.name } return None if path.size > string.atof(attachmentSize): initParam["attachmentError"] = _("The file can not be more than %(number)M.") % { "number": attachmentSize / 000000 } return None attachment.app = model attachment.save() model.save() return redirect(reverse(initParam.get("nextPage"), kwargs={"pk": model.id}))
def tradeAction(request, *args, **kwargs): """Query trade status.""" initParam = {} user_id = string.atoi(kwargs.get('user_id')) app_id = kwargs.get('app_id') action = kwargs.get('action') if 'sell' == action and user_id == request.user.id: transaction = get_object_or_404(models.Transaction, app_id=app_id, seller_id=user_id, is_active=True) elif 'buy' == action and user_id == request.user.id: transaction = get_object_or_404(models.Transaction, app_id=app_id, buyer_id=user_id) if transaction.status == 2: token = common.getToken(key='token_length', default=30) initParam['pay_url'] = '/'.join([ common.getHttpHeader(request), 'transaction/buyer-pay', str(app_id), str(transaction.id), token ]) else: raise Http404 support_user = common.getSystemParam(key='support_user', default='appswalk') support_users = models.User.objects.filter(username=support_user) if support_users: initParam['support_user'] = support_users[0] else: log.error(_('Support user account does not exist.')) initParam['transaction'] = transaction if transaction.status == 2 or transaction.status == 3: if transaction.end_time > datetime.datetime.now(): initParam['time_remaining'] = time.mktime( time.strptime( transaction.end_time.strftime('%Y-%m-%d %H:%M:%S'), '%Y-%m-%d %H:%M:%S')) else: initParam['time_remaining'] = "Deal Closed" initParam['paid_expiry'] = True if tradeOperation(request, transaction=transaction, initParam=initParam): return redirect(request.path) elif transaction.status == 4: initParam['time_remaining'] = common.dateBefore(transaction.end_time) initParam['seller_txn'] = creditViews.getAppraisement( user_id=transaction.seller.id, txn_id=transaction.id) initParam['buyer_txn'] = creditViews.getAppraisement( user_id=transaction.buyer.id, txn_id=transaction.id) if creditViews.createAppraisement(request, initParam=initParam): return redirect(request.path) return render_to_response('transaction/trade_action.html', initParam, context_instance=RequestContext(request))
def closedTrade(request, *args, **kwargs): """Need update end_time to now.""" initParam = {} transaction = get_object_or_404(models.Transaction, pk=kwargs.get('txn_id'), buyer_id=kwargs.get('buyer_id'), is_active=True) transaction.status = 4 transaction.end_date = datetime.datetime.now() transaction.save() #Log transaction transactionsLog = models.TransactionLog() transactionsLog.transaction = transaction transactionsLog.app = transaction.app transactionsLog.status = transaction.status transactionsLog.buyer = transaction.buyer transactionsLog.save() #Increase seller and buyer credit point point = common.getSystemParam(key='cp_closed_trade', default=50) creditViews.increaseCreditPoint(user=transaction.buyer, point=point) creditViews.increaseCreditPoint(user=transaction.seller, point=point) #Send email to seller and buyer notificationViews.closedTradeInform(transaction=transaction) initParam['transaction'] = transaction return render_to_response('transaction/trade_action.html', initParam, context_instance=RequestContext(request))
def queryAppsWithPaginator(request, *args, **kwargs): """Offer query function""" page_range = kwargs.get("page_range") page = kwargs.get("page", 1) offers = kwargs.get("offers") if page_range is None: page_range = common.getSystemParam(key="page_range", default=10) if offers: offer_list = [] for offer in offers: # info list[0]:The offer info info_list = [offer] offer_list.append(info_list) paginator = Paginator(offer_list, page_range) try: offerInfoList = paginator.page(page) except PageNotAnInteger: offerInfoList = paginator.page(1) except EmptyPage: offerInfoList = paginator.page(paginator.num_pages) # Query offer record showed in the current page. for info_list in offerInfoList: info_list.append(offerModels.Offer.OFFER_TYPES[info_list[0].type - 1][1]) records = offerModels.OfferRecord.objects.filter(offer_id=info_list[0].id) if records: info_list.append(records[0].view_count) info_list.append(records[0].apply_count) else: info_list.append(0) info_list.append(0) else: return None return offerInfoList
def checkOutSuccess(request, *args, **kwargs): """The operation after user payment successfully.""" serviceDetail = kwargs.get('serviceDetail') if serviceDetail: app = serviceDetail.app service_expiry_date = string.atoi( common.getSystemParam(key='service_expiry_date', default=31)) if serviceDetail.start_date < datetime.datetime.now(): serviceDetail.start_date = datetime.datetime.now() serviceDetail.end_date = datetime.datetime.now( ) + datetime.timedelta(days=service_expiry_date) serviceDetail.is_payed = True serviceDetail.save() # If app is draft or has been closed, change app to published after payment,. if app.status == 1 or app.status == 3: app.status = 2 app.publish_date = serviceDetail.start_date app.begin_date = serviceDetail.start_date app.end_date = serviceDetail.end_date else: app.end_date = serviceDetail.end_date app.save() #Init transaction model data # transactionViews.initTransaction(request, app=app) #Share app to social system. shareApp(request, serviceDetail=serviceDetail, app=app) return serviceDetail return None
def checkIfSellApp(*args, **kwargs): """ The task will be done every hour. When service stop, if bidding price is more than max price, seller has 7 days to trade now. Then seller did not trade app in 7 days, seller's credit points will be decreased. """ transactions = txnModels.Transaction.objects.filter( status=1, end_time__isnull=False, end_time__lte=datetime.datetime.now()).exclude(buy_type=1) massEmailThread = email.MassEmailThread() points = common.getSystemParam(key='cp_buyer_unpaid', default=50) log.info("----") for transaction in transactions: log.info(transaction.id) #Decrease seller's credit points creditViews.decreaseCreditPoint(user=transaction.seller, point=string.atoi(points), type=1, ref_id=transaction.id) templates = notificationModels.NotificationTemplate.objects.filter( name='unsold_end_inform_seller') if templates: subject = templates[0].subject message = templates[0].template.replace( '{param1}', transaction.seller.username).replace('{param2}', points) massEmailThread.addEmailData( subject=subject, message=message, recipient_list=[transaction.seller.email]) massEmailThread.start() return None
def createAppraisement(request, *args, **kwargs): initParam = kwargs.get('initParam') form = forms.AppraisementForm() if request.method == 'POST': transaction = initParam.get('transaction') appraisementForm = forms.AppraisementForm(request.POST) if appraisementForm.is_valid(): appraisement = appraisementForm.save(commit=False) appraisement.user_id = request.user.id appraisement.transaction_id = transaction.id appraisement.save() point = string.atoi( common.getSystemParam(key='cp_closed_trade', default=50)) increaseCreditPoint(user=request.user, point=point, type=1, ref_id=transaction.id) return appraisement else: initParam['error_msg'] = _( "Appraisement failed. Please try again.") log.error(_("Appraisement failed. Please try again.")) initParam['form'] = form return None
def checkOutSuccess(request, *args, **kwargs): """The operation after user payment successfully.""" serviceDetail = kwargs.get('serviceDetail') if serviceDetail: app = serviceDetail.app service_expiry_date = string.atoi(common.getSystemParam(key='service_expiry_date', default=31)) if serviceDetail.start_date < datetime.datetime.now(): serviceDetail.start_date = datetime.datetime.now() serviceDetail.end_date = datetime.datetime.now() + datetime.timedelta(days=service_expiry_date) serviceDetail.is_payed = True serviceDetail.save() # If app is draft or has been closed, change app to published after payment,. if app.status == 1 or app.status == 3: app.status = 2 app.publish_date = serviceDetail.start_date app.begin_date = serviceDetail.start_date app.end_date = serviceDetail.end_date else: app.end_date = serviceDetail.end_date app.save() #Init transaction model data # transactionViews.initTransaction(request, app=app) #Share app to social system. shareApp(request, serviceDetail=serviceDetail, app=app) return serviceDetail return None
def getServiceInfo(request, *args, **kwargs): """#Show service information to user.""" initParam = kwargs.get('initParam') token = initParam.get('token') gateway = initParam.get('gateway') if token and gateway: discount_rate = common.getSystemParam(key='discount_rate', default=1) gateways = paymentModels.Gateway.objects.filter(name__iexact=gateway) if gateways: serviceDetails = models.ServiceDetail.objects.filter( pay_token=token, is_payed=False, gateway_id=gateways[0].id) if serviceDetails: serviceItems = serviceDetails[0].serviceitem.all() return serviceDetails[0], serviceItems, discount_rate else: log.error( _('User:%(param1)s, ServiceDetail with pay_token %(param2)s no exists.' ) % { 'param1': request.user.username, 'param2': token }) else: log.error( _('Token:%(param1)s. Gateway %(param2)s no exists.') % { 'param1': token, 'param2': gateway }) else: log.error(_('Token or Gateway no exists.')) return None
def verificationAppForSeller(*args, **kwargs): """ The task will be done in at schedule time, such as: every four hours. After Seller creating app clicks verified, verified app owner ship on schedule plan """ times = string.atoi(common.getSystemParam(key='verify_app_times', default=3)) ownerShipScans = appModels.OwnerShip_Scan.objects.filter(times__lte=times) massEmailThread = email.MassEmailThread() for ownerShipScan in ownerShipScans: app = ownerShipScan.app result = common.getITunes(app.apple_id) if result is None: continue description = result.get('description', None) if app.verify_token in description: templates = notificationModels.NotificationTemplate.objects.filter(name='verified_app_success_inform_seller') if templates: subject = templates[0].subject.replace('{param1}', app.app_name) message = templates[0].template.replace('{param1}', app.publisher.username).replace('{param2}', app.app_name) massEmailThread.addEmailData(subject=subject, message=message, recipient_list=[app.publisher.email]) ownerShipScan.delete() #Update app is_verified value app.is_verified = True app.save() else: ownerShipScan.times += 1 ownerShipScan.save() templates = notificationModels.NotificationTemplate.objects.filter(name='verified_app_failed_inform_seller') if ownerShipScan.times == 3 and templates: subject = templates[0].subject.replace('{param1}', app.app_name) message = templates[0].template.replace('{param1}', app.publisher.username).replace('{param2}', app.app_name) massEmailThread.addEmailData(subject=subject, message=message, recipient_list=[app.publisher.email]) massEmailThread.start() return None
def executeOnePriceBuy(*args, **kwargs): """The operation of one price buy, after buyer payed successfully.""" initParam = kwargs.get('initParam') transaction = initParam.get('transaction') if transaction: transaction.status = 3 transaction.is_active = True txn_expiry_date = string.atoi(common.getSystemParam(key='txn_expiry_date', default=15)) transaction.end_time = datetime.datetime.now() + datetime.timedelta(days=txn_expiry_date) transaction.buyer_account = initParam.get('buyer_account') acceptGateways = paymentModels.AcceptGateway.objects.filter(user_id=transaction.seller.id, type_id=transaction.gateway.id, is_active=True) transaction.seller_account = acceptGateways[0].value transaction.appswalk_account = settings.APPSWALK_ACCOUNT txn_fee_pct = string.atof(common.getSystemParam(key='txn_fee_pct', default=0.01)) transaction.appswalk_price = transaction.price * txn_fee_pct transaction.seller_price = transaction.price * (1 - txn_fee_pct) transaction.save() #Log transaction transactionsLog = models.TransactionLog() transactionsLog.transaction = transaction transactionsLog.app = transaction.app transactionsLog.status = transaction.status transactionsLog.buyer = transaction.buyer transactionsLog.price = transaction.price transactionsLog.buyer_account = transaction.buyer_account transactionsLog.seller_account = transaction.seller_account transactionsLog.appswalk_account = transaction.appswalk_account transactionsLog.gateway = transaction.gateway transactionsLog.appswalk_price = transaction.appswalk_price transactionsLog.seller_price = transaction.seller_price transactionsLog.pay_key = transaction.pay_key transactionsLog.save() #Update app status and end_date. app = transaction.app if app.status == 2: app.status = 3 app.end_date = datetime.datetime.now() app.save() #Send email to seller notificationViews.onePriceBuyInformSellerEmail(transaction=transaction) log.info(_('The transaction of one price buy with id %(param1)s is payed by %(param2)s.') % {'param1': transaction.id, 'param2': transaction.buyer.username}) return transaction return None
def queryAppsWithPaginator(request, *args, **kwargs): """App query function for home page, feature page and so on.""" page_range = kwargs.get('page_range') page = kwargs.get('page', 1) apps = kwargs.get('apps') if page_range is None: page_range = common.getSystemParam(key='page_range', default=10) if apps: app_list = [] for app in apps: #info list[0]:The app info info_list = [app] app_list.append(info_list) paginator = Paginator(app_list, page_range) try: appInfoList = paginator.page(page) except PageNotAnInteger: appInfoList = paginator.page(1) except EmptyPage: appInfoList = paginator.page(paginator.num_pages) #Just query the app bid information showed in the current page. for info_list in appInfoList: data = {} initBidInfo(request, app=info_list[0], initParam=data) #info list[1]:current price info_list.append(data.get('current_price')) #info list[2]:bid numbers info_list.append(data.get('bid_num')) #info list[3]:bid price info_list.append(data.get('bid_price')) #info list[4]:remaining date, such as: [10, day], [25, minute] info_list.append(common.dateRemaining(info_list[0].end_date)) #info list[5]:percent of remaining date. 0:0, 1:1%-37%, 2:38%-62%, 1:63%-99%, 4:100% serviceDate = (info_list[0].end_date - info_list[0].begin_date).days if datetime.datetime.now() <= info_list[0].begin_date: percent = 100 elif info_list[0].end_date <= datetime.datetime.now(): percent = 0 else: percent = (info_list[0].end_date - datetime.datetime.now()).days * 100 / serviceDate if percent <= 0: info_list.append(0) elif percent == 100: info_list.append(4) elif percent >= 63: info_list.append(3) elif percent >= 38: info_list.append(2) elif percent > 0: info_list.append(1) else: return None return appInfoList
def buyerPay(request, *args, **kwargs): """Buyer pay, after seller begin to trade.""" initParam = {} app_id = kwargs.get('app_id') txn_id = kwargs.get('txn_id') #TODO:Can use or verify it later. token_id = kwargs.get('token') transaction = get_object_or_404(models.Transaction, pk=txn_id, app_id=app_id, buyer_id=request.user.id, status=2, is_active=True) app = transaction.app #Buyser pay for app. txn_fee_pct = string.atof( common.getSystemParam(key='txn_fee_pct', default=0.01)) initParam['currency'] = app.currency.currency initParam['appsWalk_account'] = settings.APPSWALK_ACCOUNT initParam['gateway'] = 'paypal' gateways = paymentModels.Gateway.objects.filter( name__iexact=initParam.get('gateway')) acceptGateways = paymentModels.AcceptGateway.objects.filter( user_id=transaction.seller.id, type_id=gateways[0].id, is_active=True) initParam['seller_account'] = acceptGateways[0].value initParam['appsWalk_amount'] = transaction.price * txn_fee_pct initParam['seller_amount'] = transaction.price * (1 - txn_fee_pct) initParam['txn_id'] = transaction.id #The needed operation method in pay. initParam['executeMethod'] = updateTransaction #The back page, when pay has error. if request.session.get('back_page', None): del request.session['back_page'] if request.session.get('back_page_msg', None): del request.session['back_page_msg'] url = '/'.join([ common.getHttpHeader(request), 'transaction/trade-action/buy', str(app.id), str(request.user.id) ]) request.session['back_page'] = url request.session['back_page_msg'] = 'Trade Action' #The success return page, when pay finish. if request.session.get('success_page', None): del request.session['success_page'] if request.session.get('success_page_msg', None): del request.session['success_page_msg'] request.session['success_page'] = url request.session['success_page_msg'] = 'Trade Action' return paymentViews.pay(request, initParam=initParam)
def checkServiceDateForApps(*args, **kwargs): """ The task will be done every hour. Do something, when the app service date is ending. 1. App status will be changed from published to closed. 2. Send email of expiry date to seller.(The email: 1.Service end; 2.Seller can trade now.) """ # current_date = datetime.datetime.combine(datetime.date.today(), datetime.time()) # next_date = datetime.datetime.combine(datetime.date.today() + datetime.timedelta(days=1), datetime.time()) # apps = appModels.App.objects.filter(status=2, end_date__gte=current_date, end_date__lt=next_date) apps = appModels.App.objects.filter(status=2, end_date__lte=datetime.datetime.now()) massEmailThread = email.MassEmailThread() for app in apps: app.status = 3 app.save() max_price = app.bidding_set.filter(status=1).aggregate(Max('price')) current_price = max_price.get('price__max', 0) #If bidding price is more than max price, seller has 7 days to trade or else seller can not trade it. if app.reserve_price and app.reserve_price <= current_price: bids = bidModels.Bidding.objects.filter(app_id=app.id, price=current_price, status=1) transactions = app.transaction_set.filter(is_active=True) if transactions: transaction = transactions[0] else: transaction = txnModels.Transaction() transaction.status = 1 transaction.app = app transaction.is_active = True paid_expiry_date = string.atoi(common.getSystemParam(key='sell_expiry_date', default=7)) transaction.end_time = app.end_date + datetime.timedelta(days=paid_expiry_date) transaction.save() transactionsLog = txnModels.TransactionLog() transactionsLog.transaction = transaction transactionsLog.app = app transactionsLog.status = 1 transactionsLog.save() templates = notificationModels.NotificationTemplate.objects.filter(name='service_end_inform_seller') if templates: subject = templates[0].subject.replace('{param1}', bids[0].buyer.username) message = templates[0].template.replace('{param1}', app.publisher.username).replace('{param2}', app.app_name) massEmailThread.addEmailData(subject=subject, message=message, recipient_list=[app.publisher.email]) else: templates = notificationModels.NotificationTemplate.objects.filter(name='service_end_inform_seller_lt_reserve_price') if templates: subject = templates[0].subject.replace('{param1}', app.app_name) message = templates[0].template.replace('{param1}', app.publisher.username) massEmailThread.addEmailData(subject=subject, message=message, recipient_list=[app.publisher.email]) massEmailThread.start() return None
def verificationAppForSeller(*args, **kwargs): """ The task will be done in at schedule time, such as: every four hours. After Seller creating app clicks verified, verified app owner ship on schedule plan """ times = string.atoi( common.getSystemParam(key='verify_app_times', default=3)) ownerShipScans = appModels.OwnerShip_Scan.objects.filter(times__lte=times) massEmailThread = email.MassEmailThread() for ownerShipScan in ownerShipScans: app = ownerShipScan.app result = common.getITunes(app.apple_id) if result is None: continue description = result.get('description', None) if app.verify_token in description: templates = notificationModels.NotificationTemplate.objects.filter( name='verified_app_success_inform_seller') if templates: subject = templates[0].subject.replace('{param1}', app.app_name) message = templates[0].template.replace( '{param1}', app.publisher.username).replace('{param2}', app.app_name) massEmailThread.addEmailData( subject=subject, message=message, recipient_list=[app.publisher.email]) ownerShipScan.delete() #Update app is_verified value app.is_verified = True app.save() else: ownerShipScan.times += 1 ownerShipScan.save() templates = notificationModels.NotificationTemplate.objects.filter( name='verified_app_failed_inform_seller') if ownerShipScan.times == 3 and templates: subject = templates[0].subject.replace('{param1}', app.app_name) message = templates[0].template.replace( '{param1}', app.publisher.username).replace('{param2}', app.app_name) massEmailThread.addEmailData( subject=subject, message=message, recipient_list=[app.publisher.email]) massEmailThread.start() return None
def taskForBuyUnpaid(*args, **kwargs): """ The task will be done in at schedule time, such as: every hour. Do something, if buy still unpaid after 7 days of paid_expiry_date set in system-param table. 1. Change transaction is_active from True to False. 2. Buyer will be subtracted 50 credit point, and put into blacklist. 3. Buyer's all bidding status is changed from approved to rejected.(Note: All bidding for this buyer.) 4. Send email to buyer.(The email: 1.Subtract his 50 credit point; 2.Put him into blacklist.) 5. Send email to seller.(The email: 1.Seller may choice the buyer bidding with second max price to trade again; 2.The unpaid buyer has been put into blacklist.) 6. Send email to new buyer bidding with second max price. (The email: 1. He is the max bidding one now; 2. Seller will trade with you later.) """ points = string.atoi(common.getSystemParam(key='cp_no_closed_trade', default=50)) templates_buyer = notificationModels.NotificationTemplate.objects.filter(name='buyer_unpaid_inform_buyer') templates_seller = notificationModels.NotificationTemplate.objects.filter(name='buyer_unpaid_inform_seller') templates_second_buyer = notificationModels.NotificationTemplate.objects.filter(name='buyer_unpaid_inform_second_buyer') templates_seller_no_bidding = notificationModels.NotificationTemplate.objects.filter(name='buyer_unpaid_inform_seller_no_bidding') transactions = txnModels.Transaction.objects.filter(is_active=True, status=2, end_time__lte=datetime.datetime.now()) massEmailThread = email.MassEmailThread() for transaction in transactions: transaction.is_active = False transaction.save() creditViews.decreaseCreditPoint(user=transaction.buyer, point=points, type=1, ref_id=transaction.id) bidModels.Bidding.objects.filter(app_id=transaction.app.id, buyer_id=transaction.buyer.id).update(status=False) if templates_buyer: subject = templates_buyer[0].subject message = templates_buyer[0].template.replace('{param1}', transaction.buyer.username) massEmailThread.addEmailData(subject=subject, message=message, recipient_list=[transaction.buyer.email]) bidding = bidModels.Bidding.objects.filter(app_id=transaction.app.id, status=1).order_by('-price') if bidding: if templates_seller: subject = templates_seller[0].subject message = templates_seller[0].template.replace('{param1}', transaction.seller.username).replace('{param2}', transaction.buyer.username) massEmailThread.addEmailData(subject=subject, message=message, recipient_list=[transaction.seller.email]) if templates_second_buyer: subject = templates_second_buyer[0].subject message = templates_second_buyer[0].template.replace('{param1}', bidding[0].buyer.username).replace('{param2}', transaction.app.app_name) massEmailThread.addEmailData(subject=subject, message=message, recipient_list=[bidding[0].buyer.email]) else: if templates_seller_no_bidding: subject = templates_seller_no_bidding[0].subject message = templates_seller_no_bidding[0].template.replace('{param1}', transaction.seller.username) massEmailThread.addEmailData(subject=subject, message=message, recipient_list=[transaction.seller.email]) massEmailThread.start() return None
def initCreditPoint(*args, **kwargs): user = kwargs.get('user') if user: creditPoint = models.CreditPoint() creditPoint.user = user creditPoint.points = common.getSystemParam(key='cp_init_number', default=100) creditPoint.save() #Log Credit Point Change creditLog = models.CreditLog() creditLog.user = user creditLog.credit_point = creditPoint creditLog.points = creditPoint.points creditLog.change_reason = _('Init credit point.') creditLog.save() else: #Log error message print 'Init credit point.' return None
def tradeAction(request, *args, **kwargs): """Query trade status.""" initParam = {} user_id = string.atoi(kwargs.get('user_id')) app_id = kwargs.get('app_id') action = kwargs.get('action') if 'sell' == action and user_id == request.user.id: transaction = get_object_or_404(models.Transaction, app_id=app_id, seller_id=user_id, is_active=True) elif 'buy' == action and user_id == request.user.id: transaction = get_object_or_404(models.Transaction, app_id=app_id, buyer_id=user_id) if transaction.status == 2: token = common.getToken(key='token_length', default=30) initParam['pay_url'] = '/'.join([common.getHttpHeader(request), 'transaction/buyer-pay', str(app_id), str(transaction.id), token]) else: raise Http404 support_user = common.getSystemParam(key='support_user', default='appswalk') support_users = models.User.objects.filter(username=support_user) if support_users: initParam['support_user'] = support_users[0] else: log.error(_('Support user account does not exist.')) initParam['transaction'] = transaction if transaction.status == 2 or transaction.status == 3: if transaction.end_time > datetime.datetime.now(): initParam['time_remaining'] = time.mktime(time.strptime(transaction.end_time.strftime('%Y-%m-%d %H:%M:%S'), '%Y-%m-%d %H:%M:%S')) else: initParam['time_remaining'] = "Deal Closed" initParam['paid_expiry'] = True if tradeOperation(request, transaction=transaction, initParam=initParam): return redirect(request.path) elif transaction.status == 4: initParam['time_remaining'] = common.dateBefore(transaction.end_time) initParam['seller_txn'] = creditViews.getAppraisement(user_id=transaction.seller.id, txn_id=transaction.id) initParam['buyer_txn'] = creditViews.getAppraisement(user_id=transaction.buyer.id, txn_id=transaction.id) if creditViews.createAppraisement(request, initParam=initParam): return redirect(request.path) return render_to_response('transaction/trade_action.html', initParam, context_instance=RequestContext(request))
def checkIfSellApp(*args, **kwargs): """ The task will be done every hour. When service stop, if bidding price is more than max price, seller has 7 days to trade now. Then seller did not trade app in 7 days, seller's credit points will be decreased. """ transactions = txnModels.Transaction.objects.filter(status=1, end_time__isnull=False, end_time__lte=datetime.datetime.now()).exclude(buy_type=1) massEmailThread = email.MassEmailThread() points = common.getSystemParam(key='cp_buyer_unpaid', default=50) log.info("----") for transaction in transactions: log.info(transaction.id) #Decrease seller's credit points creditViews.decreaseCreditPoint(user=transaction.seller, point=string.atoi(points), type=1, ref_id=transaction.id) templates = notificationModels.NotificationTemplate.objects.filter(name='unsold_end_inform_seller') if templates: subject = templates[0].subject message = templates[0].template.replace('{param1}', transaction.seller.username).replace('{param2}', points) massEmailThread.addEmailData(subject=subject, message=message, recipient_list=[transaction.seller.email]) massEmailThread.start() return None
def getServiceInfo(request, *args, **kwargs): """#Show service information to user.""" initParam = kwargs.get('initParam') token = initParam.get('token') gateway = initParam.get('gateway') if token and gateway: discount_rate = common.getSystemParam(key='discount_rate', default=1) gateways = paymentModels.Gateway.objects.filter(name__iexact=gateway) if gateways: serviceDetails = models.ServiceDetail.objects.filter(pay_token=token, is_payed=False, gateway_id=gateways[0].id) if serviceDetails: serviceItems = serviceDetails[0].serviceitem.all() return serviceDetails[0], serviceItems, discount_rate else: log.error(_('User:%(param1)s, ServiceDetail with pay_token %(param2)s no exists.') % {'param1': request.user.username, 'param2': token}) else: log.error(_('Token:%(param1)s. Gateway %(param2)s no exists.') % {'param1': token, 'param2': gateway}) else: log.error(_('Token or Gateway no exists.')) return None
def createAppraisement(request, *args, **kwargs): initParam = kwargs.get('initParam') form = forms.AppraisementForm() if request.method == 'POST': transaction = initParam.get('transaction') appraisementForm = forms.AppraisementForm(request.POST) if appraisementForm.is_valid(): appraisement = appraisementForm.save(commit=False) appraisement.user_id = request.user.id appraisement.transaction_id = transaction.id appraisement.save() point = string.atoi(common.getSystemParam(key='cp_closed_trade', default=50)) increaseCreditPoint(user=request.user, point=point, type=1, ref_id=transaction.id) return appraisement else: initParam['error_msg'] = _("Appraisement failed. Please try again.") log.error(_("Appraisement failed. Please try again.")) initParam['form'] = form return None
def buyerPay(request, *args, **kwargs): """Buyer pay, after seller begin to trade.""" initParam = {} app_id = kwargs.get('app_id') txn_id = kwargs.get('txn_id') #TODO:Can use or verify it later. token_id = kwargs.get('token') transaction = get_object_or_404(models.Transaction, pk=txn_id, app_id=app_id, buyer_id=request.user.id, status=2, is_active=True) app = transaction.app #Buyser pay for app. txn_fee_pct = string.atof(common.getSystemParam(key='txn_fee_pct', default=0.01)) initParam['currency'] = app.currency.currency initParam['appsWalk_account'] = settings.APPSWALK_ACCOUNT initParam['gateway'] = 'paypal' gateways = paymentModels.Gateway.objects.filter(name__iexact=initParam.get('gateway')) acceptGateways = paymentModels.AcceptGateway.objects.filter(user_id=transaction.seller.id, type_id=gateways[0].id, is_active=True) initParam['seller_account'] = acceptGateways[0].value initParam['appsWalk_amount'] = transaction.price * txn_fee_pct initParam['seller_amount'] = transaction.price * (1 - txn_fee_pct) initParam['txn_id'] = transaction.id #The needed operation method in pay. initParam['executeMethod'] = updateTransaction #The back page, when pay has error. if request.session.get('back_page', None): del request.session['back_page'] if request.session.get('back_page_msg', None): del request.session['back_page_msg'] url = '/'.join([common.getHttpHeader(request), 'transaction/trade-action/buy', str(app.id), str(request.user.id)]) request.session['back_page'] = url request.session['back_page_msg'] = 'Trade Action' #The success return page, when pay finish. if request.session.get('success_page', None): del request.session['success_page'] if request.session.get('success_page_msg', None): del request.session['success_page_msg'] request.session['success_page'] = url request.session['success_page_msg'] = 'Trade Action' return paymentViews.pay(request, initParam=initParam)
def queryAppsWithPaginator(request, *args, **kwargs): """Offer query function""" page_range = kwargs.get('page_range') page = kwargs.get('page', 1) offers = kwargs.get('offers') if page_range is None: page_range = common.getSystemParam(key='page_range', default=10) if offers: offer_list = [] for offer in offers: #info list[0]:The offer info info_list = [offer] offer_list.append(info_list) paginator = Paginator(offer_list, page_range) try: offerInfoList = paginator.page(page) except PageNotAnInteger: offerInfoList = paginator.page(1) except EmptyPage: offerInfoList = paginator.page(paginator.num_pages) #Query offer record showed in the current page. for info_list in offerInfoList: info_list.append(offerModels.Offer.OFFER_TYPES[info_list[0].type - 1][1]) records = offerModels.OfferRecord.objects.filter( offer_id=info_list[0].id) if records: info_list.append(records[0].view_count) info_list.append(records[0].apply_count) else: info_list.append(0) info_list.append(0) else: return None return offerInfoList
except Exception, e: initParam["error_msg"] = _("App store link is not correct.") log.error(_("App store link %(param)s is not correct.") % {"param": app_store_link}) log.error(e.message) return None # Save app data if model is None: model = form.save(commit=False) # New app, and init some data model.publisher = appModels.User.objects.get(id=request.user.id) model.store_type = 1 model.status = 1 model.source_code = True model.unique_sell = True currency_id = common.getSystemParam(key="currency", default=1) model.currency = get_object_or_404(appModels.Currency, pk=currency_id) model.minimum_bid = common.getSystemParam(key="minimum_bid", default=10) token_len = common.getSystemParam(key="token_len", default=10) model.verify_token = "".join(random.sample(string.ascii_letters + string.digits, string.atoi(token_len))) model.is_verified = False else: model.title = title model.app_store_link = app_store_link model.app_type = app_type model.rating = result.get("averageUserRating", 0) model.platform_version = result.get("version", None) model.apple_id = result.get("trackId", None) model.app_name = result.get("trackName", None) model.web_site = result.get("sellerUrl", None) model.reviews = result.get("userRatingCount", None)
def createBid(request, *args, **kwargs): if kwargs.get('pk'): initParam = {} app = get_object_or_404(appModels.App, pk=kwargs.get('pk')) initParam['app'] = app initParam['appInfo'] = app.appinfo initBidInfo(request, app=app, initParam=initParam) #For below code using the value #Do something, when the time is app end date. if app.status == 2 and initParam['begin_bid']: initParam['is_callback'] = True if request.method == "POST": biddingForm = forms.BiddingForm(request.POST) #Buyer credit point judge for bidding. min_cp = common.getSystemParam(key='min_cp_for_bid', default=50) cp = creditViews.getUserCreditPoint(user=request.user) if cp == -1 or cp < string.atoi(min_cp): initParam['biddingForm'] = biddingForm initParam['bid_error'] = _( 'You are not allowed to place bid, because your low credit points. But you can buy additional credit points.' ) else: if biddingForm.is_valid(): #From bid_create.html if 'yes' == request.POST.get('bid_create'): bid = biddingForm.save(commit=False) if datetime.datetime.now() > app.end_date: initParam['biddingForm'] = biddingForm initParam['bid_error'] = _( 'The bidding is closed, you can not bid.') elif bid.price >= initParam.get('bid_price'): bid.app = app bid.buyer = request.user bid.status = 1 # userPrivateItem = userSettingModels.UserPrivateItem.objects.filter(key='is_bid_approved') # if userPrivateItem: # is_bid_approved = userSettingModels.UserPrivateSetting.objects.filter(user_id=app.publisher.id, user_private_item_id=userPrivateItem[0]) # #Need be verified by app publisher. # if is_bid_approved and is_bid_approved[0].value == 'True': # bid.status = 3 bid.save() #Send the message to app publisher send_message = request.POST.get('send_message') if send_message and send_message == 'yes': if sendMessage(request, initParam=initParam): notificationViews.sendNewBidEmail(request, bid=bid, app=app) return redirect( reverse('bid:bid_list', kwargs={'pk': app.id})) else: initParam['biddingForm'] = biddingForm initParam['bid_error'] = initParam[ 'message_error'] else: notificationViews.sendNewBidEmail(request, bid=bid, app=app) return redirect( reverse('bid:bid_list', kwargs={'pk': app.id})) else: initParam['biddingForm'] = biddingForm initParam['bid_error'] = _( 'The new bid has been submitted.') #From list_detail.html else: initParam['biddingForm'] = biddingForm initParam['sender'] = request.user initParam['receiver'] = app.publisher transactions = txnModels.Transaction.objects.filter( app_id=app.id).exclude(status=1) if transactions: initParam['transaction'] = transactions[0] #Comment the message # sendMessage(request, initParam=initParam) queryViews.shareSocial(request, initParam=initParam, app=app) return render_to_response('bid/bid_create.html', initParam, context_instance=RequestContext(request)) raise Http404
def registerApp(request, *args, **kwargs): """The common function for create, update app information.""" app = None # initParam maybe save error message, when validate failed. initParam = kwargs.copy() flag = kwargs.get("flag") form = forms.AppForm() # Initial data if kwargs.get("pk"): app = get_object_or_404(appModels.App, pk=kwargs.get("pk"), publisher=request.user) form = forms.AppForm(instance=app) initParam["app_id"] = app.id initParam["app_type"] = app.app_type initParam["app_status"] = app.status # For Additional Info if flag == 3: attachmentSize = string.atoi(common.getSystemParam(key="attachment_size", default=50000000)) initParam["attachmentSize"] = attachmentSize / 1000000 initParam["attachments"] = appModels.Attachment.objects.filter(app_id=app.id) # For App Verification if flag == 7: initParam["verify_token"] = app.verify_token # For App Attributes if flag == 1.2: appInfos = appModels.AppInfo.objects.filter(app_id=app.id) if appInfos: initParam["appInfoForm"] = forms.AppInfoForm(instance=appInfos[0]) # For Payment if flag == 6: initParam["discount_rate"] = common.getSystemParam(key="discount_rate", default=1) initParam["serviceItems"] = orderModels.ServiceItem.objects.filter(end_date__gte=datetime.datetime.now()) serviceDetails = orderModels.ServiceDetail.objects.filter(app_id=app.id).order_by("-pk") sn = kwargs.get("sn", None) if sn and sn != "new": # For query service detail by sn. serviceDetail = get_object_or_404(orderModels.ServiceDetail, app_id=app.id, sn=sn) initParam["selectItems"] = serviceDetail.serviceitem.all() initParam["serviceDetail"] = serviceDetail initParam["amount"] = serviceDetail.amount elif (sn is None or sn == "") and serviceDetails: # For query the latest payment. The rule: Publisher just has one unpaid payment. initParam["selectItems"] = serviceDetails[0].serviceitem.all() initParam["serviceDetail"] = serviceDetails[0] initParam["amount"] = serviceDetails[0].amount else: # Create the new payment. amount = 0 serviceItems = orderModels.ServiceItem.objects.filter( is_basic_service=True, end_date__gte=datetime.datetime.now() ) for serviceItem in serviceItems: amount += serviceItem.price initParam["amount"] = amount # Get app Nav status. appNavStatus(app=app, initParam=initParam) # Create or update app. if request.method == "POST": form = forms.AppForm(request.POST) saveMethod = kwargs.pop("saveMethod", None) if form.is_valid() and saveMethod: result = saveMethod(request, form, app, initParam=initParam) if result: return result userDetails = usersettingModels.UserDetail.objects.filter(user=request.user) if userDetails: initParam["developer_status"] = userDetails[0].developer_status # Initial data initParam["form"] = form if flag == 3: initParam["attachmentForm"] = forms.AttachmentForm() if flag == 1.1: initParam["apps"] = appModels.App.objects.filter(publisher=request.user, status=1).order_by("create_time") return render_to_response(kwargs.get("backPage"), initParam, context_instance=RequestContext(request))
def saveService(request, form, model, *args, **kwargs): """Save the third register page - Service.""" if model is None: return None initParam = kwargs.get('initParam') sn = request.POST.get('sn') if sn: serviceDetail = get_object_or_404(orderModels.ServiceDetail, app_id=model.id, sn=sn) serviceDetail.serviceitem.clear() else: #Check if there is the unpaid payment, before create the new one. serviceDetails = model.servicedetail_set.filter(is_payed=False) if serviceDetails: serviceDetail = serviceDetails[0] serviceDetail.serviceitem.clear() else: #Create the new service detail. serviceDetail = orderModels.ServiceDetail() serviceDetail.app_id = model.id serviceDetail.is_payed = False serviceDetail.sn = datetime.datetime.now().strftime('%Y%m%d%H%M%S') serviceDetail.save() #Save service items amount = 0 for id in request.POST.getlist('serviceItem_id'): try: serviceItem = orderModels.ServiceItem.objects.get(id=id) amount += serviceItem.price serviceDetail.serviceitem.add(serviceItem) except orderModels.ServiceItem.DoesNotExist: return None #Update amount value discount_rate = common.getSystemParam(key='discount_rate', default=1) serviceDetail.actual_amount = string.atof(discount_rate) * amount serviceDetail.amount = amount serviceDetail.save() #Check if the app is verified before check out. if not model.is_verified: initParam['payment_msg'] = _( 'Your app is not verified at the moment. Please goto next step and click \'App Verification\' to request verification.' ) initParam['selectItems'] = serviceDetail.serviceitem.all() initParam['serviceDetail'] = serviceDetail initParam['amount'] = serviceDetail.amount return None #Check if user's payment account is set. acceptGateway = paymentModels.AcceptGateway.objects.filter( user_id=request.user.id, is_active=True, is_default=True).count() if acceptGateway == 0: #Go back this page, after payment account setting. next = '/'.join([ 'order/checkout', str(model.id), str(serviceDetail.id), str(serviceDetail.sn) ]) #redirect payment account setting page. page_url = '/'.join(['/usersetting/payment-setting', next]) return redirect(page_url) return redirect( reverse(initParam.get('nextPage'), kwargs={ 'app_id': model.id, 'service_id': serviceDetail.id, 'service_sn': serviceDetail.sn }))
def saveService(request, form, model, *args, **kwargs): """Save the third register page - Service.""" if model is None: return None initParam = kwargs.get("initParam") sn = request.POST.get("sn") if sn: serviceDetail = get_object_or_404(orderModels.ServiceDetail, app_id=model.id, sn=sn) serviceDetail.serviceitem.clear() else: # Check if there is the unpaid payment, before create the new one. serviceDetails = model.servicedetail_set.filter(is_payed=False) if serviceDetails: serviceDetail = serviceDetails[0] serviceDetail.serviceitem.clear() else: # Create the new service detail. serviceDetail = orderModels.ServiceDetail() serviceDetail.app_id = model.id serviceDetail.is_payed = False serviceDetail.sn = datetime.datetime.now().strftime("%Y%m%d%H%M%S") serviceDetail.save() # Save service items amount = 0 for id in request.POST.getlist("serviceItem_id"): try: serviceItem = orderModels.ServiceItem.objects.get(id=id) amount += serviceItem.price serviceDetail.serviceitem.add(serviceItem) except orderModels.ServiceItem.DoesNotExist: return None # Update amount value discount_rate = common.getSystemParam(key="discount_rate", default=1) serviceDetail.actual_amount = string.atof(discount_rate) * amount serviceDetail.amount = amount serviceDetail.save() # Check if the app is verified before check out. if not model.is_verified: initParam["payment_msg"] = _( "Your app is not verified at the moment. Please goto next step and click 'App Verification' to request verification." ) initParam["selectItems"] = serviceDetail.serviceitem.all() initParam["serviceDetail"] = serviceDetail initParam["amount"] = serviceDetail.amount return None # Check if user's payment account is set. acceptGateway = paymentModels.AcceptGateway.objects.filter( user_id=request.user.id, is_active=True, is_default=True ).count() if acceptGateway == 0: # Go back this page, after payment account setting. next = "/".join(["order/checkout", str(model.id), str(serviceDetail.id), str(serviceDetail.sn)]) # redirect payment account setting page. page_url = "/".join(["/usersetting/payment-setting", next]) return redirect(page_url) return redirect( reverse( initParam.get("nextPage"), kwargs={"app_id": model.id, "service_id": serviceDetail.id, "service_sn": serviceDetail.sn}, ) )
def registerApp(request, *args, **kwargs): """The common function for create, update app information.""" app = None # initParam maybe save error message, when validate failed. initParam = kwargs.copy() flag = kwargs.get('flag') form = forms.AppForm() #Initial data if kwargs.get('pk'): app = get_object_or_404(appModels.App, pk=kwargs.get('pk'), publisher=request.user) form = forms.AppForm(instance=app) initParam['app_id'] = app.id initParam['app_type'] = app.app_type initParam['app_status'] = app.status #For Additional Info if flag == 3: attachmentSize = string.atoi( common.getSystemParam(key='attachment_size', default=50000000)) initParam['attachmentSize'] = attachmentSize / 1000000 initParam['attachments'] = appModels.Attachment.objects.filter( app_id=app.id) #For App Verification if flag == 7: initParam['verify_token'] = app.verify_token #For App Attributes if flag == 1.2: appInfos = appModels.AppInfo.objects.filter(app_id=app.id) if appInfos: initParam['appInfoForm'] = forms.AppInfoForm( instance=appInfos[0]) #For Payment if flag == 6: initParam['discount_rate'] = common.getSystemParam( key='discount_rate', default=1) initParam['serviceItems'] = orderModels.ServiceItem.objects.filter( end_date__gte=datetime.datetime.now()) serviceDetails = orderModels.ServiceDetail.objects.filter( app_id=app.id).order_by('-pk') sn = kwargs.get('sn', None) if sn and sn != 'new': #For query service detail by sn. serviceDetail = get_object_or_404(orderModels.ServiceDetail, app_id=app.id, sn=sn) initParam['selectItems'] = serviceDetail.serviceitem.all() initParam['serviceDetail'] = serviceDetail initParam['amount'] = serviceDetail.amount elif (sn is None or sn == '') and serviceDetails: #For query the latest payment. The rule: Publisher just has one unpaid payment. initParam['selectItems'] = serviceDetails[0].serviceitem.all() initParam['serviceDetail'] = serviceDetails[0] initParam['amount'] = serviceDetails[0].amount else: #Create the new payment. amount = 0 serviceItems = orderModels.ServiceItem.objects.filter( is_basic_service=True, end_date__gte=datetime.datetime.now()) for serviceItem in serviceItems: amount += serviceItem.price initParam['amount'] = amount #Get app Nav status. appNavStatus(app=app, initParam=initParam) #Create or update app. if request.method == "POST": form = forms.AppForm(request.POST) saveMethod = kwargs.pop('saveMethod', None) if form.is_valid() and saveMethod: result = saveMethod(request, form, app, initParam=initParam) if result: return result userDetails = usersettingModels.UserDetail.objects.filter( user=request.user) if userDetails: initParam['developer_status'] = userDetails[0].developer_status #Initial data initParam['form'] = form if flag == 3: initParam['attachmentForm'] = forms.AttachmentForm() if flag == 1.1: initParam['apps'] = appModels.App.objects.filter( publisher=request.user, status=1).order_by('create_time') return render_to_response(kwargs.get('backPage'), initParam, context_instance=RequestContext(request))
def tradeNow(request, *args, **kwargs): """Trade app.""" initParam = {} app = get_object_or_404(appModels.App, pk=kwargs.get('app_id'), publisher_id=request.user.id) user = get_object_or_404(User, pk=kwargs.get('buyer_id')) bid = get_object_or_404(bidModels.Bidding, pk=kwargs.get('bid_id'), buyer_id=user.id, app_id=app.id, status=1) initParam['app'] = app initParam['user'] = user initParam['bid'] = bid transactions = models.Transaction.objects.filter(app_id=app.id, seller_id=request.user.id, is_active=True) if transactions: transaction = transactions[0] else: transaction = models.Transaction() transaction.app = app transaction.status = 1 transaction.seller = request.user transaction.is_active = True transaction.save() #Remind that seller has 7 days to trade now, if bid price is more than reserve price. cur_time = datetime.datetime.now() if transaction.status == 1 and app.status != 1 and app.end_date <= cur_time and bid.price >= app.reserve_price: if transaction.end_time is None: paid_expiry_date = string.atoi( common.getSystemParam(key='sell_expiry_date', default=7)) transaction.end_time = app.end_date + datetime.timedelta( days=paid_expiry_date) transaction.save() if transaction.end_time > cur_time: initParam['time_remaining'] = time.mktime( time.strptime(str(transaction.end_time), '%Y-%m-%d %H:%M:%S')) initParam['is_expiry_date'] = False else: initParam['is_expiry_date'] = True initParam['transaction'] = transaction if request.method == 'POST': if transaction and transaction.status != 1: initParam['error_msg'] = _( 'You have traded with buyer %(param)s, can not trade again.' ) % { 'param': user.username } else: if transaction is None: transaction = models.Transaction() transaction.app = app transaction.seller = request.user transaction.is_active = True transaction.status = 2 transaction.buyer = user transaction.price = bid.price paid_expiry_date = string.atoi( common.getSystemParam(key='paid_expiry_date', default=7)) transaction.end_time = cur_time + datetime.timedelta( days=paid_expiry_date) transaction.buy_type = 2 transaction.save() #Log transaction transactionsLog = models.TransactionLog() transactionsLog.transaction = transaction transactionsLog.app = transaction.app transactionsLog.status = transaction.status transactionsLog.seller = transaction.seller transactionsLog.buyer = transaction.buyer transactionsLog.price = transaction.price transactionsLog.buy_type = transaction.buy_type transactionsLog.save() #Update app status and end_date if app.status == 2: app.status = 3 app.end_date = cur_time app.save() #Send the email of pay to buyer notificationViews.tradeNowInformBuyerPayEmail(request, app=app, user=user) return redirect( reverse('transaction:trade_action', kwargs={ 'action': 'sell', 'app_id': app.id, 'user_id': request.user.id })) return render_to_response('transaction/trade_now.html', initParam, context_instance=RequestContext(request))
def tradeNow(request, *args, **kwargs): """Trade app.""" initParam = {} app = get_object_or_404(appModels.App, pk=kwargs.get('app_id'), publisher_id=request.user.id) user = get_object_or_404(User, pk=kwargs.get('buyer_id')) bid = get_object_or_404(bidModels.Bidding, pk=kwargs.get('bid_id'), buyer_id=user.id, app_id=app.id, status=1) initParam['app'] = app initParam['user'] = user initParam['bid'] = bid transactions = models.Transaction.objects.filter(app_id=app.id, seller_id=request.user.id, is_active=True) if transactions: transaction = transactions[0] else: transaction = models.Transaction() transaction.app = app transaction.status = 1 transaction.seller = request.user transaction.is_active = True transaction.save() #Remind that seller has 7 days to trade now, if bid price is more than reserve price. cur_time = datetime.datetime.now() if transaction.status == 1 and app.status != 1 and app.end_date <= cur_time and bid.price >= app.reserve_price: if transaction.end_time is None: paid_expiry_date = string.atoi(common.getSystemParam(key='sell_expiry_date', default=7)) transaction.end_time = app.end_date + datetime.timedelta(days=paid_expiry_date) transaction.save() if transaction.end_time > cur_time: initParam['time_remaining'] = time.mktime(time.strptime(str(transaction.end_time), '%Y-%m-%d %H:%M:%S')) initParam['is_expiry_date'] = False else: initParam['is_expiry_date'] = True initParam['transaction'] = transaction if request.method == 'POST': if transaction and transaction.status != 1: initParam['error_msg'] = _('You have traded with buyer %(param)s, can not trade again.') % {'param': user.username} else: if transaction is None: transaction = models.Transaction() transaction.app = app transaction.seller = request.user transaction.is_active = True transaction.status = 2 transaction.buyer = user transaction.price = bid.price paid_expiry_date = string.atoi(common.getSystemParam(key='paid_expiry_date', default=7)) transaction.end_time = cur_time + datetime.timedelta(days=paid_expiry_date) transaction.buy_type = 2 transaction.save() #Log transaction transactionsLog = models.TransactionLog() transactionsLog.transaction = transaction transactionsLog.app = transaction.app transactionsLog.status = transaction.status transactionsLog.seller = transaction.seller transactionsLog.buyer = transaction.buyer transactionsLog.price = transaction.price transactionsLog.buy_type = transaction.buy_type transactionsLog.save() #Update app status and end_date if app.status == 2: app.status = 3 app.end_date = cur_time app.save() #Send the email of pay to buyer notificationViews.tradeNowInformBuyerPayEmail(request, app=app, user=user) return redirect(reverse('transaction:trade_action', kwargs={'action': 'sell', 'app_id': app.id, 'user_id': request.user.id})) return render_to_response('transaction/trade_now.html', initParam, context_instance=RequestContext(request))
def taskForBuyUnpaid(*args, **kwargs): """ The task will be done in at schedule time, such as: every hour. Do something, if buy still unpaid after 7 days of paid_expiry_date set in system-param table. 1. Change transaction is_active from True to False. 2. Buyer will be subtracted 50 credit point, and put into blacklist. 3. Buyer's all bidding status is changed from approved to rejected.(Note: All bidding for this buyer.) 4. Send email to buyer.(The email: 1.Subtract his 50 credit point; 2.Put him into blacklist.) 5. Send email to seller.(The email: 1.Seller may choice the buyer bidding with second max price to trade again; 2.The unpaid buyer has been put into blacklist.) 6. Send email to new buyer bidding with second max price. (The email: 1. He is the max bidding one now; 2. Seller will trade with you later.) """ points = string.atoi( common.getSystemParam(key='cp_no_closed_trade', default=50)) templates_buyer = notificationModels.NotificationTemplate.objects.filter( name='buyer_unpaid_inform_buyer') templates_seller = notificationModels.NotificationTemplate.objects.filter( name='buyer_unpaid_inform_seller') templates_second_buyer = notificationModels.NotificationTemplate.objects.filter( name='buyer_unpaid_inform_second_buyer') templates_seller_no_bidding = notificationModels.NotificationTemplate.objects.filter( name='buyer_unpaid_inform_seller_no_bidding') transactions = txnModels.Transaction.objects.filter( is_active=True, status=2, end_time__lte=datetime.datetime.now()) massEmailThread = email.MassEmailThread() for transaction in transactions: transaction.is_active = False transaction.save() creditViews.decreaseCreditPoint(user=transaction.buyer, point=points, type=1, ref_id=transaction.id) bidModels.Bidding.objects.filter( app_id=transaction.app.id, buyer_id=transaction.buyer.id).update(status=False) if templates_buyer: subject = templates_buyer[0].subject message = templates_buyer[0].template.replace( '{param1}', transaction.buyer.username) massEmailThread.addEmailData( subject=subject, message=message, recipient_list=[transaction.buyer.email]) bidding = bidModels.Bidding.objects.filter(app_id=transaction.app.id, status=1).order_by('-price') if bidding: if templates_seller: subject = templates_seller[0].subject message = templates_seller[0].template.replace( '{param1}', transaction.seller.username).replace( '{param2}', transaction.buyer.username) massEmailThread.addEmailData( subject=subject, message=message, recipient_list=[transaction.seller.email]) if templates_second_buyer: subject = templates_second_buyer[0].subject message = templates_second_buyer[0].template.replace( '{param1}', bidding[0].buyer.username).replace( '{param2}', transaction.app.app_name) massEmailThread.addEmailData( subject=subject, message=message, recipient_list=[bidding[0].buyer.email]) else: if templates_seller_no_bidding: subject = templates_seller_no_bidding[0].subject message = templates_seller_no_bidding[0].template.replace( '{param1}', transaction.seller.username) massEmailThread.addEmailData( subject=subject, message=message, recipient_list=[transaction.seller.email]) massEmailThread.start() return None
def checkout(request, *args, **kwargs): """checkout for service detail payment.""" initParam = {'begin_date': None} app_id = kwargs.get('app_id') service_id = kwargs.get('service_id') service_sn = kwargs.get('service_sn') initParam['select'] = request.POST.get('select') user = get_object_or_404(User, pk=request.user.id, username=request.user.username) app = get_object_or_404(appModels.App, pk=app_id, publisher_id=user.id) serviceDetail = get_object_or_404(models.ServiceDetail, pk=service_id, app_id=app_id, sn=service_sn) #Init data service_expiry_date = string.atoi(common.getSystemParam(key='service_expiry_date', default=31)) initParam['service_expiry_date'] = service_expiry_date acceptGateways = user.acceptgateway_set.filter(is_active=True, is_default=True) serviceDetails = models.ServiceDetail.objects.filter(app_id=app_id, is_payed=True, end_date__gte=datetime.datetime.now().strftime('%Y-%m-%d')).order_by('-pk') if serviceDetails: initParam['begin_date'] = serviceDetails[0].end_date serviceDetail.start_date = serviceDetails[0].end_date else: serviceDetail.start_date = datetime.datetime.now() serviceDetail.end_date = datetime.datetime.now() + datetime.timedelta(days=service_expiry_date) initParam['currency'] = app.currency.currency if acceptGateways: initParam['acceptGateway'] = acceptGateways[0] initParam['discount_rate'] = common.getSystemParam(key='discount_rate', default=1) if request.method == "POST": form = forms.ServiceDetailForm(request.POST) if form.is_valid(): days = (form.cleaned_data['end_date'] - form.cleaned_data['start_date']).days if serviceDetail.is_payed: initParam['order_error'] = _('The payment is paid.') elif len(acceptGateways) == 0: initParam['order_error'] = _('The gateway is required.Please choice gateway.') elif (initParam['begin_date'] and form.cleaned_data['start_date'] < initParam['begin_date']) or days != service_expiry_date: initParam['order_error'] = _('Service date is not correct.') else: form.save(commit=False) serviceDetail.start_date = form.cleaned_data['start_date'] serviceDetail.end_date = form.cleaned_data['end_date'] serviceDetail.save() if serviceDetail.actual_amount <= 0: if checkOutSuccess(request, serviceDetail=serviceDetail): initParam['msg'] = _('The payment is successful.') initParam['success_page'] = '/'.join([common.getHttpHeader(request), 'query/app-detail', str(app.id)]) initParam['success_page_msg'] = 'App Detail' log.info(_('Seller %(param1)s has paid service fee - %(param2)s with service detail id %(param3)s.') % {'param1': request.user.username, 'param2': serviceDetail.actual_amount, 'param3': serviceDetail.id}) return render_to_response('payment/paypal_success.html', initParam, context_instance=RequestContext(request)) else: initParam['order_error'] = _('The payment is failed. Please payment again.') else: #Invoke payment method - payment for service detail initParam['serviceDetail_id'] = serviceDetail.id initParam['amount'] = serviceDetail.actual_amount initParam['DESC'] = 'Service fee on AppsWalk.' initParam['PAYMENTREQUEST_0_DESC'] = 'Service fee for App %(param1)s of user %(param2)s on AppsWalk.' % {'param1':app.app_name, 'param2':user.username} initParam['ITEMAMT'] = serviceDetail.actual_amount initParam['L_NAME0'] = 'Service fee on AppsWalk' initParam['L_DESC0'] = 'Service fee for App %(param1)s' % {'param1':app.app_name} initParam['L_AMT0'] = serviceDetail.actual_amount initParam['L_QTY0'] = 1 initParam['gateway'] = 'paypal' #The needed operation method in payment. initParam['executeMethod'] = kwargs.get('executeMethod') #The back page, when payment has error. if request.session.get('back_page', None): del request.session['back_page'] if request.session.get('back_page_msg', None): del request.session['back_page_msg'] request.session['back_page'] = '/'.join([common.getHttpHeader(request), 'seller/payment', str(app.id)]) request.session['back_page_msg'] = 'Payment' #The success return page, when payment finish. if request.session.get('success_page', None): del request.session['success_page'] if request.session.get('success_page_msg', None): del request.session['success_page_msg'] request.session['success_page'] = '/'.join([common.getHttpHeader(request), 'query/app-detail', str(app.id)]) request.session['success_page_msg'] = 'App Detail' return paymentViews.payment(request, initParam=initParam) #Init data initParam['form'] = forms.ServiceDetailForm(instance=serviceDetail) return render_to_response('order/checkout.html', initParam, context_instance=RequestContext(request))
log.error( _('App store link %(param)s is not correct.') % {'param': app_store_link}) log.error(e.message) return None #Save app data if model is None: model = form.save(commit=False) #New app, and init some data model.publisher = appModels.User.objects.get(id=request.user.id) model.store_type = 1 model.status = 1 model.source_code = True model.unique_sell = True currency_id = common.getSystemParam(key='currency', default=1) model.currency = get_object_or_404(appModels.Currency, pk=currency_id) model.minimum_bid = common.getSystemParam(key='minimum_bid', default=10) token_len = common.getSystemParam(key='token_len', default=10) model.verify_token = ''.join( random.sample(string.ascii_letters + string.digits, string.atoi(token_len))) model.is_verified = False else: model.title = title model.app_store_link = app_store_link model.app_type = app_type model.rating = result.get('averageUserRating', 0) model.platform_version = result.get('version', None) model.apple_id = result.get('trackId', None)
def checkServiceDateForApps(*args, **kwargs): """ The task will be done every hour. Do something, when the app service date is ending. 1. App status will be changed from published to closed. 2. Send email of expiry date to seller.(The email: 1.Service end; 2.Seller can trade now.) """ # current_date = datetime.datetime.combine(datetime.date.today(), datetime.time()) # next_date = datetime.datetime.combine(datetime.date.today() + datetime.timedelta(days=1), datetime.time()) # apps = appModels.App.objects.filter(status=2, end_date__gte=current_date, end_date__lt=next_date) apps = appModels.App.objects.filter(status=2, end_date__lte=datetime.datetime.now()) massEmailThread = email.MassEmailThread() for app in apps: app.status = 3 app.save() max_price = app.bidding_set.filter(status=1).aggregate(Max('price')) current_price = max_price.get('price__max', 0) #If bidding price is more than max price, seller has 7 days to trade or else seller can not trade it. if app.reserve_price and app.reserve_price <= current_price: bids = bidModels.Bidding.objects.filter(app_id=app.id, price=current_price, status=1) transactions = app.transaction_set.filter(is_active=True) if transactions: transaction = transactions[0] else: transaction = txnModels.Transaction() transaction.status = 1 transaction.app = app transaction.is_active = True paid_expiry_date = string.atoi( common.getSystemParam(key='sell_expiry_date', default=7)) transaction.end_time = app.end_date + datetime.timedelta( days=paid_expiry_date) transaction.save() transactionsLog = txnModels.TransactionLog() transactionsLog.transaction = transaction transactionsLog.app = app transactionsLog.status = 1 transactionsLog.save() templates = notificationModels.NotificationTemplate.objects.filter( name='service_end_inform_seller') if templates: subject = templates[0].subject.replace('{param1}', bids[0].buyer.username) message = templates[0].template.replace( '{param1}', app.publisher.username).replace('{param2}', app.app_name) massEmailThread.addEmailData( subject=subject, message=message, recipient_list=[app.publisher.email]) else: templates = notificationModels.NotificationTemplate.objects.filter( name='service_end_inform_seller_lt_reserve_price') if templates: subject = templates[0].subject.replace('{param1}', app.app_name) message = templates[0].template.replace( '{param1}', app.publisher.username) massEmailThread.addEmailData( subject=subject, message=message, recipient_list=[app.publisher.email]) massEmailThread.start() return None
def createMessage(request, *args, **kwargs): """User from inbox page, send messages page and app detail page, reply or send message.""" initParam = {} username = kwargs.get("username") user_id = kwargs.get("user_id") type = kwargs.get("type", 1) msg_id = kwargs.get("msg_id") msg_action = kwargs.get("msg_action") if msg_action and (msg_action == "reply" or msg_action == "send"): initParam["msg_action"] = msg_action else: raise Http404 user = get_object_or_404(User, pk=request.user.id, username=request.user.username) receiver = get_object_or_404(User, pk=user_id, username=username) if msg_id: if msg_action == "reply": message = get_object_or_404(messageModels.Message, pk=msg_id, sender_id=receiver.id, receiver_id=user.id) if msg_action == "send": message = get_object_or_404(messageModels.Message, pk=msg_id, sender_id=user.id, receiver_id=receiver.id) initParam["msg_id"] = message.id initParam["sender"] = user initParam["receiver"] = receiver initParam["type"] = type initParam["next"] = request.GET.get("next", None) initParam["page"] = request.GET.get("page", 1) initParam["attachmentForm"] = messageForms.AttachmentForm() attachmentSize = string.atof(common.getSystemParam(key="attachment_size", default=50000000)) initParam["attachmentSize"] = attachmentSize / 1000000 message = messageViews.sendMessage(request, initParam=initParam) if message: messages.info(request, _("Send message successfully.")) # For job, log number of apply the job. if initParam["type"] == "6" and initParam["next"] is not None: offerId = initParam["next"].split("/")[3] offers = offerModels.Offer.objects.filter(pk=offerId, publisher_id=user_id) if offers: offerRecord = offers[0].offerrecord if offerRecord is not None: offerRecord.apply_count += 1 else: offerRecord = offerModels.OfferRecord() offerRecord.offer = offers[0] offerRecord.view_count = 0 offerRecord.apply_count = 1 offerRecord.save() pathList = request.FILES.getlist("path") if pathList: maxNum = common.getSystemParam(key="max_num_attachment", default=50) attachments = messageModels.Attachment.objects.filter(message_id=message.id) if len(pathList) + len(attachments) > string.atoi(maxNum): initParam["attachmentError"] = _("The attachment number can not be more than %(number)s.") % { "number": maxNum[0].value } return render_to_response( "dashboard/create_message.html", initParam, context_instance=RequestContext(request) ) for path in pathList: attachment = messageModels.Attachment(path=path) attachment.name = path.name if path.name.endswith(".txt") and path.content_type == "text/plain": attachment.type = 1 elif path.content_type.startswith("image"): attachment.type = 2 elif path.name.endswith(".pdf") and path.content_type == "application/pdf": attachment.type = 3 elif path.name.endswith(".doc") and path.content_type == "application/msword": attachment.type = 4 elif ( path.name.endswith(".docx") and path.content_type == "application/vnd.openxmlformats-officedocument.wordprocessingml.document" ): attachment.type = 4 elif path.name.endswith(".xls") and path.content_type == "application/vnd.ms-excel": attachment.type = 4 elif ( path.name.endswith(".xlsx") and path.content_type == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ): attachment.type = 4 elif path.name.endswith(".ppt") and path.content_type == "application/vnd.ms-powerpoint": attachment.type = 4 elif ( path.name.endswith(".pptx") and path.content_type == "application/vnd.openxmlformats-officedocument.presentationml.presentation" ): attachment.type = 4 else: initParam["attachmentError"] = _("The file type of %(param)s does not supported.") % { "param": path.name } return render_to_response( "dashboard/create_message.html", initParam, context_instance=RequestContext(request) ) if path.size > attachmentSize: initParam["attachmentError"] = _("The file can not be more than %(number)M.") % { "number": attachmentSize / 000000 } return render_to_response( "dashboard/create_message.html", initParam, context_instance=RequestContext(request) ) attachment.message = message attachment.save() notificationViews.sendNewMessageEmail(request, message=message) return redirect(reverse("dashboard:sent_messages")) return render_to_response("dashboard/create_message.html", initParam, context_instance=RequestContext(request))
def mostActive(request): """Query the apps info in most active page.""" initParam = {} page = request.GET.get('page', 1) revenue_min = request.GET.get('revenue_min', None) category = request.GET.get('category', None) subcategory = request.GET.get('subcategory', None) monetize = request.GET.get('monetize', None) device = request.GET.get('device', None) seller = request.GET.get('seller', None) currency_id = common.getSystemParam(key='currency', default=2) initParam['currency'] = get_object_or_404(appModels.Currency, pk=currency_id) app_id = [] bids = bidModels.Bidding.objects.values('app').annotate(bid_num=Count('app')).order_by('-bid_num') for bid in bids: app_id.append(bid.get('app')) if revenue_min is None and category is None and subcategory is None and monetize is None and device is None and seller is None: apps = appModels.App.objects.filter(pk__in=app_id, app_type=1, status=2, end_date__gt=datetime.datetime.now()) #Revenue Part REVENUE_LIST = [2000, 1000, 500, 100, 0] initParam['revenue_list'] = [] for i in range(len(REVENUE_LIST)): if i == 0: temp_apps = appModels.App.objects.filter(pk__in=app_id, app_type=1, status=2, end_date__gt=datetime.datetime.now(), revenue__gte=REVENUE_LIST[i]) else: temp_apps = appModels.App.objects.filter(pk__in=app_id, app_type=1, status=2, end_date__gt=datetime.datetime.now(), revenue__lt=REVENUE_LIST[i-1], revenue__gte=REVENUE_LIST[i]) if revenue_min and string.atoi(revenue_min) == REVENUE_LIST[i]: apps = temp_apps title = _('Revenue(%(param)s/Month)') % {'param': initParam['currency'].currency} subTitle = _('Over %(param)s') % {'param': revenue_min} initParam['query_tile'] = [title, subTitle, ''.join(['?revenue_min=', revenue_min])] initParam['revenue_list'].append([REVENUE_LIST[i], len(temp_apps)]) #Monetize Part initParam['monetize_list'] = [] if monetize: monetizeModel = get_object_or_404(appModels.Monetize, pk=monetize) for temp_monetize in appModels.Monetize.objects.all(): if monetize and monetizeModel == temp_monetize: apps = monetizeModel.app_set.filter(pk__in=app_id, app_type=1, status=2, end_date__gt=datetime.datetime.now()) initParam['monetize_list'].append([temp_monetize, len(apps)]) initParam['query_tile'] = [_('Monetize'), temp_monetize.method, ''.join(['?monetize=', monetize])] else: initParam['monetize_list'].append([temp_monetize, temp_monetize.app_set.filter( pk__in=app_id, app_type=1, status=2, end_date__gt=datetime.datetime.now()).count()]) #Device Part initParam['device_list'] = [] if device: deviceModel = get_object_or_404(appModels.Device, pk=device) for tem_device in appModels.Device.objects.all(): if device and deviceModel == tem_device: apps = deviceModel.app_set.filter(pk__in=app_id, app_type=1, status=2, end_date__gt=datetime.datetime.now()) initParam['device_list'].append([tem_device, len(apps)]) initParam['query_tile'] = [_('Device'), tem_device.device, ''.join(['?device=', device])] else: initParam['device_list'].append([tem_device, tem_device.app_set.filter( pk__in=app_id, app_type=1, status=2, end_date__gt=datetime.datetime.now()).count()]) #Category Part initParam['category_list'] = [] if category: categoryModel = get_object_or_404(appModels.Category, apple_id=category) for temp_category in appModels.Category.objects.all(): if category and categoryModel == temp_category: apps = categoryModel.app_set.filter(pk__in=app_id, app_type=1, status=2, end_date__gt=datetime.datetime.now()) initParam['category_list'].append([temp_category, len(apps)]) initParam['query_tile'] = [_('Category'), temp_category.name, ''.join(['?category=', category])] else: initParam['category_list'].append([temp_category, temp_category.app_set.filter( pk__in=app_id, app_type=1, status=2, end_date__gt=datetime.datetime.now()).count()]) common.sortWithIndexLie(initParam['category_list'], 1, order='desc') #For sort app by bid numbers app_map = {} for app in apps: app_map[str(app.id)] = app new_app = [] for id in app_id: if app_map.get(str(id)): new_app.append(app_map.get(str(id))) #Query data initParam['apps'] = queryAppsWithPaginator(request, page=page, apps=new_app) return render_to_response('query/listing_base.html', initParam, context_instance=RequestContext(request))
def onePriceBuy(request, *args, **kwargs): """ Buyer pay by clicking button 'Buy It Now with 10 USD' in app detail page. Note: url include app_id, and publisher_id, because of preventing user to cheat. """ initParam = {} app_id = kwargs.get('app_id') publisher_id = kwargs.get('publisher_id') app = get_object_or_404(appModels.App, pk=app_id, publisher_id=publisher_id, status=2) transactions = models.Transaction.objects.filter(app_id=app.id, seller_id=publisher_id, buyer_id=request.user.id, status=1) if transactions: transaction = transactions[0] else: transaction = models.Transaction() transaction.app = app transaction.seller = app.publisher transaction.status = 1 transaction.is_active = False transaction.buyer = request.user transaction.price = app.one_price transaction.buy_type = 1 paid_expiry_date = string.atoi( common.getSystemParam(key='paid_expiry_date', default=7)) transaction.end_time = datetime.datetime.now() + datetime.timedelta( days=paid_expiry_date) transaction.save() #Log transaction transactionsLog = models.TransactionLog() transactionsLog.transaction = transaction transactionsLog.app = transaction.app transactionsLog.status = transaction.status transactionsLog.buyer = transaction.buyer transactionsLog.price = transaction.price transactionsLog.buy_type = transaction.buy_type transactionsLog.save() initParam['transaction'] = transaction initParam['page_source'] = 'one-price' if transaction.end_time > datetime.datetime.now(): initParam['time_remaining'] = time.mktime( time.strptime(transaction.end_time.strftime('%Y-%m-%d %H:%M:%S'), '%Y-%m-%d %H:%M:%S')) else: initParam['time_remaining'] = "Deal Closed" initParam['paid_expiry'] = True if request.method == 'POST': #Buyer credit point judge for bidding. min_cp = common.getSystemParam(key='min_cp_for_bid', default=50) cp = creditViews.getUserCreditPoint(user=request.user) if cp == -1 or cp < string.atoi(min_cp): initParam['error_msg'] = _( 'You are not allowed to buy, because your credit points is too low.' ) else: #Buyser pay for app. txn_fee_pct = string.atof( common.getSystemParam(key='txn_fee_pct', default=0.01)) initParam['currency'] = app.currency.currency initParam['appsWalk_account'] = settings.APPSWALK_ACCOUNT initParam['gateway'] = 'paypal' gateways = paymentModels.Gateway.objects.filter( name__iexact=initParam.get('gateway')) acceptGateways = paymentModels.AcceptGateway.objects.filter( user_id=transaction.seller.id, type_id=gateways[0].id, is_active=True) initParam['seller_account'] = acceptGateways[0].value initParam['appsWalk_amount'] = app.one_price * txn_fee_pct initParam['seller_amount'] = app.one_price * (1 - txn_fee_pct) initParam['txn_id'] = transaction.id #The needed operation method in pay. initParam['executeMethod'] = updateTransaction #The back page, when pay has error. if request.session.get('back_page', None): del request.session['back_page'] if request.session.get('back_page_msg', None): del request.session['back_page_msg'] request.session['back_page'] = '/'.join([ common.getHttpHeader(request), 'query/app-detail', str(app.id) ]) request.session['back_page_msg'] = 'App Detail' #The success return page, when pay finish. if request.session.get('success_page', None): del request.session['success_page'] if request.session.get('success_page_msg', None): del request.session['success_page_msg'] request.session['success_page'] = '/'.join([ common.getHttpHeader(request), 'transaction/trade-action/buy', str(app.id), str(request.user.id) ]) request.session['success_page_msg'] = 'Trade Action' return paymentViews.pay(request, initParam=initParam) return render_to_response('transaction/one_price_buy.html', initParam, context_instance=RequestContext(request))
def justSold(request): initParam = {} page = request.GET.get('page', 1) revenue_min = request.GET.get('revenue_min', None) category = request.GET.get('category', None) subcategory = request.GET.get('subcategory', None) monetize = request.GET.get('monetize', None) device = request.GET.get('device', None) seller = request.GET.get('seller', None) currency_id = common.getSystemParam(key='currency', default=2) initParam['currency'] = get_object_or_404(appModels.Currency, pk=currency_id) app_id = txnModels.Transaction.objects.filter(status__gte=2, is_active=True).values_list('app_id') if revenue_min is None and category is None and subcategory is None and monetize is None and device is None and seller is None: apps = appModels.App.objects.filter(pk__in=app_id, app_type=1) #Revenue Part REVENUE_LIST = [2000, 1000, 500, 100, 0] initParam['revenue_list'] = [] for i in range(len(REVENUE_LIST)): if i == 0: temp_apps = appModels.App.objects.filter(pk__in=app_id, app_type=1, revenue__gte=REVENUE_LIST[i]) else: temp_apps = appModels.App.objects.filter(pk__in=app_id, app_type=1, revenue__lt=REVENUE_LIST[i-1], revenue__gte=REVENUE_LIST[i]) if revenue_min and string.atoi(revenue_min) == REVENUE_LIST[i]: apps = temp_apps title = _('Revenue(%(param)s/Month)') % {'param': initParam['currency'].currency} subTitle = _('Over %(param)s') % {'param': revenue_min} initParam['query_tile'] = [title, subTitle, ''.join(['?revenue_min=', revenue_min])] initParam['revenue_list'].append([REVENUE_LIST[i], len(temp_apps)]) #Monetize Part initParam['monetize_list'] = [] if monetize: monetizeModel = get_object_or_404(appModels.Monetize, pk=monetize) for temp_monetize in appModels.Monetize.objects.all(): if monetize and monetizeModel == temp_monetize: apps = monetizeModel.app_set.filter(pk__in=app_id, app_type=1) initParam['monetize_list'].append([temp_monetize, len(apps)]) initParam['query_tile'] = [_('Monetize'), temp_monetize.method, ''.join(['?monetize=', monetize])] else: initParam['monetize_list'].append([temp_monetize, temp_monetize.app_set.filter(pk__in=app_id, app_type=1).count()]) #Device Part initParam['device_list'] = [] if device: deviceModel = get_object_or_404(appModels.Device, pk=device) for tem_device in appModels.Device.objects.all(): if device and deviceModel == tem_device: apps = deviceModel.app_set.filter(pk__in=app_id, app_type=1) initParam['device_list'].append([tem_device, len(apps)]) initParam['query_tile'] = [_('Device'), tem_device.device, ''.join(['?device=', device])] else: initParam['device_list'].append([tem_device, tem_device.app_set.filter(pk__in=app_id, app_type=1).count()]) #Category Part initParam['category_list'] = [] if category: categoryModel = get_object_or_404(appModels.Category, apple_id=category) for temp_category in appModels.Category.objects.all(): if category and categoryModel == temp_category: apps = categoryModel.app_set.filter(pk__in=app_id, app_type=1) initParam['category_list'].append([temp_category, len(apps)]) initParam['query_tile'] = [_('Category'), temp_category.name, ''.join(['?category=', category])] else: initParam['category_list'].append([temp_category, temp_category.app_set.filter(pk__in=app_id, app_type=1).count()]) common.sortWithIndexLie(initParam['category_list'], 1, order='desc') #Query data initParam['apps'] = queryAppsWithPaginator(request, page=page, apps=apps) return render_to_response('query/listing_base.html', initParam, context_instance=RequestContext(request))
def onePriceBuy(request, *args, **kwargs): """ Buyer pay by clicking button 'Buy It Now with 10 USD' in app detail page. Note: url include app_id, and publisher_id, because of preventing user to cheat. """ initParam = {} app_id = kwargs.get('app_id') publisher_id = kwargs.get('publisher_id') app = get_object_or_404(appModels.App, pk=app_id, publisher_id=publisher_id, status=2) transactions = models.Transaction.objects.filter(app_id=app.id, seller_id=publisher_id, buyer_id=request.user.id, status=1) if transactions: transaction = transactions[0] else: transaction = models.Transaction() transaction.app = app transaction.seller = app.publisher transaction.status = 1 transaction.is_active = False transaction.buyer = request.user transaction.price = app.one_price transaction.buy_type = 1 paid_expiry_date = string.atoi(common.getSystemParam(key='paid_expiry_date', default=7)) transaction.end_time = datetime.datetime.now() + datetime.timedelta(days=paid_expiry_date) transaction.save() #Log transaction transactionsLog = models.TransactionLog() transactionsLog.transaction = transaction transactionsLog.app = transaction.app transactionsLog.status = transaction.status transactionsLog.buyer = transaction.buyer transactionsLog.price = transaction.price transactionsLog.buy_type = transaction.buy_type transactionsLog.save() initParam['transaction'] = transaction initParam['page_source'] = 'one-price' if transaction.end_time > datetime.datetime.now(): initParam['time_remaining'] = time.mktime(time.strptime(transaction.end_time.strftime('%Y-%m-%d %H:%M:%S'), '%Y-%m-%d %H:%M:%S')) else: initParam['time_remaining'] = "Deal Closed" initParam['paid_expiry'] = True if request.method == 'POST': #Buyer credit point judge for bidding. min_cp = common.getSystemParam(key='min_cp_for_bid', default=50) cp = creditViews.getUserCreditPoint(user=request.user) if cp == -1 or cp < string.atoi(min_cp): initParam['error_msg'] = _('You are not allowed to buy, because your credit points is too low.') else: #Buyser pay for app. txn_fee_pct = string.atof(common.getSystemParam(key='txn_fee_pct', default=0.01)) initParam['currency'] = app.currency.currency initParam['appsWalk_account'] = settings.APPSWALK_ACCOUNT initParam['gateway'] = 'paypal' gateways = paymentModels.Gateway.objects.filter(name__iexact=initParam.get('gateway')) acceptGateways = paymentModels.AcceptGateway.objects.filter(user_id=transaction.seller.id, type_id=gateways[0].id, is_active=True) initParam['seller_account'] = acceptGateways[0].value initParam['appsWalk_amount'] = app.one_price * txn_fee_pct initParam['seller_amount'] = app.one_price * (1 - txn_fee_pct) initParam['txn_id'] = transaction.id #The needed operation method in pay. initParam['executeMethod'] = updateTransaction #The back page, when pay has error. if request.session.get('back_page', None): del request.session['back_page'] if request.session.get('back_page_msg', None): del request.session['back_page_msg'] request.session['back_page'] = '/'.join([common.getHttpHeader(request), 'query/app-detail', str(app.id)]) request.session['back_page_msg'] = 'App Detail' #The success return page, when pay finish. if request.session.get('success_page', None): del request.session['success_page'] if request.session.get('success_page_msg', None): del request.session['success_page_msg'] request.session['success_page'] = '/'.join([common.getHttpHeader(request), 'transaction/trade-action/buy', str(app.id), str(request.user.id)]) request.session['success_page_msg'] = 'Trade Action' return paymentViews.pay(request, initParam=initParam) return render_to_response('transaction/one_price_buy.html', initParam, context_instance=RequestContext(request))
def listFeatured(request, *args, **kwargs): """Query the apps info in featured page.""" initParam = {} page = request.GET.get('page', 1) revenue_min = request.GET.get('revenue_min', None) category = request.GET.get('category', None) subcategory = request.GET.get('subcategory', None) monetize = request.GET.get('monetize', None) device = request.GET.get('device', None) seller = request.GET.get('seller', None) currency_id = common.getSystemParam(key='currency', default=2) initParam['currency'] = get_object_or_404(appModels.Currency, pk=currency_id) if revenue_min is None and category is None and subcategory is None and monetize is None and device is None and seller is None: apps = appModels.App.objects.filter(app_type=1, status=2, end_date__gt=datetime.datetime.now()) #Revenue Part REVENUE_LIST = [2000, 1000, 500, 100, 0] initParam['revenue_list'] = [] for i in range(len(REVENUE_LIST)): if i == 0: temp_apps = appModels.App.objects.filter(app_type=1, status=2, end_date__gt=datetime.datetime.now(), revenue__gte=REVENUE_LIST[i]).order_by('status') else: temp_apps = appModels.App.objects.filter(app_type=1, status=2, end_date__gt=datetime.datetime.now(), revenue__lt=REVENUE_LIST[i-1], revenue__gte=REVENUE_LIST[i]).order_by('status') if revenue_min and string.atoi(revenue_min) == REVENUE_LIST[i]: apps = temp_apps title = _('Revenue(%(param)s/Month)') % {'param': initParam['currency'].currency} subTitle = _('Over %(param)s') % {'param': revenue_min} initParam['query_tile'] = [title, subTitle, ''.join(['?revenue_min=', revenue_min])] initParam['revenue_list'].append([REVENUE_LIST[i], len(temp_apps)]) #Monetize Part initParam['monetize_list'] = [] if monetize: monetizeModel = get_object_or_404(appModels.Monetize, pk=monetize) for temp_monetize in appModels.Monetize.objects.all(): if monetize and monetizeModel == temp_monetize: apps = monetizeModel.app_set.filter(app_type=1, status=2, end_date__gt=datetime.datetime.now()) initParam['monetize_list'].append([temp_monetize, len(apps)]) initParam['query_tile'] = [_('Monetize'), temp_monetize.method, ''.join(['?monetize=', monetize])] else: initParam['monetize_list'].append([temp_monetize, temp_monetize.app_set.filter(app_type=1, status=2, end_date__gt=datetime.datetime.now()).count()]) #Device Part initParam['device_list'] = [] if device: deviceModel = get_object_or_404(appModels.Device, pk=device) for tem_device in appModels.Device.objects.all(): if device and deviceModel == tem_device: apps = deviceModel.app_set.filter(app_type=1, status=2, end_date__gt=datetime.datetime.now()) initParam['device_list'].append([tem_device, len(apps)]) initParam['query_tile'] = [_('Device'), tem_device.device, ''.join(['?device=', device])] else: initParam['device_list'].append([tem_device, tem_device.app_set.filter(app_type=1, status=2, end_date__gt=datetime.datetime.now()).count()]) #Category Part initParam['category_list'] = [] if category: categoryModel = get_object_or_404(appModels.Category, apple_id=category) for temp_category in appModels.Category.objects.all(): if category and categoryModel == temp_category: apps = categoryModel.app_set.filter(app_type=1, status=2, end_date__gt=datetime.datetime.now()) initParam['category_list'].append([temp_category, len(apps)]) initParam['query_tile'] = [_('Category'), temp_category.name, ''.join(['?category=', category])] else: initParam['category_list'].append([temp_category, temp_category.app_set.filter(app_type=1, status=2, end_date__gt=datetime.datetime.now()).count()]) common.sortWithIndexLie(initParam['category_list'], 1, order='desc') #SubCategory Part from app detail page. if subcategory: subcategoryModel = get_object_or_404(appModels.SubCategory, apple_id=subcategory) apps = subcategoryModel.app_set.filter(app_type=1).exclude(status=1).order_by('status') initParam['query_tile'] = ['SubCategory', subcategoryModel.name, ''.join(['?subcategory=', subcategory])] #Seller part from watch sellers page. if seller: sellerModel = get_object_or_404(User, pk=seller) apps = sellerModel.app_set.filter(app_type=1).exclude(status=1).order_by('status') initParam['query_tile'] = ['Seller', sellerModel.username, ''.join(['?seller=', seller])] #Query data initParam['apps'] = queryAppsWithPaginator(request, page=page, apps=apps) return render_to_response('query/listing_base.html', initParam, context_instance=RequestContext(request))
def createBid(request, *args, **kwargs): if kwargs.get('pk'): initParam = {} app = get_object_or_404(appModels.App, pk=kwargs.get('pk')) initParam['app'] = app initParam['appInfo'] = app.appinfo initBidInfo(request, app=app, initParam=initParam)#For below code using the value #Do something, when the time is app end date. if app.status == 2 and initParam['begin_bid']: initParam['is_callback'] = True if request.method == "POST": biddingForm = forms.BiddingForm(request.POST) #Buyer credit point judge for bidding. min_cp = common.getSystemParam(key='min_cp_for_bid', default=50) cp = creditViews.getUserCreditPoint(user=request.user) if cp == -1 or cp < string.atoi(min_cp): initParam['biddingForm'] = biddingForm initParam['bid_error'] = _('You are not allowed to place bid, because your low credit points. But you can buy additional credit points.') else: if biddingForm.is_valid(): #From bid_create.html if 'yes' == request.POST.get('bid_create'): bid = biddingForm.save(commit=False) if datetime.datetime.now() > app.end_date: initParam['biddingForm'] = biddingForm initParam['bid_error'] = _('The bidding is closed, you can not bid.') elif bid.price >= initParam.get('bid_price'): bid.app = app bid.buyer = request.user bid.status = 1 # userPrivateItem = userSettingModels.UserPrivateItem.objects.filter(key='is_bid_approved') # if userPrivateItem: # is_bid_approved = userSettingModels.UserPrivateSetting.objects.filter(user_id=app.publisher.id, user_private_item_id=userPrivateItem[0]) # #Need be verified by app publisher. # if is_bid_approved and is_bid_approved[0].value == 'True': # bid.status = 3 bid.save() #Send the message to app publisher send_message = request.POST.get('send_message') if send_message and send_message == 'yes': if sendMessage(request, initParam=initParam): notificationViews.sendNewBidEmail(request, bid=bid, app=app) return redirect(reverse('bid:bid_list', kwargs={'pk': app.id})) else: initParam['biddingForm'] = biddingForm initParam['bid_error'] = initParam['message_error'] else: notificationViews.sendNewBidEmail(request, bid=bid, app=app) return redirect(reverse('bid:bid_list', kwargs={'pk': app.id})) else: initParam['biddingForm'] = biddingForm initParam['bid_error'] = _('The new bid has been submitted.') #From list_detail.html else: initParam['biddingForm'] = biddingForm initParam['sender'] = request.user initParam['receiver'] = app.publisher transactions = txnModels.Transaction.objects.filter(app_id=app.id).exclude(status=1) if transactions: initParam['transaction'] = transactions[0] #Comment the message # sendMessage(request, initParam=initParam) queryViews.shareSocial(request, initParam=initParam, app=app) return render_to_response('bid/bid_create.html', initParam, context_instance=RequestContext(request)) raise Http404
def checkout(request, *args, **kwargs): """checkout for service detail payment.""" initParam = {'begin_date': None} app_id = kwargs.get('app_id') service_id = kwargs.get('service_id') service_sn = kwargs.get('service_sn') initParam['select'] = request.POST.get('select') user = get_object_or_404(User, pk=request.user.id, username=request.user.username) app = get_object_or_404(appModels.App, pk=app_id, publisher_id=user.id) serviceDetail = get_object_or_404(models.ServiceDetail, pk=service_id, app_id=app_id, sn=service_sn) #Init data service_expiry_date = string.atoi( common.getSystemParam(key='service_expiry_date', default=31)) initParam['service_expiry_date'] = service_expiry_date acceptGateways = user.acceptgateway_set.filter(is_active=True, is_default=True) serviceDetails = models.ServiceDetail.objects.filter( app_id=app_id, is_payed=True, end_date__gte=datetime.datetime.now().strftime('%Y-%m-%d')).order_by( '-pk') if serviceDetails: initParam['begin_date'] = serviceDetails[0].end_date serviceDetail.start_date = serviceDetails[0].end_date else: serviceDetail.start_date = datetime.datetime.now() serviceDetail.end_date = datetime.datetime.now() + datetime.timedelta( days=service_expiry_date) initParam['currency'] = app.currency.currency if acceptGateways: initParam['acceptGateway'] = acceptGateways[0] initParam['discount_rate'] = common.getSystemParam(key='discount_rate', default=1) if request.method == "POST": form = forms.ServiceDetailForm(request.POST) if form.is_valid(): days = (form.cleaned_data['end_date'] - form.cleaned_data['start_date']).days if serviceDetail.is_payed: initParam['order_error'] = _('The payment is paid.') elif len(acceptGateways) == 0: initParam['order_error'] = _( 'The gateway is required.Please choice gateway.') elif (initParam['begin_date'] and form.cleaned_data['start_date'] < initParam['begin_date']) or days != service_expiry_date: initParam['order_error'] = _('Service date is not correct.') else: form.save(commit=False) serviceDetail.start_date = form.cleaned_data['start_date'] serviceDetail.end_date = form.cleaned_data['end_date'] serviceDetail.save() if serviceDetail.actual_amount <= 0: if checkOutSuccess(request, serviceDetail=serviceDetail): initParam['msg'] = _('The payment is successful.') initParam['success_page'] = '/'.join([ common.getHttpHeader(request), 'query/app-detail', str(app.id) ]) initParam['success_page_msg'] = 'App Detail' log.info( _('Seller %(param1)s has paid service fee - %(param2)s with service detail id %(param3)s.' ) % { 'param1': request.user.username, 'param2': serviceDetail.actual_amount, 'param3': serviceDetail.id }) return render_to_response( 'payment/paypal_success.html', initParam, context_instance=RequestContext(request)) else: initParam['order_error'] = _( 'The payment is failed. Please payment again.') else: #Invoke payment method - payment for service detail initParam['serviceDetail_id'] = serviceDetail.id initParam['amount'] = serviceDetail.actual_amount initParam['DESC'] = 'Service fee on AppsWalk.' initParam[ 'PAYMENTREQUEST_0_DESC'] = 'Service fee for App %(param1)s of user %(param2)s on AppsWalk.' % { 'param1': app.app_name, 'param2': user.username } initParam['ITEMAMT'] = serviceDetail.actual_amount initParam['L_NAME0'] = 'Service fee on AppsWalk' initParam['L_DESC0'] = 'Service fee for App %(param1)s' % { 'param1': app.app_name } initParam['L_AMT0'] = serviceDetail.actual_amount initParam['L_QTY0'] = 1 initParam['gateway'] = 'paypal' #The needed operation method in payment. initParam['executeMethod'] = kwargs.get('executeMethod') #The back page, when payment has error. if request.session.get('back_page', None): del request.session['back_page'] if request.session.get('back_page_msg', None): del request.session['back_page_msg'] request.session['back_page'] = '/'.join([ common.getHttpHeader(request), 'seller/payment', str(app.id) ]) request.session['back_page_msg'] = 'Payment' #The success return page, when payment finish. if request.session.get('success_page', None): del request.session['success_page'] if request.session.get('success_page_msg', None): del request.session['success_page_msg'] request.session['success_page'] = '/'.join([ common.getHttpHeader(request), 'query/app-detail', str(app.id) ]) request.session['success_page_msg'] = 'App Detail' return paymentViews.payment(request, initParam=initParam) #Init data initParam['form'] = forms.ServiceDetailForm(instance=serviceDetail) return render_to_response('order/checkout.html', initParam, context_instance=RequestContext(request))