//Встает в ближайшую работающую кассу без очереди //TODO Если очередь полная, то встать где-то рядом с последним и ждать //TODO Занимать очередь в той, где меньше народа или ближайшей void FindWorkingCashBox() { CashBox[] cashBoxArray = gameController.cashBoxArray; float minimalDistance = 1000; foreach (var box in cashBoxArray) { if (box.ready && !box.fullQueue) { float distance = Vector3.Distance(box.transform.position, transform.position); if (distance < minimalDistance) { minimalDistanceCashBox = box; minimalDistance = distance; } } else { //Если не нашел ни одной работающей кассы cashBoxObject = null; cashBox = null; } } if (cashBoxArray.Length > 0) { cashBox = minimalDistanceCashBox; cashBoxObject = minimalDistanceCashBox.gameObject; } }
void Update() { agent.speed = startSpeed * shop.GetTimeScale(); agent.angularSpeed = startAngularSpeed * shop.GetTimeScale(); if (GetTargetComplated(2f, BuyPointPosition) && Stay == BuyerStay.ChangeProducts) { if (ChangeTime < 0f) { ChangedCashBox = shop.GetOptimalCashBox(); agent.destination = ChangedCashBox.transform.position; Stay = BuyerStay.GoToCashBox; return; } if (BuyPointSwithTimeout < 0f) { GoToBuyPoint(); BuyPointSwithTimeout = BuyPointSwithTime; } ChangeTime -= Time.deltaTime * shop.GetTimeScale(); BuyPointSwithTimeout -= Time.deltaTime * shop.GetTimeScale(); } else if (Stay == BuyerStay.GoToCashBox && !WasInCashBox && GetTargetComplated(2f, ChangedCashBox.transform.position)) { ChangedCashBox.Queue.Add(this); WasInCashBox = true; } else if (Stay == BuyerStay.GoToHome && GetTargetComplated(2f, HomePosition)) { Destroy(gameObject); } }
static void Main(string[] args) { Mike first_item = new Mike("Coloss", 500, 43, "Cotton", "TTX", 3); Milk second_item = new Milk("Health", 200, new DateTime(2015, 7, 20), 20, 30); Jeans third_item = new Jeans("K_jeans", 3000, 40, "cotton", "Santa Maria", true); Cleaner fourth_item = new Cleaner("Superclean", 300, 4.5, "plate"); Sausage fifth_item = new SausageBuilder().setCompany("MeatGodman").setName("MeatHealth").setPrice(200); SimpleBuyer buyer_one = new SimpleBuyer(1); buyer_one.AddItemIntoCart(first_item); buyer_one.AddItemIntoCart(second_item); buyer_one.AddItemIntoCart(third_item); buyer_one.AddItemIntoCart(fourth_item); CashBox cash_box = CashBox.getInstance(); cash_box.setState(cashBoxState.WORK); cash_box.addCustomerToQueue(buyer_one); cash_box.processCustomer(); Console.ReadLine(); }
private void SendAllDocumentsForCashMachine(CashBox cashBox, IList <PreparedReceiptNode> receiptNodes, CancellationToken token) { logger.Info($"Отправка чеков для фискального регистратора №{cashBox.Id}"); using (HttpClient httpClient = GetHttpClient(cashBox)) { if (!ConnectToCashBox(httpClient, cashBox)) { return; } int i = 1; foreach (var receiptNode in receiptNodes) { if (token.IsCancellationRequested) { return; } var orderId = receiptNode.CashReceipt.Order.Id; logger.Info($"Отправка документа №{orderId} на сервер фискализации №{cashBox.Id} ({i++}/{receiptNodes.Count})..."); receiptNode.SendResultCode = SendDocument(httpClient, receiptNode.SalesDocumentDTO, orderId); } } }
public CashBox Create(int customerId, AssetTypeModel.EnterMode enterMode, int cashBoxID) { // Create new cashbox int areaId = (int)AssetAreaId.Cashbox; CashBox cashbox = new CashBox() { //CashBoxID = NextCashBoxId(customerId), // CashBoxID = cashBoxID, CustomerID = customerId, CashBoxName = "", CashBoxSeq = cashBoxID, CashBoxState = (int)AssetStateType.Pending, CashBoxType = (int)MeterGroups.Cashbox, OperationalStatus = (int)OperationalStatusType.Inactive, OperationalStatusTime = DateTime.Now, CashBoxLocationTypeId = (int)Duncan.PEMS.Entities.Enumerations.CashBoxLocationType.Inventory }; PemsEntities.CashBoxes.Add(cashbox); PemsEntities.SaveChanges(); // Create audit record. Audit(cashbox); return(cashbox); }
public JsonResult _UpdateCashbox(CashBox ins) { CashBox ins2 = CBRep.Update(ins); //...Repopulate Grid... return(Json(new GridModel(CBRep.GetAllCashBox()))); }
public override void Interact(Client client) { CashBox freeCashBox = _freeCashBoxes.Dequeue(); client.AddTarget(freeCashBox); client.AddTarget(_supermarketExit); client.NextTarget(); }
public void ResetCashBox() { cashBox = null; cashBoxObject = null; inQueue = false; positionInQueue = 0; minimalDistanceCashBox = null; }
public void DoesAddMachineBalanceWork() { // Arrange CashBox test = new CashBox(); // Act test.AddMachineBalance(1); // Assert Assert.AreEqual(test.MachineBalance, 1); }
public void NotAddingNegativeBalance() { // Arrange CashBox test = new CashBox(); // Act test.AddCustomerBalance("-1"); // Assert Assert.AreEqual(test.CustomerBalance, 0); }
public void DoesAddBalanceWork() { // Arrange CashBox test = new CashBox(); // Act test.AddCustomerBalance("1"); // Assert Assert.AreEqual(test.CustomerBalance, 1); }
public void NotAddingNonInteger() { // Arrange CashBox test = new CashBox(); // Act test.AddCustomerBalance("1.5"); // Assert Assert.AreEqual(0, test.CustomerBalance); }
public void Properties() { // Arrange CashBox test = new CashBox(); // Act // Assert Assert.AreEqual(0, test.CustomerBalance); }
public void NotAddingString() { // Arrange CashBox test = new CashBox(); // Act test.AddCustomerBalance("a"); // Assert Assert.AreEqual(0, test.CustomerBalance); }
/// <summary> /// Gets the next CashBox Id from the table [CashBox]. This will be used /// in the creation of a new CashBox. Called from <see cref="CashboxFactory.Create"/> and <see cref="CashboxFactory.Clone(int, int, Int64)"/>. /// It is entirely possible that this is the first CashBox so check for this case. /// </summary> /// <param name="customerId">The customer id</param> /// <returns>Next available CashBox id</returns> private int NextCashBoxId(int customerId) { int nextId = 1; CashBox cashBox = PemsEntities.CashBoxes.FirstOrDefault(m => m.CustomerID == customerId); if (cashBox != null) { nextId = PemsEntities.CashBoxes.Where(m => m.CustomerID == customerId).Max(m => m.CashBoxSeq) + 1; } return(nextId); }
private void CashBoxInit(ref CashBox cashBox, short orgId, short staffId, decimal cashOut, decimal yestodayCashBox) { cashBox.InCash = 0; cashBox.Cheque = 0; cashBox.BankDepoist = 0; cashBox.Cheque = 0; cashBox.Eftpos = 0; cashBox.OutCash = cashOut; cashBox.YesterdayCash = yestodayCashBox; cashBox.OrgId = orgId; cashBox.StaffId = staffId; cashBox.CloseTime = toNZTimezone(DateTime.UtcNow); cashBox.CashBoxDate = toNZTimezone(DateTime.UtcNow).Date; }
private bool ConnectToCashBox(HttpClient httpClient, CashBox cashBox) { try { logger.Info($"Авторизация и проверка фискального регистратора №{cashBox.Id} ({cashBox.RetailPointName})..."); HttpResponseMessage response = httpClient.GetAsync(fiscalizationStatusAddress).Result; if (!response.IsSuccessStatusCode) { logger.Warn($"Провал. Нет ответа от сервиса. Регистратор №{cashBox.Id}"); return(false); } var finscalizatorStatusResponse = response.Content.ReadAsAsync <FinscalizatorStatusResponseDTO>().Result; if (finscalizatorStatusResponse == null) { logger.Warn($"Провал. Нет удалось прочитать ответ от сервиса. Регистратор №{cashBox.Id}"); return(false); } switch (finscalizatorStatusResponse.Status) { case FiscalRegistratorStatus.Ready: logger.Info($"Соединение с фискальным накопителем №{cashBox.Id} установлено и его состояние позволяет фискализировать чеки."); return(true); case FiscalRegistratorStatus.Failed: logger.Warn($"Проблемы получения статуса фискального накопителя №{cashBox.Id}. " + "Этот статус не препятствует добавлению документов для фискализации. " + "Все документы будут добавлены в очередь на сервере и дождутся момента когда касса будет в состоянии их фискализировать."); return(true); case FiscalRegistratorStatus.Associated: logger.Warn("Клиент успешно связан с розничной точкой, " + $"но касса еще ни разу не вышла на связь и не сообщила свое состояние. " + $"Отправка чеков для фискального регистратора №{cashBox.Id} отменена"); return(false); default: logger.Warn($"Провал с сообщением: \"{finscalizatorStatusResponse.Message}\". " + $"Отправка чеков для фискального регистратора №{cashBox.Id} отменена"); return(false); } } catch (Exception ex) { logger.Error(ex, $"Ошибка при авторизации и проверки фискального регистратора №{cashBox.Id}"); return(false); } }
static void Main(string[] args) { CashBox pri = new CashBox(); pri.addProductToCheck(new CandyBelochka()); pri.addProductToCheck(new CandyBelochka()); pri.addProductToCheck(new CandyBelochka()); pri.addProductToCheck(new CandyBelochka()); pri.addProductToCheck(new CandyBelochka()); pri.addProductToCheck(new CandyBelochka()); pri.addProductToCheck(new MilkProstokvashino()); Console.WriteLine(pri.getPrice()); Console.ReadLine(); }
public RentPoint AddRentPoint(string name, string adress, Employee employee, decimal money) { if (money < 0) { throw new ArgumentOutOfRangeException(nameof(money)); } CashBox cashbox = new CashBox(money); Safe safe = new Safe(); RentPoint rentPoint = new RentPoint(name, adress, employee, safe, cashbox); _rentPointRepository.Add(rentPoint); return(rentPoint); }
public void ResetWorkPlace() { Debug.Log("reset workplace on " + gameObject.name); if (cashBoxObject) { cashBox.haveCashier = false; cashBox.ready = false; stayingAtCashBox = false; readyToSell = false; cashBox.ClearQueue(); cashBox.CalculateQueue(); cashBox = null; cashBoxObject = null; minimalDistanceCashBox = null; } gameController.CalcCashboxes(); }
private HttpClient GetHttpClient(CashBox cashBox) { var authentication = new AuthenticationHeaderValue( "Basic", Convert.ToBase64String( Encoding.GetEncoding("ISO-8859-1").GetBytes($"{cashBox.UserName}:{cashBox.Password}") ) ); var httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Accept.Clear(); httpClient.DefaultRequestHeaders.Authorization = authentication; httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); httpClient.BaseAddress = new Uri(baseAddress); httpClient.Timeout = TimeSpan.FromSeconds(60); return(httpClient); }
public async Task <ActionResult> PostCashBox(short orgId, short staffId, decimal cashOut, DateTime date) { Result <Object> result = new Result <object>(); //var payments = new List<Payment>(); // dynamic cashBox = new Object(); CashBox cashBox = new CashBox(); try { short?[] staffOrg = await _ablemusicContext.StaffOrg.Where(s => s.OrgId == orgId). Select(s => s.StaffId).ToArrayAsync(); Payment[] payments = await _ablemusicContext.Payment.Where(p => staffOrg.Contains(p.StaffId) && p.CreatedAt.Value.Date == date.Date).ToArrayAsync(); var cashBoxCheck = await _ablemusicContext.CashBox.Where(p => orgId == p.OrgId && p.CloseTime.Value.Date == date.Date).FirstOrDefaultAsync(); if (cashBoxCheck != null) { throw new Exception("Today's Daily Log Has Already Been Submitted"); } decimal yestodayCashBox; yestodayCashBox = getLastCashBox(orgId, staffOrg, date); CashBoxInit(ref cashBox, orgId, staffId, cashOut, yestodayCashBox); paymentToCashBox(ref cashBox, payments); setCashBoxToday(ref cashBox); await _ablemusicContext.AddAsync(cashBox); await _ablemusicContext.SaveChangesAsync(); result.Data = cashBox; return(Ok(result)); } catch (Exception ex) { result.IsSuccess = false; result.ErrorMessage = ex.Message; return(BadRequest(result)); } }
public RentPoint AddRentPoint(Employee employee, decimal money) { if (employee == null) { throw new ArgumentNullException(nameof(employee)); } if (money < 0) { throw new ArgumentOutOfRangeException(nameof(money)); } CashBox cashbox = new CashBox(money); Safe safe = new Safe(); RentPoint rentPoint = new RentPoint(employee, safe, cashbox); _rentPointRepository.Add(rentPoint); return(rentPoint); }
/// <summary> /// Creates a clone (copy) of the <see cref="CashBox"/> refrenced by <paramref name="assetId"/> and <paramref name="customerId"/>. This cloned /// <see cref="CashBox"/> is written to the [CashBox] table and the [AssetPending] table. /// </summary> /// <param name="customerId">The customer id</param> /// <param name="areaId">The area id (presently not used)</param> /// <param name="assetId">The cashbox id to clone</param> /// <returns>Integer representing the new cashbox id (<see cref="CashBox.CashBoxID"/>)</returns> private int Clone(int customerId, int areaId, Int64 assetId) { // Get original cashbox // Since this cashbox exists, this entity should exist also. CashBox cashbox = PemsEntities.CashBoxes.FirstOrDefault(m => m.CashBoxSeq == assetId && m.CustomerID == customerId); // Create a cashbox CashBox newCashbox = new CashBox() { // CashBoxID = NextCashBoxId(customerId), CustomerID = customerId, CashBoxSeq = NextCashBoxId(customerId), //cashbox.CashBoxSeq, CashBoxState = (int)AssetStateType.Pending, CashBoxModel = cashbox.CashBoxModel, CashBoxType = cashbox.CashBoxType, OperationalStatus = (int)OperationalStatusType.Inactive, OperationalStatusTime = DateTime.Now, NextPreventativeMaintenance = cashbox.NextPreventativeMaintenance, CashBoxName = "", WarrantyExpiration = cashbox.WarrantyExpiration, CashBoxLocationTypeId = cashbox.CashBoxLocationTypeId }; PemsEntities.CashBoxes.Add(newCashbox); PemsEntities.SaveChanges(); // Set audit records. Audit(newCashbox); // Add AssetPending record (new PendingFactory(ConnectionStringName, Now)).SetImportPending(AssetTypeModel.AssetType.Cashbox, SetToMidnight(Now), AssetStateType.Current, customerId, newCashbox.CashBoxID, (int)AssetStateType.Pending, (int)OperationalStatusType.Inactive, (int)AssetAreaId.Cashbox); return(newCashbox.CashBoxSeq); }
private void OpenCashBox() { if (ConstantValuePool.BizSettingConfig.cashBoxConfig.Enabled) { try { if (ConstantValuePool.BizSettingConfig.cashBoxConfig.IsUsbPort) { string vid = ConstantValuePool.BizSettingConfig.cashBoxConfig.VID; string pid = ConstantValuePool.BizSettingConfig.cashBoxConfig.PID; string endpointId = ConstantValuePool.BizSettingConfig.cashBoxConfig.EndpointID; CashBox.Open(vid, pid, endpointId); } else { string port = ConstantValuePool.BizSettingConfig.cashBoxConfig.Port; if (port.IndexOf("COM", StringComparison.OrdinalIgnoreCase) >= 0 && port.Length > 3) { if (port.Substring(0, 3).ToUpper() == "COM") { string portName = port.Substring(0, 4).ToUpper(); CashBox.Open(portName, 9600, Parity.None, 8, StopBits.One); } } else if (port.IndexOf("LPT", StringComparison.OrdinalIgnoreCase) >= 0 && port.Length > 3) { if (port.Substring(0, 3).ToUpper() == "LPT") { string lptName = port.Substring(0, 4).ToUpper(); CashBox.Open(lptName); } } } } catch (Exception exception) { MessageBox.Show("钱箱打开失败,错误信息:" + exception, "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Error); } } }
public void addProstokvashino5x_addCandyBelochka6x_getPrice110() { // arrange CashBox cashBox = new CashBox(); MilkProstokvashino milk = new MilkProstokvashino(); CandyBelochka candy = new CandyBelochka(); double expected = 110; // act for (int i = 0; i < 5; i++) { cashBox.addProductToCheck(milk); } for (int i = 0; i < 6; i++) { cashBox.addProductToCheck(candy); } double actual = cashBox.getPrice(); //assert Assert.AreEqual(expected, actual); }
private void paymentToCashBox(ref CashBox cashBox, Payment[] payments) { foreach (var payment in payments) { if (payment.PaymentMethod == 1) //cash { cashBox.InCash += payment.Amount; } else if (payment.PaymentMethod == 2) //EftPos { cashBox.Eftpos += payment.Amount; } else if (payment.PaymentMethod == 3) //online Transfer { cashBox.BankDepoist += payment.Amount; } else { cashBox.Cheque += payment.Amount; }; } }
//Ищет ближайшую кассу без кассира void FindFreeCashBox() { //Debug.Log(gameObject.name + " ищет свободную кассу"); CashBox[] cashBoxArray = gameController.cashBoxArray; float minimalDistance = 1000; foreach (var box in cashBoxArray) { if (!box.haveCashier) { float distance = Vector3.Distance(box.transform.position, transform.position); if (distance < minimalDistance) { minimalDistanceCashBox = box; minimalDistance = distance; } } else if (cashBox != box) { cashBoxObject = null; cashBox = null; } } if (cashBoxArray.Length > 0) { cashBox = minimalDistanceCashBox; cashBoxObject = minimalDistanceCashBox.gameObject; } if (!cashBox) { //Если не нашел ни одной свободной кассы } }
private void AddFreeCashBox(CashBox cashBox) { _freeCashBoxes.Enqueue(cashBox); }
private void setCashBoxToday(ref CashBox cashBox) { cashBox.TodayCash = cashBox.YesterdayCash + cashBox.InCash - cashBox.OutCash; }