def int_stall_order_submit(request, content): # get parameters customer_barcode = get_attribute(content, "customer_barcode") collection = get_attribute(content, "collection") # get stall our_stall = get_login_stall(request) # get user try: cus = customer.objects.get(barcode=customer_barcode) except Exception: return error(err_barcode_invalid) orderitems = [] # get order_item's from json try: for entry in collection: # TODO replace the id lookup with get_by_id item = menu_item.objects.get(id=entry['itemid']) quantity = entry['quantity'] remarks = entry['remarks'] orderitems.append( order_item(item=item, quantity=quantity, remarks=remarks)) except Exception as e: return error(err_value_incorrect) # we have order items, call common payment function # place_order returns an error object return error(place_order_to_stall(our_stall, cus, orderitems)) """
def test_method_error(self): '''test for error() method''' ''' must test error.py before ''' err = err_unknown err_msg = 'Testing!' response = json.loads(error(err,err_msg).content) expected = {"err_msg": "Testing!","err_code":1} err1 = err_unknown err_msg1 = None # err_msg = None response1 = json.loads(error(err1,err_msg1).content) expected1 = {"err_msg": "Oops, something went wrong in the server :( debug time","err_code":1} err2 = err_api err_msg2 = 'Testing!' response2 = json.loads(error(err2,err_msg2).content) expected2 = {"err_msg": "Testing!","err_code":2} err3 = err_api err_msg3 = 3 #int type err_msg response3 = json.loads(error(err3,err_msg3).content) expected3 = {"err_msg": 3,"err_code":2} err4 = err_api err_msg4 = '' #string type err_msg, but no value response4 = json.loads(error(err4,err_msg4).content) expected4 = {"err_msg": '',"err_code":2} self.assertEqual(response, expected) self.assertEqual(response1, expected1) self.assertEqual(response2, expected2) self.assertEqual(response3, expected3) self.assertEqual(response4, expected4)
def int_ofs_stall_add(request, content, bypass=False): try: if not bypass: get_login_ofs_manager(request) except Exception: return error(err_no_access_rights) # get parameters name = get_attribute(content, "name") description = get_attribute(content, "description") canteenid = get_attribute(content, "canteen") category = get_attribute(content, "category") prefix = get_attribute(content, "username_prefix") manageruname = prefix + "_mgr" operatoruname = prefix + "_op" #validate canteen availability canobj = get_by_id(canteen, canteenid) # create item if len(stall_user.objects.filter(username=manageruname)) != 0: return error(err_stall_managername) if len(stall_user.objects.filter(username=operatoruname)) != 0: return error(err_stall_operatorname) stcreated = False mgrcreated = False opcreated = False try: newstall = stall( name=name, description=description, canteen=canobj, category=category, username_prefix=prefix, is_activated=True, ) valid_save(newstall) stcreated = True stall_mgr = stall_user(usertype=stall_user.manager, username=manageruname, password="******", stall=newstall) valid_save(stall_mgr) mgrcreated = True stall_op = stall_user(usertype=stall_user.operator, username=operatoruname, password="******", stall=newstall) valid_save(stall_op) opcreated = True except Exception as e: # TODO we should check if e is cams_ex to give more useful info if stcreated and newstall.id > 0: newstall.delte() if mgrcreated and stall_mgr.id > 0: stall_mgr.delete() if opcreated and stall_op.id > 0: stall_op.delete() return error(err_creating_entry) return case1(newstall)
def int_ofs_stall_reset_mgrpwd(request, content): get_login_ofs_manager(request) stallid = get_attribute(content, "stallid") stallobj = get_by_id(stall, stallid) # find mgr try: mgrobj = stall_user.objects.get(username=stallobj.username_prefix + "_mgr") except Exception: return error(err_stall_mgr_notfound) mgrobj.password = "******" mgrobj.save() # guaranteed to be valid return error(err_success)
def int_stall_order_revoke(request, content): print "trying to revoke order" # get parameters orderid = get_attribute(content, "orderid") notify = get_attribute(content, "notify") print orderid # get stall our_stall = get_login_stall(request) # get the order and order items and customer targetorder = get_by_id(order, orderid) if targetorder.is_finished: return error(err_cannot_revoke) targetitems = targetorder.order_item_set.all() targetcus = targetorder.customer totalPrice = calcOrderPrice(targetorder) # inform customer if notify and targetcus.hpnumber != "": print "trying to sms customer" smsItemInfo = "" for entry in targetitems: smsItemInfo += entry.item.name + " x" + str( entry.quantity) + "\n" smsMsg = "CaMS: your order to " + our_stall.name + " (Q no. " + str( targetorder.queue_num ) + ")" + " with these items has been revoked:\n" + smsItemInfo + "$" + str( totalPrice) + " dollars is refunded to your acct." # if msg too long if len(smsMsg) >= 160: smsMsg = "CaMS: your order to " + our_stall.name + " (Q no. " + str( targetorder.queue_num ) + ")" + " has been revoked:\n" + "$" + str( totalPrice) + " dollars is refunded to your acct." # if msg still too long if len(smsMsg) >= 160: smsMsg = "CaMS: your order to " + our_stall.name[:20] + " (Q no. " + str( targetorder.queue_num ) + ")" + " has been revoked:\n" + "$" + str( totalPrice) + " dollars is refunded to your acct." sendSMS(smsMsg, targetcus.hpnumber) # revoke return_queue_number(our_stall.canteen, targetorder.queue_num) targetcus.balance += totalPrice targetcus.save() targetorder.delete() for i in range(len(targetitems) - 1, -1, -1): targetitems[i].delete() # calculate total price return error(err_success)
def int_cus_set_cart(request, content): cus = get_login_payment(request) cart0 = cus.get_default_cart() olditems = [entry for entry in cart0.cart_item_set.all()] collection = get_attribute(content, "collection") successList = [] try: for entry in collection: item = menu_item.objects.get(id=entry['item']) quantity = entry['quantity'] remarks = entry['remarks'] newcitem = cart_item(cart=cart0, item=item, quantity=quantity, remarks=remarks) valid_save(newcitem) successList.append(newcitem) except Exception as e: for entry in successList: entry.delete() return error(err_cus_cart_failed) # clear previous cart items for entry in olditems: entry.delete() return case2(cart0.cart_item_set.all())
def int_stall_menu_item_add(request, content): # get parameters name = get_attribute(content, "name") description = get_attribute(content, "description") price = get_attribute(content, "price") is_available = get_attribute(content, "is_available") is_available_online = get_attribute(content, "is_available_online") promotion = get_attribute(content, "promotion") promotion_until = get_attribute(content, "promotion_until") img_loc = default_img_path if 'newimgid' in content: img_loc = get_newitem_image_path(content['newimgid']) # get stall our_stall = get_login_stall(request) # create item item = menu_item(stall=our_stall, name=name, description=description, price=price, is_available=is_available, is_available_online=is_available_online, is_activated=True, promotion=promotion, promotion_until=promotion_until, img_location=img_loc) valid_save(item) return error(err_success)
def int_ofs_stall_deactivate(request, content): # FIXME need to make sure stall can be deactivated get_login_ofs_manager(request) stallid = get_attribute(content, "stallid") stallobj = get_by_id(stall, stallid) stallobj.is_activated = False stallobj.save() # guaranteed to be valid return error(err_success)
def int_stall_edit(request, content): # get stall our_stall = get_login_stall(request) # get parameters mayset(content, our_stall, 'name') mayset(content, our_stall, 'description') valid_save(our_stall) return error(err_success)
def int_ofs_stall_edit(request, content): #check login get_login_ofs(request) #get parameter name = get_attribute(content, "name") # get object try: stallobj = stall.objects.get(name=name) except Exception: return error(err_missing_obj) # execute mayset(content, stallobj, 'description') mayset(content, stallobj, 'canteen') mayset(content, stallobj, 'category') mayset(content, stallobj, 'is_activated') valid_save(stallobj) return error(err_success)
def request(request): global handlers try: print request.body received = json.loads(request.body) print handlers[received['req_code']].__name__ return handlers[received['req_code']](request, received['content']) except cams_ex as e: return error(e.err_obj, e.err_msg) """
def int_ofs_ofsuser_add(request, content): get_login_ofs_manager(request) # get parameters username = get_attribute(content, "username") password = get_attribute(content, "password") usertype = get_attribute(content, "usertype") name = get_attribute(content, "name") ofsuser = ofs_user.objects.filter(username=username) if len(ofsuser) > 0: return error(err_invalid_info_submitted) #create new ofs user new_ofsuser = ofs_user(username=username, password=password, usertype=usertype, name=name, is_activated=True) valid_save(new_ofsuser) return error(err_success)
def int_ofs_customer_getbybarcode(request, content): #check login get_login_ofs(request) #get parameters barcode = get_attribute(content, "barcode") #execute try: cus1 = customer.objects.get(barcode=barcode) except Exception: return error(err_missing_obj) return case1(cus1)
def int_login(request, content): username = get_attribute(content, "username") password = get_attribute(content, "password") domain = get_attribute(content, "domain") if domain == "customer": usr_acc = customer elif domain == "ofs_user": usr_acc = ofs_user elif domain == "stall_user": usr_acc = stall_user else: return error(err_incorrect_domain) user = usr_acc.objects.filter(username=username, password=password) if len(user) < 1: return error(err_incorrect_login) request.session['logged_in'] = True request.session['username'] = username request.session['user_id'] = user[0].id request.session['user_domain'] = domain return case1(user[0])
def int_ofs_customer_mass_add(request, content): get_login_ofs_manager(request) #get parameters newcuslist = get_attribute(content, "collection") # we need to reverse action if we run into error. save the successful ones # for deletion later success = [] suc_num = 0 try: for entry in newcuslist: cus1 = customer(username=entry['username'], barcode=entry['barcode'], password=entry['password'], usertype=entry['usertype'], balance=0.0, is_activated=True) # validate entry validate_username(cus1.username) validate_barcode(cus1.barcode) validate_password(cus1.password) valid_save(cus1) success.append(cus1) suc_num += 1 except Exception as e: print str(e) for entry in success: entry.delete() errinfo = "" if isinstance(e, cams_ex): errinfo = e.getErrMsg() msg = "Mass creation failed. " + newcuslist[suc_num][ "barcode"] + " has erroneous info" if errinfo: msg += ": " + errinfo return error(err_mass_creation_failed, msg) # build cart for all for cus in success: cus.build_cart() return error(err_success)
def int_ofs_stalluser_add(request, content): get_login_ofs_manager(request) # get parameters username = get_attribute(content, "username") password = get_attribute(content, "password") usertype = get_attribute(content, "usertype") stallid = get_attribute(content, "stall") name = get_attribute(content, "name") # make sure no user with same username stalluser = stall_user.objects.filter(username=username) if len(stalluser) > 0: return error(err_invalid_info_submitted) stallobj = get_by_id(stall, stallid) #create new stall and stall user stalluser = stall_user(username=username, password=password, usertype=usertype, stall=stallobj, name=name, is_activated=True) valid_save(stalluser) return error(err_success)
def int_login_payment(request, content): barcode = get_attribute(content, 'barcode') try: cus = customer.objects.get(barcode=barcode) except: return error(err_vali_badbarcode) request.session['logged_in'] = True request.session['username'] = cus.username request.session['user_id'] = cus.id # we use a payment domain to limit login authority # payment login is checked using get_login_payment() request.session['user_domain'] = 'payment' return case1(cus)
def int_ofs_canteen_setactivated(request, content): #check login get_login_ofs_manager(request) # get parameter canid = get_attribute(content, "canteenid") value = get_attribute(content, "value") canobj = get_by_id(canteen, canid) if not value and len( stall.objects.filter(canteen=canobj, is_activated=True)) > 0: return error(err_canteen_cannotdeact) canobj.is_activated = value valid_save(canobj) return case1(canobj)
def int_ofs_canteen_add(request, content): #check login get_login_ofs_manager(request) # get parameter name = get_attribute(content, "name") description = get_attribute(content, "description") canteens = canteen.objects.filter(name=name) if len(canteens) > 0: return error(err_invalid_info_submitted) newcan = canteen(name=name, description=description) valid_save(newcan) newcan.buildQueueTable() return case1(newcan)
def int_ofs_customer_mass_deactivate(request, content): get_login_ofs_manager(request) delist = get_attribute(content, "collection") barcodeList = [] # grab list of barcode try: for entry in delist: barcodeList.append(entry['barcode']) except Exception: return error(err_api) # verify all records exist try: for entry in barcodeList: cus = customer.objects.get(barcode=entry) except Exception: return error(err_mass_deactivate_notfound) # deactivate them all for entry in barcodeList: cus = customer.objects.get(barcode=entry) cus.is_activated = False cus.save() # guaranteed to be valid return error(err_success)
def int_ofs_customer_refund(request, content): #check login get_login_ofs(request) #get parameter customerid = get_attribute(content, "customerid") #check customer validation try: cus = customer.objects.get(id=customerid, is_activated=True) except Exception: return error(err_missing_obj) #execute oldbalance = cus.balance cus.balance = 0 valid_save(cus) # sms customer to notify smsCustomer(cus, "CaMS: Your account has been refunded $" + str(oldbalance)) return case1(cus)
def int_ofs_customer_get_page(request, content): """divide customer entries into pages, return a specific page""" #check login get_login_ofs_manager(request) try: page_num = int(get_attribute(content, "page_num")) if page_num < 0: raise NameError("Incorrect page number") except NameError as e: return error(err_api, str(e)) #execute # order by cusList = customer.objects.all().order_by("-is_activated", "id") startIndex = page_num * page_size endIndex = (page_num + 1) * page_size if (cusList.count() < endIndex): endIndex = cusList.count() page = cusList[startIndex:endIndex] return case2(page)
def int_ofs_customer_add(request, content): get_login_ofs_manager(request) # get parameters username = get_attribute(content, "username") barcode = get_attribute(content, "barcode") password = get_attribute(content, "password") usertype = get_attribute(content, "usertype") #validate if user is already exist users = customer.objects.filter(username=username) if len(users) > 0: return error(err_invalid_info_submitted) # create item cust1 = customer(username=username, barcode=barcode, password=password, usertype=usertype, balance=0.0, is_activated=True) valid_save(cust1) return case1(cust1)
def int_ofs_customer_topup(request, content): #check login get_login_ofs(request) #get parameter customerid = get_attribute(content, "customerid") value = get_attribute(content, "value") #check customer validation try: cus = customer.objects.get(id=customerid, is_activated=True) except Exception: return error(err_missing_obj) #excute newbalance = float(cus.balance) + float(value) cus.balance = newbalance valid_save(cus) # sms customer to notify smsCustomer( cus, "CaMS: Your account has received a topup of $" + str(value) + ", your current balance is $" + str(newbalance)) return case1(cus)
def testrequest(handler, request, content): try: return handler(request, content) except cams_ex as e: return error(e.err_obj, e.err_msg)
def int_cus_pay_canteen(request, content): cus = get_login_payment(request) canid = get_attribute(content, "canteenid") can = get_by_id(canteen, canid) cart0 = cus.get_default_cart() ciAll = cart0.cart_item_set.all() # get all cart items inside current canteen ciCan = [entry for entry in ciAll if entry.item.stall.canteen == can] ciCanSaved = ciCan[:] if ciCan.count == 0: return error(err_cus_empty_cart) # validate customer has enough balance balance = float(cus.balance) total = 0 for entry in ciCan: total += entry.quantity * float(calcItemPrice(entry.item)) newbalance = balance - total if newbalance < 0: return error(err_insufficient_balance) # multiple errors might come up during payment, keep track of them lowBalance = False # customer's in low balance? errMsg = "" # names of the failed stalls failure = False # if there's any failing payment? success = False # if there's any successful payment? queue_num = 0 # group ciCan by their stalls, and place order one by one stalls = [] # stalls we're done for while len(ciCan) > 0: # grab all items of current stall curStall = ciCan[0].item.stall cistall = [ entry for entry in ciCan if entry.item.stall == curStall ] # turn them into order_item and call payment function oistall = [ order_item(item=ci.item, quantity=ci.quantity, remarks=ci.remarks) for ci in cistall ] # place_order returns an error object err = place_order_to_stall(curStall, cus, oistall) # if it is not success, we'd have to prepare an error message if err[0] != err_success[0]: if errMsg: errMsg += ", " errMsg += curStall.name failure = True else: success = True queue_num = err[2] # if err msg is overwritten, it's an low-balance alert if err[1] != err_success[1]: lowBalance = True # remove cistall from ciCan ciCan = [entry for entry in ciCan if entry.item.stall != curStall] # check errors, and report back if not success: return error(err_payment_allfailed, "Payment to " + errMsg + " all failed") # remove all items in current canteen, and return confirmation msg for entry in ciCanSaved: entry.delete() msg = "Your queue number is " + str(queue_num) if lowBalance: msg += ". Your balance is low, please topup soon" if failure: return error( err_payment_partfailed, "Payment to " + errMsg + "had failed. Payment to the other stalls were successful. " + msg) return error(err_success, "Payment successful. " + msg)
def int_cus_pay(request, content): cus = get_login_payment(request) cart0 = cus.get_default_cart() citems = cart0.cart_item_set.all() if citems.count == 0: return error(err_cus_empty_cart)
def int_logout(request, content): request.session['logged_in'] = False return error(err_success)