Browse Source

Isolate instant stop report from billing

shayne_lo 6 tháng trước cách đây
mục cha
commit
59dc023cc7

+ 1 - 0
EVCB_OCPP.WSServer/HostedProtalServer.cs

@@ -6,6 +6,7 @@ using EVCB_OCPP.WSServer.Helper;
 using EVCB_OCPP.WSServer.Jobs;
 using EVCB_OCPP.WSServer.Message;
 using EVCB_OCPP.WSServer.Service;
+using EVCB_OCPP.WSServer.Service.BusinessService;
 using EVCB_OCPP.WSServer.Service.DbService;
 using EVCB_OCPP.WSServer.Service.WsService;
 using Microsoft.EntityFrameworkCore;

+ 330 - 385
EVCB_OCPP.WSServer/Message/CoreProfileHandler.cs

@@ -22,6 +22,7 @@ using EVCB_OCPP.WSServer.Service.WsService;
 using EVCB_OCPP.Domain.Models.MainDb;
 using EVCB_OCPP.Domain.ConnectionFactory;
 using EVCB_OCPP.WSServer.Service.DbService;
+using EVCB_OCPP.WSServer.Service.BusinessService;
 
 namespace EVCB_OCPP.WSServer.Message;
 
@@ -371,7 +372,7 @@ internal partial class ProfileHandler
                         {
                             //var businessService = BusinessServiceFactory.CreateBusinessService(session.CustomerId.ToString());
                             //var businessService = await serviceProvider.GetService<BusinessServiceFactory>().CreateBusinessService(session.CustomerId.ToString());
-                            var businessService = await businessServiceFactory.CreateBusinessService(session.CustomerId.ToString());
+                            var businessService = await businessServiceFactory.CreateBusinessService(session.CustomerId);
                             var notification = businessService.NotifyFaultStatus(new ErrorDetails()
                             {
                                 ChargeBoxId = session.ChargeBoxId,
@@ -542,7 +543,7 @@ internal partial class ProfileHandler
 
 						int _transactionId = -1;
 
-						var businessService = await businessServiceFactory.CreateBusinessService(session.CustomerId.ToString());
+						var businessService = await businessServiceFactory.CreateBusinessService(session.CustomerId);
 						t0 = timer.ElapsedMilliseconds;
 
 						var _idTagInfo = new IdTagInfo() { expiryDate = DateTime.UtcNow.AddDays(1), status = AuthorizationStatus.Accepted };
@@ -692,7 +693,7 @@ internal partial class ProfileHandler
 						var utcNow = DateTime.UtcNow;
 
 						getDateTimeTime = stopTrasactionTimer.ElapsedMilliseconds;
-						var businessService = await businessServiceFactory.CreateBusinessService(session.CustomerId.ToString());
+						var businessService = await businessServiceFactory.CreateBusinessService(session.CustomerId);
 						getServiceTime = stopTrasactionTimer.ElapsedMilliseconds;
 
 						TransactionRecord transaction;
@@ -896,7 +897,7 @@ internal partial class ProfileHandler
 					{
 						AuthorizeRequest _request = request as AuthorizeRequest;
 
-						var businessService = await businessServiceFactory.CreateBusinessService(session.CustomerId.ToString());
+						var businessService = await businessServiceFactory.CreateBusinessService(session.CustomerId);
 						var confirm = new AuthorizeConfirmation()
 						{
 							idTagInfo = new IdTagInfo() { expiryDate = DateTime.UtcNow.AddDays(1), status = AuthorizationStatus.Accepted }
@@ -978,434 +979,363 @@ internal partial class ProfileHandler
 					{
 						DataTransferConfirmation _confirm = confirm as DataTransferConfirmation;
 						DataTransferRequest _request = _confirm.GetRequest() as DataTransferRequest;
-						using (var db = await maindbContextFactory.CreateDbContextAsync())
-						{
-							var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
-							x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
-							if (operation != null)
-							{
-								operation.FinishedOn = DateTime.UtcNow;
-								operation.Status = 1;//電樁有回覆
-								operation.EvseStatus = (int)_confirm.status;
-								operation.EvseValue = string.IsNullOrEmpty(_confirm.data) ? "" : _confirm.data;
-								await db.SaveChangesAsync();
-							}
 
-							if (_request.messageId == "ID_FirmwareVersion")
-							{
-								var machine = new Machine() { Id = session.MachineId };
-								if (machine != null)
-								{
-									db.ChangeTracker.AutoDetectChangesEnabled = false;
-									//db.Configuration.ValidateOnSaveEnabled = false;
-									db.Machine.Attach(machine);
-									machine.BoardVersions = _confirm.data;
-									db.Entry(machine).Property(x => x.BoardVersions).IsModified = true;
-									await db.SaveChangesAsync();
-								}
-							}
+                        await mainDbService.SetMachineOperateRecordFinished(requestId, session.ChargeBoxId, _confirm.status, _confirm.data);
 
-							if (_request.messageId == "ID_TxEnergy") //計費
-							{
-								if (_confirm.status == DataTransferStatus.Accepted)
-								{
-									decimal couponPoint = 0m;
-									string farewellMessage = string.Empty;
-									string receipt = string.Empty;
-									List<ChargingBill> bill = new List<ChargingBill>();
-									List<ChargingPrice> chargingPrices = new List<ChargingPrice>();
-									var txEnergy = JsonConvert.DeserializeObject<TransactionEnergy>(_confirm.data);
-									var feedto = await db.TransactionRecord.Where(x => x.Id == txEnergy.TxId).Select(x => new { Id = x.Id, ConnectorId = x.ConnectorId, Fee = x.Fee, StopTime = x.StopTime, StartTime = x.StartTime, NotifyPnC = x.NotifyPnC }).FirstOrDefaultAsync();
-									decimal chargedEnergy = 0m;
-
-									if (feedto == null)
-										return result;
-
-									if (string.IsNullOrEmpty(feedto.Fee))
-									{
-										if (feedto.StopTime != GlobalConfig.DefaultNullTime)
-										{
-                                            await mainDbService.InsertOrUpdateTransactionPeriodEnergy(txEnergy.TxId, txEnergy.PeriodEnergy);
-											await mainDbService.SetTransactionBillingDone(txEnergy.TxId, 0, string.Empty);
-                                        }
-										return result;
-									}
-
-                                    if (feedto == null || string.IsNullOrEmpty(feedto.Fee)) return result;
+                        if (_request.messageId == "ID_FirmwareVersion")
+                        {
+                            await mainDbService.RecordBoardVersions(session.MachineId, _confirm.data);
+                        }
 
-									if (!feedto.NotifyPnC && !string.IsNullOrEmpty(txEnergy.EVCCID))
-									{
-										//send PnC notification....
-										var customerInfo = db.Customer.Where(x => x.Id == session.CustomerId).Select(x => new { x.InstantStopTxReport, x.ApiUrl, x.ApiKey }).FirstOrDefault();
 
-										var request = new
-										{
-											SessionId = feedto.Id,
-											ChargeBoxId = session.ChargeBoxId,
-											EVCCID = txEnergy.EVCCID
+                        if (_request.messageId == "ID_TxEnergy") //計費
+                        {
+                            if (_confirm.status == DataTransferStatus.Accepted)
+                            {
+                                decimal couponPoint = 0m;
+                                string farewellMessage = string.Empty;
+                                string receipt = string.Empty;
+                                List<ChargingBill> bill = new List<ChargingBill>();
+                                List<ChargingPrice> chargingPrices = new List<ChargingPrice>();
+                                var txEnergy = JsonConvert.DeserializeObject<TransactionEnergy>(_confirm.data);
+                                var roundedPeriodEnergy = PeriodEnergyRounding(txEnergy.PeriodEnergy);
+                                //var feedto = await db.TransactionRecord.Where(x => x.Id == txEnergy.TxId).Select(x => new { Id = x.Id, ConnectorId = x.ConnectorId, Fee = x.Fee, StopTime = x.StopTime, StartTime = x.StartTime, NotifyPnC = x.NotifyPnC }).FirstOrDefaultAsync();
+                                var feedto = await mainDbService.GetTransaction(txEnergy.TxId);
+                                decimal chargedEnergy = 0m;
+
+                                if (feedto == null)
+                                    return result;
+
+                                if (string.IsNullOrEmpty(feedto.Fee))
+                                {
+                                    if (feedto.StopTime != GlobalConfig.DefaultNullTime)
+                                    {
+                                        await mainDbService.InsertOrUpdateTransactionPeriodEnergy(txEnergy.TxId, roundedPeriodEnergy);
+                                        await mainDbService.SetTransactionBillingDone(txEnergy.TxId, 0, string.Empty);
 
-										};
+                                        IBusinessService customer = await businessServiceFactory.CreateBusinessService(session.CustomerId);
+										await customer.NotifyTransactionCompleted(feedto, roundedPeriodEnergy);
+                                    }
+                                    return result;
+                                }
 
-										logger.LogDebug(customerInfo.ApiUrl + "session_pncinfo=>" + JsonConvert.SerializeObject(request));
+                                if (feedto == null || string.IsNullOrEmpty(feedto.Fee)) return result;
 
-										var response = await httpClient.Post(customerInfo.ApiUrl + "session_pncinfo", new Dictionary<string, string>()
-												{
-													{ "PartnerId",session.CustomerId.ToString()}
+                                if (!feedto.NotifyPnC && !string.IsNullOrEmpty(txEnergy.EVCCID))
+                                {
+                                    //send PnC notification....
+                                    //var customerInfo = db.Customer.Where(x => x.Id == session.CustomerId).Select(x => new { x.InstantStopTxReport, x.ApiUrl, x.ApiKey }).FirstOrDefault();
+									var customerInfo = await mainDbService.GetCustomer(session.CustomerId);
 
-												}, request, customerInfo.ApiKey);
+                                    var request = new
+                                    {
+                                        SessionId = feedto.Id,
+                                        ChargeBoxId = session.ChargeBoxId,
+                                        EVCCID = txEnergy.EVCCID
 
-										if (response.Status == System.Net.HttpStatusCode.OK)
-										{
-											var _httpResult = JsonConvert.DeserializeObject<CPOOuterResponse>(response.Response);
-											logger.LogDebug("session_pncinfo Response" + JsonConvert.SerializeObject(response));
-											var pnc_info = db.TransactionRecord.Where(x => x.Id == txEnergy.TxId).FirstOrDefault();
-											if (response.Status == System.Net.HttpStatusCode.OK)
-											{
-												pnc_info.NotifyPnC = true;
-											}
+                                    };
 
-											pnc_info.Evccid = txEnergy.EVCCID;
-											db.ChangeTracker.AutoDetectChangesEnabled = false;
-											db.TransactionRecord.Attach(pnc_info);
-											db.Entry(pnc_info).Property(x => x.Evccid).IsModified = true;
-											db.Entry(pnc_info).Property(x => x.NotifyPnC).IsModified = true;
+                                    logger.LogDebug(customerInfo.ApiUrl + "session_pncinfo=>" + JsonConvert.SerializeObject(request));
 
-											await db.SaveChangesAsync();
-										}
-									}
+                                    var response = await httpClient.Post(customerInfo.ApiUrl + "session_pncinfo", new Dictionary<string, string>()
+                                                {
+                                                    { "PartnerId",session.CustomerId.ToString()}
 
-									string currency = feedto.Fee.Substring(feedto.Fee.Length - 3);
-									decimal chargingCost = 0;
-									if (feedto.Fee.Length > 58)
-									{
-										chargingPrices = JsonConvert.DeserializeObject<List<ChargingPrice>>(feedto.Fee.Split('|')[0]);
-										foreach (var item in txEnergy.PeriodEnergy)
-										{
-											DateTime dt = new DateTime(2021, 01, 01, int.Parse(item.Key), 0, 0, DateTimeKind.Utc);
-											string startTime = dt.ToString("hh:mm tt", new CultureInfo("en-us"));
-											decimal perfee = 0;
+                                                }, request, customerInfo.ApiKey);
 
-											// 小數點第5位4捨五入
-											var periodEnergy = PeriodEnergyRounding(item.Value);
+                                    if (response.Status == System.Net.HttpStatusCode.OK)
+                                    {
+                                        var _httpResult = JsonConvert.DeserializeObject<CPOOuterResponse>(response.Response);
+                                        logger.LogDebug("session_pncinfo Response" + JsonConvert.SerializeObject(response));
 
-											chargedEnergy += periodEnergy;
-											if (chargingPrices.Count == 1)
-											{
-												perfee = Decimal.Multiply(periodEnergy, chargingPrices[0].Fee);
-												if (bill.Count == 0)
-												{
-													bill.Add(new ChargingBill()
-													{
-														StartTime = "12:00 AM",
-														EndTime = "11:59 PM",
-														Fee = chargingPrices[0].Fee
-													});
-												}
-
-												bill[0].PeriodEnergy += periodEnergy;
-
-											}
-											else
-											{
-												var price = chargingPrices.Where(x => x.StartTime == startTime).FirstOrDefault();
-												perfee = Decimal.Multiply(periodEnergy, price.Fee);
-
-												bill.Add(new ChargingBill()
-												{
-													StartTime = price.StartTime,
-													EndTime = price.EndTime,
-													PeriodEnergy = periodEnergy,
-													Fee = price.Fee,
-
-												});
-											}
-											if (bill.Count > 0)
-											{
-												bill[bill.Count - 1].Total += DollarRounding(perfee, session.Currency);
-												chargingCost += bill[bill.Count - 1].Total;
+										await mainDbService.SetPncNotifiyResult(txEnergy.TxId, response.Status == System.Net.HttpStatusCode.OK, txEnergy.EVCCID);
+                                    }
+                                }
 
-												if (bill.Count == 1)
-												{
+                                string currency = feedto.Fee.Substring(feedto.Fee.Length - 3);
+                                decimal chargingCost = 0;
+                                if (feedto.Fee.Length > 58)
+                                {
+                                    chargingPrices = JsonConvert.DeserializeObject<List<ChargingPrice>>(feedto.Fee.Split('|')[0]);
+                                    foreach (var item in roundedPeriodEnergy)
+                                    {
+                                        DateTime dt = new DateTime(2021, 01, 01, int.Parse(item.Key), 0, 0, DateTimeKind.Utc);
+                                        string startTime = dt.ToString("hh:mm tt", new CultureInfo("en-us"));
+                                        decimal perfee = 0;
 
-													bill[bill.Count - 1].Total = DollarRounding(Decimal.Multiply(bill[0].PeriodEnergy, bill[0].Fee), session.Currency);
-													chargingCost = bill[bill.Count - 1].Total;
-												}
-											}
-										}
-									}
-									else
-									{
-										//以小時計費
-										foreach (var item in txEnergy.PeriodEnergy)
-										{
-											// 小數點第5位4捨五入
-											var periodEnergy = PeriodEnergyRounding(item.Value);
-											chargedEnergy += periodEnergy;
-										}
+                                        // 小數點第5位4捨五入
+                                        //var periodEnergy = PeriodEnergyRounding(item.Value);
+										var periodEnergy = item.Value;
 
-										var fee = decimal.Parse(feedto.Fee.Split('|')[0]);
-										var charging_stoptime = feedto.StopTime == GlobalConfig.DefaultNullTime ? DateTime.Parse(DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm")) : DateTime.Parse(feedto.StopTime.ToString("yyyy/MM/dd HH:mm"));
-										var charging_starttime = DateTime.Parse(feedto.StartTime.ToString("yyyy/MM/dd HH:mm"));
-										chargingCost = Decimal.Multiply((decimal)charging_stoptime.Subtract(charging_starttime).TotalHours, fee);
-										chargingCost = DollarRounding(chargingCost, session.Currency);
-									}
+                                        chargedEnergy += periodEnergy;
+                                        if (chargingPrices.Count == 1)
+                                        {
+                                            perfee = Decimal.Multiply(periodEnergy, chargingPrices[0].Fee);
+                                            if (bill.Count == 0)
+                                            {
+                                                bill.Add(new ChargingBill()
+                                                {
+                                                    StartTime = "12:00 AM",
+                                                    EndTime = "11:59 PM",
+                                                    Fee = chargingPrices[0].Fee
+                                                });
+                                            }
+
+                                            bill[0].PeriodEnergy += periodEnergy;
 
-									// 計算停車費
-									var parkingFee = decimal.Parse(feedto.Fee.Split('&')[1]);
-									var stoptime = feedto.StopTime == GlobalConfig.DefaultNullTime ? DateTime.Parse(DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm")) : DateTime.Parse(feedto.StopTime.ToString("yyyy/MM/dd HH:mm"));
-									var starttime = DateTime.Parse(feedto.StartTime.ToString("yyyy/MM/dd HH:mm"));
-									var totalHours = stoptime.Subtract(starttime).TotalHours;
-									var parkingCost = Decimal.Multiply((decimal)totalHours, parkingFee);
-									parkingCost = DollarRounding(parkingCost, session.Currency);
+                                        }
+                                        else
+                                        {
+                                            var price = chargingPrices.Where(x => x.StartTime == startTime).FirstOrDefault();
+                                            perfee = Decimal.Multiply(periodEnergy, price.Fee);
 
-									if (feedto.StopTime != GlobalConfig.DefaultNullTime)
-									{
-										//var customerInfo = await db.Customer
-										//    .Where(x => x.Id == session.CustomerId).Select(x => new { x.InstantStopTxReport, x.ApiUrl, x.ApiKey })
-										//    .FirstOrDefaultAsync();
-										var customerInfo = await mainDbService.GetCustomer(session.CustomerId);
+                                            bill.Add(new ChargingBill()
+                                            {
+                                                StartTime = price.StartTime,
+                                                EndTime = price.EndTime,
+                                                PeriodEnergy = periodEnergy,
+                                                Fee = price.Fee,
 
-										decimal accountBalance = 0;
-										decimal.TryParse(feedto.Fee.Split('+')[1], out accountBalance);
+                                            });
+                                        }
+                                        if (bill.Count > 0)
+                                        {
+                                            bill[bill.Count - 1].Total += DollarRounding(perfee, session.Currency);
+                                            chargingCost += bill[bill.Count - 1].Total;
 
-										var tx = await db.TransactionRecord.Where(x => x.Id == txEnergy.TxId).FirstOrDefaultAsync();
-										if (tx == null)
-										{
-											logger.LogWarning("Tx is empty");
-											return result;
-										}
+                                            if (bill.Count == 1)
+                                            {
 
-										if (tx.BillingDone) return result;
+                                                bill[bill.Count - 1].Total = DollarRounding(Decimal.Multiply(bill[0].PeriodEnergy, bill[0].Fee), session.Currency);
+                                                chargingCost = bill[bill.Count - 1].Total;
+                                            }
+                                        }
+                                    }
+                                }
+                                else
+                                {
+                                    //以小時計費
+                                    foreach (var periodEnergy in roundedPeriodEnergy)
+                                    {
+                                        // 小數點第5位4捨五入
+                                        //var periodEnergy = PeriodEnergyRounding(item.Value);
+                                        chargedEnergy += periodEnergy.Value;
+                                    }
 
-										if (feedto.StopTime != DefaultSetting.DefaultNullTime)
-										{
-											await mainDbService.InsertOrUpdateTransactionPeriodEnergy(txEnergy.TxId, txEnergy.PeriodEnergy);
-										}
+                                    var fee = decimal.Parse(feedto.Fee.Split('|')[0]);
+                                    var charging_stoptime = feedto.StopTime == GlobalConfig.DefaultNullTime ? DateTime.Parse(DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm")) : DateTime.Parse(feedto.StopTime.ToString("yyyy/MM/dd HH:mm"));
+                                    var charging_starttime = DateTime.Parse(feedto.StartTime.ToString("yyyy/MM/dd HH:mm"));
+                                    chargingCost = Decimal.Multiply((decimal)charging_stoptime.Subtract(charging_starttime).TotalHours, fee);
+                                    chargingCost = DollarRounding(chargingCost, session.Currency);
+                                }
 
-										var startTime = new DateTime(tx.StartTime.Year, tx.StartTime.Month, tx.StartTime.Day, tx.StartTime.Hour, 0, 0);
-										List<ChargingBill> confirmbill = new List<ChargingBill>();
-										receipt = string.Format("({0} )Energy:", chargedEnergy);
+                                // 計算停車費
+                                var parkingFee = decimal.Parse(feedto.Fee.Split('&')[1]);
+                                var stoptime = feedto.StopTime == GlobalConfig.DefaultNullTime ? DateTime.Parse(DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm")) : DateTime.Parse(feedto.StopTime.ToString("yyyy/MM/dd HH:mm"));
+                                var starttime = DateTime.Parse(feedto.StartTime.ToString("yyyy/MM/dd HH:mm"));
+                                var totalHours = stoptime.Subtract(starttime).TotalHours;
+                                var parkingCost = Decimal.Multiply((decimal)totalHours, parkingFee);
+                                parkingCost = DollarRounding(parkingCost, session.Currency);
 
-										while (startTime < tx.StopTime)
-										{
-											if (bill.Count == 1)
-											{
-												confirmbill = bill;
-												receipt += string.Format("| {0} - {1}:| {2} kWh @ ${3}/kWh= ${4}", tx.StartTime.ToString("hh:mm tt", new CultureInfo("en-us")), tx.StopTime.ToString("hh:mm tt", new CultureInfo("en-us")),
-													confirmbill[0].PeriodEnergy.ToString("0.0000"), bill[0].Fee, bill[0].Total);
+                                if (feedto.StopTime != GlobalConfig.DefaultNullTime)
+                                {
+                                    //var customerInfo = await db.Customer
+                                    //    .Where(x => x.Id == session.CustomerId).Select(x => new { x.InstantStopTxReport, x.ApiUrl, x.ApiKey })
+                                    //    .FirstOrDefaultAsync();
+                                    //var customerInfo = await mainDbService.GetCustomer(session.CustomerId);
+                                    IBusinessService customer = await businessServiceFactory.CreateBusinessService(session.CustomerId);
+
+                                    decimal accountBalance = 0;
+                                    decimal.TryParse(feedto.Fee.Split('+')[1], out accountBalance);
+
+                                    //var tx = await db.TransactionRecord.Where(x => x.Id == txEnergy.TxId).FirstOrDefaultAsync();
+                                    var tx = await mainDbService.GetTransaction(txEnergy.TxId);
+                                    if (tx == null)
+                                    {
+                                        logger.LogWarning("Tx is empty");
+                                        return result;
+                                    }
 
-												break;
-											}
-											if (bill.Count == 0)
-											{
-												receipt += string.Format("| {0} - {1} @ ${2}/hr= ${3}", feedto.StartTime.ToString("hh:mm tt", new CultureInfo("en-us")),
-												   feedto.StopTime.ToString("hh:mm tt", new CultureInfo("en-us")), feedto.Fee.Split('|')[0], chargingCost);
+                                    if (tx.BillingDone) return result;
 
-												break;
-											}
-											if (bill.Count > 1)
-											{
-												var time = startTime.ToString("hh:mm tt", new CultureInfo("en-us"));
-												var tt = bill.Where(x => x.StartTime == time).FirstOrDefault();
-												confirmbill.Add(tt);
-												if (confirmbill.Count == 1)
-												{
-													confirmbill[0].StartTime = tx.StartTime.ToString("hh:mm tt", new CultureInfo("en-us"));
-												}
-
-
-												var stopTimeText = tx.StopTime.ToString("hh:mm tt", new CultureInfo("en-us"));
-												if (confirmbill[confirmbill.Count - 1].StartTime.Contains(stopTimeText.Split(' ')[1]))
-												{
-													var subHourText = (int.Parse(stopTimeText.Split(':')[0])).ToString();
-													subHourText = subHourText.Length == 1 ? "0" + subHourText : subHourText;
-													if (confirmbill[confirmbill.Count - 1].StartTime.Contains(subHourText))
-													{
-														confirmbill[confirmbill.Count - 1].EndTime = stopTimeText;
-													}
-
-												}
-												receipt += string.Format("| {0} - {1}:| {2} kWh @ ${3}/kWh= ${4}", confirmbill[confirmbill.Count - 1].StartTime, confirmbill[confirmbill.Count - 1].EndTime,
-													confirmbill[confirmbill.Count - 1].PeriodEnergy.ToString("0.0000"), confirmbill[confirmbill.Count - 1].Fee, confirmbill[confirmbill.Count - 1].Total);
-
-												if (confirmbill.Count == 24) break;
-
-											}
-											startTime = startTime.AddHours(1);
+                                    if (feedto.StopTime != DefaultSetting.DefaultNullTime)
+                                    {
+                                        await mainDbService.InsertOrUpdateTransactionPeriodEnergy(txEnergy.TxId, roundedPeriodEnergy);
+                                    }
 
-										}
+                                    var startTime = new DateTime(tx.StartTime.Year, tx.StartTime.Month, tx.StartTime.Day, tx.StartTime.Hour, 0, 0);
+                                    List<ChargingBill> confirmbill = new List<ChargingBill>();
+                                    receipt = string.Format("({0} )Energy:", chargedEnergy);
 
-										chargingCost = confirmbill.Count > 0 ? confirmbill.Sum(x => x.Total) : chargingCost;
-										receipt += string.Format("|Total Energy Fee : ${0}", chargingCost);
+                                    while (startTime < tx.StopTime)
+                                    {
+                                        if (bill.Count == 1)
+                                        {
+                                            confirmbill = bill;
+                                            receipt += string.Format("| {0} - {1}:| {2} kWh @ ${3}/kWh= ${4}", tx.StartTime.ToString("hh:mm tt", new CultureInfo("en-us")), tx.StopTime.ToString("hh:mm tt", new CultureInfo("en-us")),
+                                                confirmbill[0].PeriodEnergy.ToString("0.0000"), bill[0].Fee, bill[0].Total);
 
-										receipt += string.Format("|Parking Fee: | {0} - {1}: | {2} @ ${3}/hr= ${4}", feedto.StartTime.ToString("hh:mm tt", new CultureInfo("en-us")),
-										feedto.StopTime.ToString("hh:mm tt", new CultureInfo("en-us")), (totalHours / 1 >= 1) ? string.Format("{0} hours {1} minutes", (int)totalHours / 1, ((totalHours % 1) * 60).ToString("0.0")) : string.Format("{0} minutes", ((totalHours % 1) * 60).ToString("0.0")), parkingFee, parkingCost);
-										receipt += string.Format("|Stop Reason: {0}", tx.StopReason);
+                                            break;
+                                        }
+                                        if (bill.Count == 0)
+                                        {
+                                            receipt += string.Format("| {0} - {1} @ ${2}/hr= ${3}", feedto.StartTime.ToString("hh:mm tt", new CultureInfo("en-us")),
+                                               feedto.StopTime.ToString("hh:mm tt", new CultureInfo("en-us")), feedto.Fee.Split('|')[0], chargingCost);
 
-										tx.Cost = chargingCost + parkingCost;
+                                            break;
+                                        }
+                                        if (bill.Count > 1)
+                                        {
+                                            var time = startTime.ToString("hh:mm tt", new CultureInfo("en-us"));
+                                            var tt = bill.Where(x => x.StartTime == time).FirstOrDefault();
+                                            confirmbill.Add(tt);
+                                            if (confirmbill.Count == 1)
+                                            {
+                                                confirmbill[0].StartTime = tx.StartTime.ToString("hh:mm tt", new CultureInfo("en-us"));
+                                            }
+
+
+                                            var stopTimeText = tx.StopTime.ToString("hh:mm tt", new CultureInfo("en-us"));
+                                            if (confirmbill[confirmbill.Count - 1].StartTime.Contains(stopTimeText.Split(' ')[1]))
+                                            {
+                                                var subHourText = (int.Parse(stopTimeText.Split(':')[0])).ToString();
+                                                subHourText = subHourText.Length == 1 ? "0" + subHourText : subHourText;
+                                                if (confirmbill[confirmbill.Count - 1].StartTime.Contains(subHourText))
+                                                {
+                                                    confirmbill[confirmbill.Count - 1].EndTime = stopTimeText;
+                                                }
+
+                                            }
+                                            receipt += string.Format("| {0} - {1}:| {2} kWh @ ${3}/kWh= ${4}", confirmbill[confirmbill.Count - 1].StartTime, confirmbill[confirmbill.Count - 1].EndTime,
+                                                confirmbill[confirmbill.Count - 1].PeriodEnergy.ToString("0.0000"), confirmbill[confirmbill.Count - 1].Fee, confirmbill[confirmbill.Count - 1].Total);
+
+                                            if (confirmbill.Count == 24) break;
 
+                                        }
+                                        startTime = startTime.AddHours(1);
 
-										if (customerInfo != null && customerInfo.InstantStopTxReport)
-										{
-											var PeriodEnergy = await mainDbService.GetTransactionPeriodEnergy(tx.Id);
+                                    }
 
-											var request = new
-											{
-												ChargeBoxId = tx.ChargeBoxId,
-												ConnectorId = tx.ConnectorId,
-												SessionId = tx.Id,
-												MeterStart = tx.MeterStart,
-												MeterStop = tx.MeterStop,
-												IdTag = tx.StartIdTag,
-												StartTime = tx.StartTime.ToString(GlobalConfig.UTC_DATETIMEFORMAT),
-												StopTime = tx.StopTime.ToString(GlobalConfig.UTC_DATETIMEFORMAT),
-												StopReason = tx.StopReasonId < 1 ? "Unknown" : (tx.StopReasonId > 12 ? "Unknown" : ((Reason)tx.StopReasonId).ToString()),
-												Receipt = tx.Receipt,
-												TotalCost = tx.Cost,
-												Fee = tx.Fee,
-												PeriodEnergy = PeriodEnergy,
-												StartSOC = int.TryParse(tx.StartSoc, out int StartSOCint) ? StartSOCint : (int?)null,
-												StopSOC = int.TryParse(tx.StopSoc, out int StopSOCint) ? StopSOCint : (int?)null
+                                    chargingCost = confirmbill.Count > 0 ? confirmbill.Sum(x => x.Total) : chargingCost;
+                                    receipt += string.Format("|Total Energy Fee : ${0}", chargingCost);
 
-											};
+                                    receipt += string.Format("|Parking Fee: | {0} - {1}: | {2} @ ${3}/hr= ${4}", feedto.StartTime.ToString("hh:mm tt", new CultureInfo("en-us")),
+                                    feedto.StopTime.ToString("hh:mm tt", new CultureInfo("en-us")), (totalHours / 1 >= 1) ? string.Format("{0} hours {1} minutes", (int)totalHours / 1, ((totalHours % 1) * 60).ToString("0.0")) : string.Format("{0} minutes", ((totalHours % 1) * 60).ToString("0.0")), parkingFee, parkingCost);
+                                    receipt += string.Format("|Stop Reason: {0}", tx.StopReason);
 
-											logger.LogDebug("completed_session " + JsonConvert.SerializeObject(request));
-											var response = await httpClient.Post(customerInfo.ApiUrl + "completed_session", new Dictionary<string, string>()
-											{
-												{ "PartnerId",session.CustomerId.ToString()}
+                                    //tx.Cost = chargingCost + parkingCost;
 
-											}, request, customerInfo.ApiKey);
+                                    var response = await customer.NotifyTransactionCompleted(tx, roundedPeriodEnergy);
 
+                                    if (response != null)
+                                    {
+                                        couponPoint = response.CouponPoint == null ? couponPoint : response.CouponPoint.Value;
+                                        farewellMessage = response.FarewellMessage == null ? farewellMessage : response.FarewellMessage;
+                                    }
 
-											logger.LogDebug("completed_session Response" + response.Response);
+                                    await mainDbService.SetTransactionBillingDone(txEnergy.TxId, cost: chargingCost + parkingCost, receipt);
 
-											if (response.Success && !string.IsNullOrEmpty(response.Response))
-											{
-												var _httpResult = JsonConvert.DeserializeObject<CPOOuterResponse>(response.Response);
-												logger.LogDebug("completed_session Response" + response.Response);
-												JObject jo = JObject.Parse(_httpResult.Data);
-												if (jo.ContainsKey("CouponPoint"))
-												{
-													couponPoint = jo["CouponPoint"].Value<Decimal>();
-
-												}
-
-												if (jo.ContainsKey("FarewellMessage"))
-												{
-													farewellMessage = jo["FarewellMessage"].Value<string>();
-												}
-											}
-										}
+                                    await messageService.SendDataTransferRequest(
+                                        session.ChargeBoxId,
+                                        messageId: "FinalCost",
+                                        vendorId: "Phihong Technology",
+                                        data: JsonConvert.SerializeObject(new
+                                        {
+                                            txId = txEnergy.TxId,
+                                            description = JsonConvert.SerializeObject(new
+                                            {
+                                                chargedEnergy = chargedEnergy,
+                                                chargingFee = chargingCost,
+                                                parkTime = (int)stoptime.Subtract(starttime).TotalSeconds,
+                                                parkingFee = parkingCost,
+                                                currency = currency,
+                                                couponPoint = couponPoint,
+                                                accountBalance = accountBalance - tx.Cost,
+                                                farewellMessage = farewellMessage
+                                            })
+                                        })
+                                        );
 
-										tx.Receipt = receipt;
-										tx.BillingDone = true;
-										db.ChangeTracker.AutoDetectChangesEnabled = false;
-										//db.Configuration.ValidateOnSaveEnabled = false;
-										db.TransactionRecord.Attach(tx);
-										db.Entry(tx).Property(x => x.Cost).IsModified = true;
-										db.Entry(tx).Property(x => x.Receipt).IsModified = true;
-										db.Entry(tx).Property(x => x.BillingDone).IsModified = true;
-
-										await db.SaveChangesAsync();
-
-										await messageService.SendDataTransferRequest(
-											session.ChargeBoxId,
-											messageId: "FinalCost",
-											vendorId: "Phihong Technology",
-											data: JsonConvert.SerializeObject(new
-											{
-												txId = txEnergy.TxId,
-												description = JsonConvert.SerializeObject(new
-												{
-													chargedEnergy = chargedEnergy,
-													chargingFee = chargingCost,
-													parkTime = (int)stoptime.Subtract(starttime).TotalSeconds,
-													parkingFee = parkingCost,
-													currency = currency,
-													couponPoint = couponPoint,
-													accountBalance = accountBalance - tx.Cost,
-													farewellMessage = farewellMessage
-												})
-											})
-											);
-
-										await meterValueDbService.InsertAsync(
-											chargeBoxId: session.ChargeBoxId,
-											connectorId: feedto.ConnectorId,
-											value: chargingCost,
-											createdOn: DateTime.UtcNow,
-											contextId: (int)ReadingContext.Sample_Periodic,
-											formatId: (int)ValueFormat.Raw,
-											measurandId: (int)Measurand.TotalCost,
-											phaseId: -1,
-											locationId: -1,
-											unitId: -1,
-											transactionId: feedto.Id);
-
-										using (SqlConnection conn = await webDbConnectionFactory.CreateAsync())
-										{
-											var parameters = new DynamicParameters();
-											parameters.Add("@IdTag", tx.StartIdTag, DbType.String, ParameterDirection.Input, 50);
-											parameters.Add("@parentIdTag", accountBalance - tx.Cost, DbType.String, ParameterDirection.Input, 50);
-											string strSql = "update [dbo].[LocalListDetail] set parentIdTag =@parentIdTag  where ListId = 27 and IdTag=@IdTag; ";
-											await conn.ExecuteAsync(strSql, parameters);
+                                    await meterValueDbService.InsertAsync(
+                                        chargeBoxId: session.ChargeBoxId,
+                                        connectorId: feedto.ConnectorId,
+                                        value: chargingCost,
+                                        createdOn: DateTime.UtcNow,
+                                        contextId: (int)ReadingContext.Sample_Periodic,
+                                        formatId: (int)ValueFormat.Raw,
+                                        measurandId: (int)Measurand.TotalCost,
+                                        phaseId: -1,
+                                        locationId: -1,
+                                        unitId: -1,
+                                        transactionId: feedto.Id);
+
+                                    using (SqlConnection conn = await webDbConnectionFactory.CreateAsync())
+                                    {
+                                        var parameters = new DynamicParameters();
+                                        parameters.Add("@IdTag", tx.StartIdTag, DbType.String, ParameterDirection.Input, 50);
+                                        parameters.Add("@parentIdTag", accountBalance - tx.Cost, DbType.String, ParameterDirection.Input, 50);
+                                        string strSql = "update [dbo].[LocalListDetail] set parentIdTag =@parentIdTag  where ListId = 27 and IdTag=@IdTag; ";
+                                        await conn.ExecuteAsync(strSql, parameters);
 
-										}
+                                    }
 
-										#region 提供給PHA 過CDFA認證 使用
-										if (tx.CustomerId == Guid.Parse("10C7F5BD-C89A-4E2A-8611-B617E0B41A73"))
-										{
-											var mail_response = httpClient.PostFormDataAsync("https://charge.zerovatech.com/CDFA/" + tx.Id, new Dictionary<string, string>()
-											{
-												{ "email","2"},
-												{ "to","wonderj@phihongusa.com;jessica_tseng@phihong.com.tw"}
+                                    #region 提供給PHA 過CDFA認證 使用
+                                    if (tx.CustomerId == Guid.Parse("10C7F5BD-C89A-4E2A-8611-B617E0B41A73"))
+                                    {
+                                        var mail_response = httpClient.PostFormDataAsync("https://charge.zerovatech.com/CDFA/" + tx.Id, new Dictionary<string, string>()
+                                            {
+                                                { "email","2"},
+                                                { "to","wonderj@phihongusa.com;jessica_tseng@phihong.com.tw"}
                                                 //{ "to","jessica_tseng@phihong.com.tw"}
                                            }, null);
 
-											logger.LogTrace(JsonConvert.SerializeObject(mail_response));
+                                        logger.LogTrace(JsonConvert.SerializeObject(mail_response));
 
-										}
-										#endregion
+                                    }
+                                    #endregion
 
-									}
-									else
-									{
-										await messageService.SendDataTransferRequest(
-											session.ChargeBoxId,
-											messageId: "RunningCost",
-											vendorId: "Phihong Technology",
-											data: JsonConvert.SerializeObject(new
-											{
-												txId = txEnergy.TxId,
-												description = JsonConvert.SerializeObject(new
-												{
-													chargedEnergy = chargedEnergy,
-													chargingFee = chargingCost,
-													parkTime = (int)stoptime.Subtract(starttime).TotalSeconds,
-													parkingFee = parkingCost,
-													currency = currency
-												})
-
-											})
-											);
-
-										await meterValueDbService.InsertAsync(
-											chargeBoxId: session.ChargeBoxId,
-											connectorId: (byte)feedto.ConnectorId,
-											value: chargingCost,
-											createdOn: DateTime.UtcNow,
-											contextId: (int)ReadingContext.Sample_Periodic,
-											formatId: (int)ValueFormat.Raw,
-											measurandId: (int)Measurand.ChargingCost,
-											phaseId: -1,
-											locationId: -1,
-											unitId: -1,
-											transactionId: feedto.Id
-											);
-									}
-								}
+                                }
+                                else
+                                {
+                                    await messageService.SendDataTransferRequest(
+                                        session.ChargeBoxId,
+                                        messageId: "RunningCost",
+                                        vendorId: "Phihong Technology",
+                                        data: JsonConvert.SerializeObject(new
+                                        {
+                                            txId = txEnergy.TxId,
+                                            description = JsonConvert.SerializeObject(new
+                                            {
+                                                chargedEnergy = chargedEnergy,
+                                                chargingFee = chargingCost,
+                                                parkTime = (int)stoptime.Subtract(starttime).TotalSeconds,
+                                                parkingFee = parkingCost,
+                                                currency = currency
+                                            })
+
+                                        })
+                                        );
 
-							}
+                                    await meterValueDbService.InsertAsync(
+                                        chargeBoxId: session.ChargeBoxId,
+                                        connectorId: (byte)feedto.ConnectorId,
+                                        value: chargingCost,
+                                        createdOn: DateTime.UtcNow,
+                                        contextId: (int)ReadingContext.Sample_Periodic,
+                                        formatId: (int)ValueFormat.Raw,
+                                        measurandId: (int)Measurand.ChargingCost,
+                                        phaseId: -1,
+                                        locationId: -1,
+                                        unitId: -1,
+                                        transactionId: feedto.Id
+                                        );
+                                }
+                            }
+
+                        }
+
+                        using (var db = await maindbContextFactory.CreateDbContextAsync())
+						{
 
 							#region 台泥
 							if (_request.messageId == "ID_GetTxUserInfo")
@@ -1818,9 +1748,24 @@ internal partial class ProfileHandler
 		energy = Decimal.Parse(energy.ToString("0.0000"));
 		return energy;
 	}
-	
 
-	private static bool CheckNeedAddMachineError(StatusNotificationRequest _request, ConnectorStatus _oldStatus)
+    /// <summary>
+    /// PeriodEnergy處理4捨5入
+    /// </summary>
+    /// <param name="periodEnergy">raw data of periodEnergy</param>
+    /// <returns></returns>
+    private Dictionary<string, decimal> PeriodEnergyRounding(Dictionary<string, decimal> periodEnergy)
+    {
+        var toReturn = new Dictionary<string, decimal>();
+        foreach (var period in periodEnergy)
+        {
+            toReturn.Add(period.Key, PeriodEnergyRounding(period.Value));
+        }
+        return toReturn;
+    }
+
+
+    private static bool CheckNeedAddMachineError(StatusNotificationRequest _request, ConnectorStatus _oldStatus)
     {
 		if (_request.status != ChargePointStatus.Faulted)
 		{

+ 11 - 7
EVCB_OCPP.WSServer/Service/BusinessServiceFactory.cs → EVCB_OCPP.WSServer/Service/BusinessService/BusinessServiceFactory.cs

@@ -1,5 +1,5 @@
 using EVCB_OCPP.Domain;
-
+using EVCB_OCPP.Domain.Models.MainDb;
 using EVCB_OCPP.Packet.Messages.SubTypes;
 using EVCB_OCPP.WSServer.Dto;
 using EVCB_OCPP.WSServer.Service.DbService;
@@ -9,7 +9,7 @@ using System;
 using System.Linq;
 using System.Threading.Tasks;
 
-namespace EVCB_OCPP.WSServer.Service;
+namespace EVCB_OCPP.WSServer.Service.BusinessService;
 
 
 public interface IBusinessService
@@ -18,7 +18,9 @@ public interface IBusinessService
 
     Task NotifyFaultStatus(ErrorDetails details);
 
-    Task NotifyConnectorUnplugged(string chargeBoxId,string data);
+    Task NotifyConnectorUnplugged(string chargeBoxId, string data);
+
+    ValueTask<NotifyTransactionCompletedResponse> NotifyTransactionCompleted(TransactionRecord tx, Dictionary<string, decimal> roundedPeriodEnergy);
 
 }
 
@@ -54,7 +56,7 @@ public class BusinessServiceFactory : IBusinessServiceFactory
 
     //private readonly IDbContextFactory<MainDBContext> mainDBContextFactory;
 
-    public async Task<IBusinessService> CreateBusinessService(string customerId)
+    public async Task<IBusinessService> CreateBusinessService(Guid customerId)
     {
         bool isCallOut = false;
         //using (var db = this.mainDBContextFactory.CreateDbContextAsync())
@@ -69,11 +71,13 @@ public class BusinessServiceFactory : IBusinessServiceFactory
         var _customerDb = await mainDbService.GetCustomer(customerId);
         if (_customerDb is not null)
         {
-            _customer = new CustomerSignMaterial() { 
+            _customer = new CustomerSignMaterial()
+            {
                 Id = _customerDb.Id.ToString(),
                 APIUrl = _customerDb.ApiUrl,
                 SaltKey = _customerDb.ApiKey,
-                CallsThirdParty = _customerDb.CallPartnerApiOnSchedule
+                CallsThirdParty = _customerDb.CallPartnerApiOnSchedule,
+                InstantStopTxReport = _customerDb.InstantStopTxReport,
             };
         }
         isCallOut = _customer != null && _customer.CallsThirdParty;
@@ -86,7 +90,7 @@ public class BusinessServiceFactory : IBusinessServiceFactory
             return outerBusinessService;
         }
         LocalBusinessService toReturn = serviceProvider.GetService<LocalBusinessService>();
-        toReturn.CustomerId = customerId;
+        toReturn.CustomerId = customerId.ToString();
         return toReturn;
 
         //return isCallOut ? new OuterBusinessService(customerId) : 

+ 9 - 0
EVCB_OCPP.WSServer/Service/BusinessService/IBusinessServiceFactory.cs

@@ -0,0 +1,9 @@
+using System.Threading.Tasks;
+
+namespace EVCB_OCPP.WSServer.Service.BusinessService
+{
+    public interface IBusinessServiceFactory
+    {
+        Task<IBusinessService> CreateBusinessService(Guid customerId);
+    }
+}

+ 8 - 2
EVCB_OCPP.WSServer/Service/LocalBusinessService.cs → EVCB_OCPP.WSServer/Service/BusinessService/LocalBusinessService.cs

@@ -1,4 +1,5 @@
-using EVCB_OCPP.Packet.Messages.SubTypes;
+using EVCB_OCPP.Domain.Models.MainDb;
+using EVCB_OCPP.Packet.Messages.SubTypes;
 using EVCB_OCPP.WSServer.Dto;
 using Microsoft.Extensions.Configuration;
 using Newtonsoft.Json.Linq;
@@ -8,7 +9,7 @@ using System.Configuration;
 using System.Net;
 using System.Threading.Tasks;
 
-namespace EVCB_OCPP.WSServer.Service
+namespace EVCB_OCPP.WSServer.Service.BusinessService
 {
     public class LocalBusinessService : IBusinessService
     {
@@ -89,5 +90,10 @@ namespace EVCB_OCPP.WSServer.Service
         {
             await Task.Delay(10);
         }
+
+        public ValueTask<NotifyTransactionCompletedResponse> NotifyTransactionCompleted(TransactionRecord tx, Dictionary<string, decimal> roundedPeriodEnergy)
+        {
+            return ValueTask.FromResult<NotifyTransactionCompletedResponse>(null);
+        }
     }
 }

+ 14 - 0
EVCB_OCPP.WSServer/Service/BusinessService/Model.cs

@@ -0,0 +1,14 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace EVCB_OCPP.WSServer.Service.BusinessService
+{
+    public class NotifyTransactionCompletedResponse
+    {
+        public decimal? CouponPoint { set; get; } = null;
+        public string? FarewellMessage { set; get; } = null;
+    }
+}

+ 75 - 10
EVCB_OCPP.WSServer/Service/OuterBusinessService.cs → EVCB_OCPP.WSServer/Service/BusinessService/OuterBusinessService.cs

@@ -1,5 +1,5 @@
 using EVCB_OCPP.Domain;
-
+using EVCB_OCPP.Domain.Models.MainDb;
 using EVCB_OCPP.Packet.Messages.SubTypes;
 using EVCB_OCPP.WSServer.Dto;
 using EVCB_OCPP.WSServer.Service.DbService;
@@ -13,7 +13,7 @@ using System.Collections.Generic;
 using System.Linq;
 using System.Threading.Tasks;
 
-namespace EVCB_OCPP.WSServer.Service
+namespace EVCB_OCPP.WSServer.Service.BusinessService
 {
     internal class CPOOuterResponse
     {
@@ -47,6 +47,8 @@ namespace EVCB_OCPP.WSServer.Service
         internal string APIUrl { set; get; }
 
         internal string SaltKey { set; get; }
+
+        internal bool InstantStopTxReport { set; get; }
     }
     public class OuterBusinessService : IBusinessService
     {
@@ -108,8 +110,8 @@ namespace EVCB_OCPP.WSServer.Service
                 logger.LogInformation(chargeBoxId + " Charging Monitor======================================>");
 
                 string requestParams = idTag.StartsWith("vid:") ? await GetRequestParamsAsPnC(chargeBoxId, idTag, connectorId, source) : GetRequestParamsAsNormal(chargeBoxId, idTag, source);
-				logger.LogInformation($"{chargeBoxId} Authorize : {signMaterial.APIUrl + requestParams}");
-				HttpResult response = await httpClient.Post(signMaterial.APIUrl + requestParams, new Dictionary<string, string>()
+                logger.LogInformation($"{chargeBoxId} Authorize : {signMaterial.APIUrl + requestParams}");
+                HttpResult response = await httpClient.Post(signMaterial.APIUrl + requestParams, new Dictionary<string, string>()
                             {
                                 { "PartnerId",signMaterial.Id}
                             }, requestBody: null, saltkey: signMaterial.SaltKey).ConfigureAwait(false);
@@ -136,21 +138,21 @@ namespace EVCB_OCPP.WSServer.Service
 
                     if (jo.ContainsKey("ChargePointFee"))
                     {
-                       
 
-                        for(int i=0;i< jo["ChargePointFee"].Count();i++)
+
+                        for (int i = 0; i < jo["ChargePointFee"].Count(); i++)
                         {
-                            if(i==0)
+                            if (i == 0)
                             {
                                 result.ChargePointFee = new List<ChargePointFee>();
                             }
                             result.ChargePointFee.Add(jo["ChargePointFee"][i].ToObject<ChargePointFee>());
                         }
-                     
+
                     }
 
                     if (jo.ContainsKey("ChargepointFee"))
-                    {                       
+                    {
 
                         for (int i = 0; i < jo["ChargepointFee"].Count(); i++)
                         {
@@ -223,7 +225,7 @@ namespace EVCB_OCPP.WSServer.Service
             {
                 JObject jo = JObject.Parse(data);
 
-                var details = new { ChargeBoxId = chargeBoxId, SessionId = jo["idTx"].Value<Int32>(), Timestamp = jo["timestamp"].Value<DateTime>() };
+                var details = new { ChargeBoxId = chargeBoxId, SessionId = jo["idTx"].Value<int>(), Timestamp = jo["timestamp"].Value<DateTime>() };
                 if (signMaterial.CallsThirdParty)
                 {
                     var response = await httpClient.Post(signMaterial.APIUrl + "connectorunplugged", new Dictionary<string, string>()
@@ -312,5 +314,68 @@ namespace EVCB_OCPP.WSServer.Service
         {
             throw new NotImplementedException();
         }
+
+        public async ValueTask<NotifyTransactionCompletedResponse> NotifyTransactionCompleted(TransactionRecord tx, Dictionary<string, decimal> roundedPeriodEnergy)
+        {
+            if (signMaterial == null || !signMaterial.InstantStopTxReport)
+            {
+                return null;
+            }
+
+            var toReturn = new NotifyTransactionCompletedResponse();
+
+            //var PeriodEnergy = await mainDbService.GetTransactionPeriodEnergy(tx.Id);
+
+            var request = new
+            {
+                ChargeBoxId = tx.ChargeBoxId,
+                ConnectorId = tx.ConnectorId,
+                SessionId = tx.Id,
+                MeterStart = tx.MeterStart,
+                MeterStop = tx.MeterStop,
+                IdTag = tx.StartIdTag,
+                StartTime = tx.StartTime.ToString(GlobalConfig.UTC_DATETIMEFORMAT),
+                StopTime = tx.StopTime.ToString(GlobalConfig.UTC_DATETIMEFORMAT),
+                StopReason = tx.StopReasonId < 1 ? "Unknown" : (tx.StopReasonId > 12 ? "Unknown" : ((Reason)tx.StopReasonId).ToString()),
+                Receipt = tx.Receipt,
+                TotalCost = tx.Cost,
+                Fee = tx.Fee,
+                PeriodEnergy = roundedPeriodEnergy,
+                StartSOC = int.TryParse(tx.StartSoc, out int StartSOCint) ? StartSOCint : (int?)null,
+                StopSOC = int.TryParse(tx.StopSoc, out int StopSOCint) ? StopSOCint : (int?)null
+
+            };
+
+            logger.LogDebug("completed_session " + JsonConvert.SerializeObject(request));
+            var response = await httpClient.Post(
+                signMaterial.APIUrl + "completed_session", 
+                new Dictionary<string, string>()
+                {
+                    { "PartnerId", CustomerId}
+                }, 
+                request,
+                signMaterial.SaltKey);
+
+            logger.LogDebug("completed_session Response" + response.Response);
+
+            if (response.Success && !string.IsNullOrEmpty(response.Response))
+            {
+                var _httpResult = JsonConvert.DeserializeObject<CPOOuterResponse>(response.Response);
+                logger.LogDebug("completed_session Response" + response.Response);
+                JObject jo = JObject.Parse(_httpResult.Data);
+                if (jo.ContainsKey("CouponPoint"))
+                {
+                    toReturn.CouponPoint = jo["CouponPoint"].Value<Decimal>();
+
+                }
+
+                if (jo.ContainsKey("FarewellMessage"))
+                {
+                    toReturn.FarewellMessage = jo["FarewellMessage"].Value<string>();
+                }
+            }
+
+            return toReturn;
+        }
     }
 }

+ 63 - 1
EVCB_OCPP.WSServer/Service/DbService/MainDbService.cs

@@ -1,4 +1,5 @@
-using Dapper;
+using Azure;
+using Dapper;
 using EVCB_OCPP.Domain;
 using EVCB_OCPP.Domain.ConnectionFactory;
 using EVCB_OCPP.Domain.Models.MainDb;
@@ -10,6 +11,7 @@ using EVCB_OCPP.Packet.Messages.RemoteTrigger;
 using EVCB_OCPP.Packet.Messages.Reservation;
 using EVCB_OCPP.Packet.Messages.Security;
 using EVCB_OCPP.Packet.Messages.SmartCharging;
+using EVCB_OCPP.Packet.Messages.SubTypes;
 using EVCB_OCPP.WSServer.Helper;
 using Microsoft.Data.SqlClient;
 using Microsoft.EntityFrameworkCore;
@@ -65,6 +67,11 @@ public interface IMainDbService
 
     Task<bool> UpdateCustomId(string customId, string chargeboxId);
     Task SetTransactionBillingDone(int txId, decimal cost, string receipt);
+
+    Task SetMachineOperateRecordFinished(string requestId, string chargeBoxId, DataTransferStatus status, string data);
+    Task RecordBoardVersions(string machineId, string data);
+    Task<TransactionRecord> GetTransaction(int txId);
+    Task SetPncNotifiyResult(int txid, bool isNotifySuccess, string eVCCID);
 }
 
 public class MainDbService : IMainDbService
@@ -583,6 +590,61 @@ public class MainDbService : IMainDbService
         await db.SaveChangesAsync();
     }
 
+    public async Task SetMachineOperateRecordFinished(string requestId, string chargeBoxId, DataTransferStatus status, string data)
+    {
+        using var db = await contextFactory.CreateDbContextAsync();
+        var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
+                            x.ChargeBoxId == chargeBoxId && x.Status == 0).FirstOrDefaultAsync();
+        if (operation != null)
+        {
+            operation.FinishedOn = DateTime.UtcNow;
+            operation.Status = 1;//電樁有回覆
+            operation.EvseStatus = (int)status;
+            operation.EvseValue = string.IsNullOrEmpty(data) ? "" : data;
+            await db.SaveChangesAsync();
+        }
+    }
+
+    public async Task RecordBoardVersions(string machineId, string data)
+    {
+        using var db = await contextFactory.CreateDbContextAsync();
+        var machine = new Machine() { Id = machineId };
+        if (machine != null)
+        {
+            db.ChangeTracker.AutoDetectChangesEnabled = false;
+            //db.Configuration.ValidateOnSaveEnabled = false;
+            db.Machine.Attach(machine);
+            machine.BoardVersions = data;
+            db.Entry(machine).Property(x => x.BoardVersions).IsModified = true;
+            await db.SaveChangesAsync();
+        }
+    }
+
+    public async Task<TransactionRecord> GetTransaction(int txId)
+    {
+        using var db = await contextFactory.CreateDbContextAsync();
+        TransactionRecord feedto = await db.TransactionRecord.Where(x => x.Id == txId).FirstOrDefaultAsync();
+        return feedto;
+    }
+
+    public async Task SetPncNotifiyResult(int txid, bool isNotifySuccess, string eVCCID)
+    {
+        using var db = await contextFactory.CreateDbContextAsync();
+
+        var pnc_info = db.TransactionRecord.Where(x => x.Id == txid).FirstOrDefault();
+
+        pnc_info.NotifyPnC = isNotifySuccess;
+
+        pnc_info.Evccid = eVCCID;
+        db.ChangeTracker.AutoDetectChangesEnabled = false;
+        db.TransactionRecord.Attach(pnc_info);
+        db.Entry(pnc_info).Property(x => x.Evccid).IsModified = true;
+        db.Entry(pnc_info).Property(x => x.NotifyPnC).IsModified = true;
+
+        await db.SaveChangesAsync();
+    }
+
+
     private void InitUpdateConnectorStatusHandler()
     {
         if (statusNotificationHandler is not null)

+ 0 - 9
EVCB_OCPP.WSServer/Service/IBusinessServiceFactory.cs

@@ -1,9 +0,0 @@
-using System.Threading.Tasks;
-
-namespace EVCB_OCPP.WSServer.Service
-{
-    public interface IBusinessServiceFactory
-    {
-        Task<IBusinessService> CreateBusinessService(string customerId);
-    }
-}