Compare commits
7 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| a947494cbd | |||
| 7e79a13cb1 | |||
| 2ad6df1195 | |||
| dc3cd75ea4 | |||
| a73f14fa7f | |||
| 0af31c39b3 | |||
| e1256503be |
@@ -31,10 +31,13 @@ public interface ICompanyListService
|
||||
{
|
||||
/// <summary>
|
||||
/// Returns a paged, searched, and sorted slice of non-deleted companies together with the
|
||||
/// total unfiltered count for pagination.
|
||||
/// total count for pagination and the count of churned accounts that are currently hidden.
|
||||
/// When <paramref name="hideChurned"/> is true, Expired/Canceled companies whose subscription
|
||||
/// ended more than 14 days ago are excluded from results (but still counted for the banner).
|
||||
/// </summary>
|
||||
Task<(List<Company> Companies, int TotalCount)> GetPagedAsync(
|
||||
string? searchTerm, string sortColumn, string sortDirection, int page, int pageSize);
|
||||
Task<(List<Company> Companies, int TotalCount, int ChurnedCount)> GetPagedAsync(
|
||||
string? searchTerm, string sortColumn, string sortDirection, int page, int pageSize,
|
||||
bool hideChurned = true);
|
||||
|
||||
/// <summary>
|
||||
/// Returns job, quote, customer, and wizard completion counts for each of the supplied
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using PowderCoating.Core.Entities;
|
||||
using PowderCoating.Core.Enums;
|
||||
using PowderCoating.Core.Interfaces.Services;
|
||||
using PowderCoating.Infrastructure.Data;
|
||||
|
||||
@@ -21,15 +22,34 @@ public class CompanyListService : ICompanyListService
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public async Task<(List<Company> Companies, int TotalCount)> GetPagedAsync(
|
||||
string? searchTerm, string sortColumn, string sortDirection, int page, int pageSize)
|
||||
public async Task<(List<Company> Companies, int TotalCount, int ChurnedCount)> GetPagedAsync(
|
||||
string? searchTerm, string sortColumn, string sortDirection, int page, int pageSize,
|
||||
bool hideChurned = true)
|
||||
{
|
||||
var cutoff = DateTime.UtcNow.AddDays(-14);
|
||||
|
||||
// Always count churned regardless of hideChurned so the banner can show a number.
|
||||
var churnedCount = await _context.Companies
|
||||
.AsNoTracking()
|
||||
.IgnoreQueryFilters()
|
||||
.Where(c => !c.IsDeleted
|
||||
&& (c.SubscriptionStatus == SubscriptionStatus.Expired || c.SubscriptionStatus == SubscriptionStatus.Canceled)
|
||||
&& c.SubscriptionEndDate != null
|
||||
&& c.SubscriptionEndDate < cutoff)
|
||||
.CountAsync();
|
||||
|
||||
var query = _context.Companies
|
||||
.AsNoTracking()
|
||||
.IgnoreQueryFilters()
|
||||
.Where(c => !c.IsDeleted)
|
||||
.AsQueryable();
|
||||
|
||||
if (hideChurned)
|
||||
query = query.Where(c =>
|
||||
!((c.SubscriptionStatus == SubscriptionStatus.Expired || c.SubscriptionStatus == SubscriptionStatus.Canceled)
|
||||
&& c.SubscriptionEndDate != null
|
||||
&& c.SubscriptionEndDate < cutoff));
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(searchTerm))
|
||||
{
|
||||
var s = searchTerm.ToLower();
|
||||
@@ -61,7 +81,7 @@ public class CompanyListService : ICompanyListService
|
||||
.Take(pageSize)
|
||||
.ToListAsync();
|
||||
|
||||
return (companies, totalCount);
|
||||
return (companies, totalCount, churnedCount);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
|
||||
@@ -66,15 +66,16 @@ public class CompaniesController : Controller
|
||||
string sortColumn = "CompanyName",
|
||||
string sortDirection = "asc",
|
||||
int pageNumber = 1,
|
||||
int pageSize = 25)
|
||||
int pageSize = 25,
|
||||
bool showChurned = false)
|
||||
{
|
||||
try
|
||||
{
|
||||
pageNumber = Math.Max(1, pageNumber);
|
||||
pageSize = pageSize is 10 or 25 or 50 or 100 ? pageSize : 25;
|
||||
|
||||
var (companies, totalCount) = await _companyList.GetPagedAsync(
|
||||
searchTerm, sortColumn, sortDirection, pageNumber, pageSize);
|
||||
var (companies, totalCount, churnedCount) = await _companyList.GetPagedAsync(
|
||||
searchTerm, sortColumn, sortDirection, pageNumber, pageSize, hideChurned: !showChurned);
|
||||
|
||||
var companyDtos = _mapper.Map<List<CompanyListDto>>(companies);
|
||||
|
||||
@@ -128,6 +129,8 @@ public class CompaniesController : Controller
|
||||
ViewBag.PageSize = pageSize;
|
||||
ViewBag.TotalPages = (int)Math.Ceiling(totalCount / (double)pageSize);
|
||||
ViewBag.ImpersonatingCompanyId = HttpContext.Session.GetInt32("ImpersonatingCompanyId");
|
||||
ViewBag.ShowChurned = showChurned;
|
||||
ViewBag.ChurnedCount = churnedCount;
|
||||
|
||||
return View(companyDtos);
|
||||
}
|
||||
|
||||
@@ -45,18 +45,30 @@ public class CompanyHealthController : Controller
|
||||
/// user's risk/search filters, so the KPI cards always show platform-wide totals.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public async Task<IActionResult> Index(string? risk, string? search, bool configIssuesOnly = false)
|
||||
public async Task<IActionResult> Index(string? risk, string? search, bool configIssuesOnly = false, bool showChurned = false)
|
||||
{
|
||||
var now = DateTime.UtcNow;
|
||||
var d30 = now.AddDays(-30);
|
||||
var d90 = now.AddDays(-90);
|
||||
var churnedCutoff = now.AddDays(-14);
|
||||
|
||||
// One query per signal — all keyed by CompanyId
|
||||
var companies = await _db.Companies
|
||||
var allCompanies = await _db.Companies
|
||||
.AsNoTracking().IgnoreQueryFilters()
|
||||
.Where(c => !c.IsDeleted)
|
||||
.ToListAsync();
|
||||
|
||||
var churnedCount = allCompanies.Count(c =>
|
||||
(c.SubscriptionStatus == SubscriptionStatus.Expired || c.SubscriptionStatus == SubscriptionStatus.Canceled)
|
||||
&& c.SubscriptionEndDate.HasValue && c.SubscriptionEndDate.Value < churnedCutoff);
|
||||
|
||||
var companies = showChurned
|
||||
? allCompanies
|
||||
: allCompanies.Where(c =>
|
||||
!((c.SubscriptionStatus == SubscriptionStatus.Expired || c.SubscriptionStatus == SubscriptionStatus.Canceled)
|
||||
&& c.SubscriptionEndDate.HasValue && c.SubscriptionEndDate.Value < churnedCutoff))
|
||||
.ToList();
|
||||
|
||||
var lastLogins = await _db.Users
|
||||
.AsNoTracking().IgnoreQueryFilters()
|
||||
.Where(u => u.LastLoginDate != null)
|
||||
@@ -163,6 +175,8 @@ public class CompanyHealthController : Controller
|
||||
ViewBag.Risk = risk;
|
||||
ViewBag.Search = search;
|
||||
ViewBag.ConfigIssuesOnly = configIssuesOnly;
|
||||
ViewBag.ShowChurned = showChurned;
|
||||
ViewBag.ChurnedCount = churnedCount;
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(search))
|
||||
all = all.Where(h =>
|
||||
|
||||
@@ -877,74 +877,6 @@ public class CustomersController : Controller
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Displays a full-screen SMS consent form for the customer to read and agree to.
|
||||
/// Staff opens this page on a tablet and hands it to the customer; no staff account
|
||||
/// interaction is required — the page is scoped to the customer by ID only.
|
||||
/// Redirects back to Details if the customer has already consented.
|
||||
/// </summary>
|
||||
// GET: Customers/SmsConsent/5
|
||||
public async Task<IActionResult> SmsConsent(int id)
|
||||
{
|
||||
var customer = await _unitOfWork.Customers.GetByIdAsync(id);
|
||||
if (customer == null) return NotFound();
|
||||
|
||||
if (customer.NotifyBySms)
|
||||
{
|
||||
this.ToastInfo("This customer has already given SMS consent.");
|
||||
return RedirectToAction(nameof(Details), new { id });
|
||||
}
|
||||
|
||||
var companyId = _tenantContext.GetCurrentCompanyId();
|
||||
if (companyId.HasValue)
|
||||
{
|
||||
var company = await _unitOfWork.Companies.GetByIdAsync(companyId.Value);
|
||||
ViewBag.CompanyName = company?.CompanyName;
|
||||
ViewBag.CompanyLogoUrl = !string.IsNullOrEmpty(company?.LogoFilePath)
|
||||
? Url.Action("Logo", "Kiosk")
|
||||
: null;
|
||||
}
|
||||
|
||||
ViewBag.ShowInactivityTimer = false;
|
||||
ViewBag.CustomerName = $"{customer.ContactFirstName} {customer.ContactLastName}".Trim();
|
||||
if (string.IsNullOrWhiteSpace(ViewBag.CustomerName as string) && !string.IsNullOrEmpty(customer.CompanyName))
|
||||
ViewBag.CustomerName = customer.CompanyName;
|
||||
|
||||
return View(customer.Id);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Records the customer's SMS consent: sets NotifyBySms, SmsConsentedAt (UTC now),
|
||||
/// and SmsConsentMethod = "InPerson". Called when the customer taps "I Agree" on the
|
||||
/// consent form presented by staff.
|
||||
/// </summary>
|
||||
// POST: Customers/SmsConsent/5
|
||||
[HttpPost, ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> SmsConsent(int id, bool agreed)
|
||||
{
|
||||
var customer = await _unitOfWork.Customers.GetByIdAsync(id);
|
||||
if (customer == null) return NotFound();
|
||||
|
||||
if (!agreed)
|
||||
{
|
||||
this.ToastError("Customer did not agree to SMS consent.");
|
||||
return RedirectToAction(nameof(Details), new { id });
|
||||
}
|
||||
|
||||
customer.NotifyBySms = true;
|
||||
customer.SmsConsentedAt = DateTime.UtcNow;
|
||||
customer.SmsConsentMethod = "InPerson";
|
||||
customer.SmsOptedOutAt = null;
|
||||
|
||||
await _unitOfWork.Customers.UpdateAsync(customer);
|
||||
await _unitOfWork.CompleteAsync();
|
||||
|
||||
_logger.LogInformation("SMS consent recorded for customer {CustomerId} via staff-presented form", id);
|
||||
|
||||
this.ToastSuccess($"SMS consent recorded for {customer.ContactFirstName} {customer.ContactLastName}.");
|
||||
return RedirectToAction(nameof(Details), new { id });
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Issues a standalone credit memo and increments the customer's CreditBalance.
|
||||
/// Restricted to CompanyAdmin because credits affect the financial ledger. The memo
|
||||
|
||||
@@ -304,6 +304,32 @@ public class InventoryController : Controller
|
||||
await _unitOfWork.SaveChangesAsync();
|
||||
}
|
||||
|
||||
// Contribute/sync to the platform powder catalog if we have enough identity data.
|
||||
// Runs silently — a failure here never blocks the inventory save.
|
||||
if (!string.IsNullOrWhiteSpace(dto.Manufacturer) && !string.IsNullOrWhiteSpace(dto.ManufacturerPartNumber))
|
||||
{
|
||||
var catalogResult = new InventoryAiLookupResult
|
||||
{
|
||||
Manufacturer = dto.Manufacturer,
|
||||
ManufacturerPartNumber = dto.ManufacturerPartNumber,
|
||||
ColorName = dto.ColorName ?? item.Name,
|
||||
Finish = dto.Finish,
|
||||
CureTemperatureF = dto.CureTemperatureF,
|
||||
CureTimeMinutes = dto.CureTimeMinutes,
|
||||
ColorFamilies = dto.ColorFamilies,
|
||||
RequiresClearCoat = dto.RequiresClearCoat ? true : (bool?)null,
|
||||
CoverageSqFtPerLb = dto.CoverageSqFtPerLb,
|
||||
SpecificGravity = dto.SpecificGravity,
|
||||
TransferEfficiency = dto.TransferEfficiency,
|
||||
UnitCostPerLb = dto.UnitCost > 0 ? dto.UnitCost : null,
|
||||
SpecPageUrl = dto.SpecPageUrl,
|
||||
ImageUrl = dto.ImageUrl,
|
||||
SdsUrl = dto.SdsUrl,
|
||||
TdsUrl = dto.TdsUrl,
|
||||
};
|
||||
await EnrichFromCatalogAsync(catalogResult, autoContribute: true);
|
||||
}
|
||||
|
||||
TempData["Success"] = "Inventory item created successfully.";
|
||||
return RedirectToAction(nameof(Details), new { id = item.Id });
|
||||
}
|
||||
@@ -704,6 +730,8 @@ public class InventoryController : Controller
|
||||
return Json(new { success = false, errorMessage = "No product URL provided." });
|
||||
|
||||
var result = await _aiLookupService.LookupByUrlAsync(productUrl, colorName);
|
||||
if (result.Success)
|
||||
await EnrichFromCatalogAsync(result, autoContribute: true);
|
||||
return Json(result);
|
||||
}
|
||||
|
||||
@@ -750,6 +778,39 @@ public class InventoryController : Controller
|
||||
result.SdsUrl ??= match.SdsUrl;
|
||||
result.TdsUrl ??= match.TdsUrl;
|
||||
if (match.UnitPrice > 0) result.UnitCostPerLb ??= match.UnitPrice;
|
||||
|
||||
// Back-sync: fill NULL catalog fields from the incoming result so the catalog
|
||||
// gets richer over time without overwriting anything already stored.
|
||||
bool catalogDirty = false;
|
||||
if (match.Finish == null && !string.IsNullOrWhiteSpace(result.Finish)) { match.Finish = result.Finish; catalogDirty = true; }
|
||||
if (match.CureTemperatureF == null && result.CureTemperatureF != null) { match.CureTemperatureF = result.CureTemperatureF; catalogDirty = true; }
|
||||
if (match.CureTimeMinutes == null && result.CureTimeMinutes != null) { match.CureTimeMinutes = result.CureTimeMinutes; catalogDirty = true; }
|
||||
if (match.ColorFamilies == null && !string.IsNullOrWhiteSpace(result.ColorFamilies)){ match.ColorFamilies = result.ColorFamilies; catalogDirty = true; }
|
||||
if (match.RequiresClearCoat == null && result.RequiresClearCoat != null) { match.RequiresClearCoat = result.RequiresClearCoat; catalogDirty = true; }
|
||||
if (match.CoverageSqFtPerLb == null && result.CoverageSqFtPerLb != null) { match.CoverageSqFtPerLb = result.CoverageSqFtPerLb; catalogDirty = true; }
|
||||
if (match.SpecificGravity == null && result.SpecificGravity != null) { match.SpecificGravity = result.SpecificGravity; catalogDirty = true; }
|
||||
if (match.TransferEfficiency == null && result.TransferEfficiency != null) { match.TransferEfficiency = result.TransferEfficiency; catalogDirty = true; }
|
||||
if (string.IsNullOrWhiteSpace(match.ImageUrl) && !string.IsNullOrWhiteSpace(result.ImageUrl)) { match.ImageUrl = result.ImageUrl; catalogDirty = true; }
|
||||
if (string.IsNullOrWhiteSpace(match.ProductUrl) && !string.IsNullOrWhiteSpace(result.SpecPageUrl)){ match.ProductUrl = result.SpecPageUrl; catalogDirty = true; }
|
||||
if (string.IsNullOrWhiteSpace(match.SdsUrl) && !string.IsNullOrWhiteSpace(result.SdsUrl)) { match.SdsUrl = result.SdsUrl; catalogDirty = true; }
|
||||
if (string.IsNullOrWhiteSpace(match.TdsUrl) && !string.IsNullOrWhiteSpace(result.TdsUrl)) { match.TdsUrl = result.TdsUrl; catalogDirty = true; }
|
||||
if (match.UnitPrice == 0 && (result.UnitCostPerLb ?? 0) > 0) { match.UnitPrice = result.UnitCostPerLb!.Value; catalogDirty = true; }
|
||||
|
||||
if (catalogDirty)
|
||||
{
|
||||
match.UpdatedAt = DateTime.UtcNow;
|
||||
try
|
||||
{
|
||||
await _unitOfWork.PowderCatalog.UpdateAsync(match);
|
||||
await _unitOfWork.CompleteAsync();
|
||||
_logger.LogInformation("Back-synced catalog gaps for {VendorName} {Sku}", match.VendorName, match.Sku);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Failed to back-sync catalog entry {Id}", match.Id);
|
||||
}
|
||||
}
|
||||
|
||||
return (true, false);
|
||||
}
|
||||
|
||||
@@ -767,6 +828,7 @@ public class InventoryController : Controller
|
||||
VendorName = manufacturer,
|
||||
Sku = sku,
|
||||
ColorName = colorName,
|
||||
UnitPrice = result.UnitCostPerLb ?? 0m,
|
||||
CureTemperatureF = result.CureTemperatureF,
|
||||
CureTimeMinutes = result.CureTimeMinutes,
|
||||
Finish = result.Finish,
|
||||
@@ -1050,61 +1112,50 @@ public class InventoryController : Controller
|
||||
.Select(i => i.ManufacturerPartNumber!.Trim().ToLower())
|
||||
.ToHashSet();
|
||||
|
||||
// When a vendor is specified, search vendor-scoped first. Only widen to all vendors
|
||||
// if the scoped search returns nothing — prevents a cross-vendor color match from
|
||||
// being returned as the only result when the user clearly intended a specific manufacturer.
|
||||
IEnumerable<PowderCatalogItem> matches;
|
||||
if (!string.IsNullOrEmpty(vendorTerm))
|
||||
{
|
||||
matches = await _unitOfWork.PowderCatalog.FindAsync(p =>
|
||||
p.VendorName.ToLower().Contains(vendorTerm) && (
|
||||
p.Sku.ToLower() == term ||
|
||||
p.ColorName.ToLower().Contains(term) ||
|
||||
p.Sku.ToLower().Contains(term)));
|
||||
|
||||
// Fall back to all vendors only when the scoped search finds nothing
|
||||
if (!matches.Any())
|
||||
{
|
||||
matches = await _unitOfWork.PowderCatalog.FindAsync(p =>
|
||||
p.Sku.ToLower() == term ||
|
||||
p.ColorName.ToLower().Contains(term) ||
|
||||
p.Sku.ToLower().Contains(term));
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
matches = await _unitOfWork.PowderCatalog.FindAsync(p =>
|
||||
p.Sku.ToLower() == term ||
|
||||
p.ColorName.ToLower().Contains(term) ||
|
||||
p.Sku.ToLower().Contains(term));
|
||||
}
|
||||
// Single query — all partial color/SKU matches across all vendors.
|
||||
// Results are ranked: exact vendor + exact color (isExact=true) sorts first and
|
||||
// triggers auto-fill in the JS. Everything else goes to the picker modal.
|
||||
// This means a user who typed "Columbia Coatings" + "Lime Green" gets auto-fill
|
||||
// only when that exact product is in the catalog; otherwise they see a ranked modal
|
||||
// with same-vendor results at the top and a "Not Listed — Search Online" escape hatch.
|
||||
var matches = await _unitOfWork.PowderCatalog.FindAsync(p =>
|
||||
p.ColorName.ToLower().Contains(term) ||
|
||||
p.Sku.ToLower() == term ||
|
||||
p.Sku.ToLower().Contains(term));
|
||||
|
||||
var results = matches
|
||||
.Where(p => !existingSkus.Contains(p.Sku.ToLower()))
|
||||
.OrderBy(p => p.Sku.ToLower() == term ? 0 : 1)
|
||||
.ThenBy(p => p.ColorName)
|
||||
.Select(p => new
|
||||
.Select(p =>
|
||||
{
|
||||
id = p.Id,
|
||||
vendorName = p.VendorName,
|
||||
sku = p.Sku,
|
||||
colorName = p.ColorName,
|
||||
description = p.Description,
|
||||
unitPrice = p.UnitPrice,
|
||||
imageUrl = p.ImageUrl,
|
||||
sdsUrl = p.SdsUrl,
|
||||
tdsUrl = p.TdsUrl,
|
||||
applicationGuideUrl = p.ApplicationGuideUrl,
|
||||
productUrl = p.ProductUrl,
|
||||
isDiscontinued = p.IsDiscontinued,
|
||||
cureTemperatureF = p.CureTemperatureF,
|
||||
cureTimeMinutes = p.CureTimeMinutes,
|
||||
finish = p.Finish,
|
||||
colorFamilies = p.ColorFamilies,
|
||||
requiresClearCoat = p.RequiresClearCoat,
|
||||
coverageSqFtPerLb = p.CoverageSqFtPerLb,
|
||||
specificGravity = p.SpecificGravity,
|
||||
transferEfficiency = GetEffectiveTransferEfficiency(p.TransferEfficiency)
|
||||
var vendorMatch = string.IsNullOrEmpty(vendorTerm) || p.VendorName.ToLower().Contains(vendorTerm);
|
||||
var colorExact = p.ColorName.ToLower() == term;
|
||||
return (p, isExact: vendorMatch && colorExact, vendorMatch, colorExact);
|
||||
})
|
||||
.OrderBy(x => x.isExact ? 0 : x.vendorMatch ? 1 : x.colorExact ? 2 : 3)
|
||||
.ThenBy(x => x.p.ColorName)
|
||||
.Select(x => new
|
||||
{
|
||||
id = x.p.Id,
|
||||
vendorName = x.p.VendorName,
|
||||
sku = x.p.Sku,
|
||||
colorName = x.p.ColorName,
|
||||
description = x.p.Description,
|
||||
unitPrice = x.p.UnitPrice,
|
||||
imageUrl = x.p.ImageUrl,
|
||||
sdsUrl = x.p.SdsUrl,
|
||||
tdsUrl = x.p.TdsUrl,
|
||||
applicationGuideUrl = x.p.ApplicationGuideUrl,
|
||||
productUrl = x.p.ProductUrl,
|
||||
isDiscontinued = x.p.IsDiscontinued,
|
||||
isExact = x.isExact,
|
||||
cureTemperatureF = x.p.CureTemperatureF,
|
||||
cureTimeMinutes = x.p.CureTimeMinutes,
|
||||
finish = x.p.Finish,
|
||||
colorFamilies = x.p.ColorFamilies,
|
||||
requiresClearCoat = x.p.RequiresClearCoat,
|
||||
coverageSqFtPerLb = x.p.CoverageSqFtPerLb,
|
||||
specificGravity = x.p.SpecificGravity,
|
||||
transferEfficiency = GetEffectiveTransferEfficiency(x.p.TransferEfficiency)
|
||||
})
|
||||
.ToList();
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ using AutoMapper;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.SignalR;
|
||||
using Microsoft.Extensions.Caching.Memory;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using PowderCoating.Application.DTOs.Kiosk;
|
||||
using PowderCoating.Application.Interfaces;
|
||||
@@ -39,6 +40,9 @@ public class KioskController : Controller
|
||||
private readonly IHubContext<KioskHub> _kioskHub;
|
||||
private readonly ILogger<KioskController> _logger;
|
||||
private readonly ICompanyLogoService _logoService;
|
||||
private readonly IMemoryCache _cache;
|
||||
|
||||
private static string SmsConsentCacheKey(int companyId) => $"kiosk-sms-consent:{companyId}";
|
||||
|
||||
/// <summary>Initialises all dependencies for the kiosk controller.</summary>
|
||||
public KioskController(
|
||||
@@ -49,7 +53,8 @@ public class KioskController : Controller
|
||||
IEmailService emailService,
|
||||
IHubContext<KioskHub> kioskHub,
|
||||
ILogger<KioskController> logger,
|
||||
ICompanyLogoService logoService)
|
||||
ICompanyLogoService logoService,
|
||||
IMemoryCache cache)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_mapper = mapper;
|
||||
@@ -59,6 +64,7 @@ public class KioskController : Controller
|
||||
_kioskHub = kioskHub;
|
||||
_logger = logger;
|
||||
_logoService = logoService;
|
||||
_cache = cache;
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
@@ -104,6 +110,10 @@ public class KioskController : Controller
|
||||
if (company == null || company.KioskActivationToken != cookie.Value.token)
|
||||
return Json(new { hasSession = false });
|
||||
|
||||
// Check for a staff-pushed SMS consent request before checking for intake sessions.
|
||||
if (_cache.TryGetValue(SmsConsentCacheKey(cookie.Value.companyId), out (int customerId, string customerName) pending))
|
||||
return Json(new { hasSession = false, smsConsentPending = true, customerId = pending.customerId, customerName = pending.customerName });
|
||||
|
||||
var window = DateTime.UtcNow.AddSeconds(-60);
|
||||
var session = await _unitOfWork.KioskSessions.FirstOrDefaultAsync(
|
||||
s => s.CompanyId == cookie.Value.companyId
|
||||
@@ -116,6 +126,116 @@ public class KioskController : Controller
|
||||
return Json(new { hasSession = true, sessionToken = session.SessionToken });
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// SMS CONSENT (staff pushes to kiosk; customer agrees on tablet)
|
||||
// =========================================================================
|
||||
|
||||
/// <summary>
|
||||
/// Staff calls this (authenticated) from the Customer Details page to push an SMS
|
||||
/// consent request to the front-desk kiosk tablet. Stores the customer ID in
|
||||
/// IMemoryCache under a company-scoped key; the kiosk's PollSession endpoint picks
|
||||
/// it up and returns smsConsentPending so the tablet can navigate to the consent page.
|
||||
/// The cache entry expires in 10 minutes in case the customer never approaches the tablet.
|
||||
/// </summary>
|
||||
[HttpPost, ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> PushSmsConsent(int customerId)
|
||||
{
|
||||
var customer = await _unitOfWork.Customers.GetByIdAsync(customerId);
|
||||
if (customer == null) return Json(new { success = false, message = "Customer not found." });
|
||||
|
||||
if (customer.NotifyBySms)
|
||||
return Json(new { success = false, message = "Customer has already given SMS consent." });
|
||||
|
||||
var companyId = customer.CompanyId;
|
||||
var name = !string.IsNullOrWhiteSpace(customer.ContactFirstName)
|
||||
? $"{customer.ContactFirstName} {customer.ContactLastName}".Trim()
|
||||
: customer.CompanyName ?? "Customer";
|
||||
|
||||
_cache.Set(SmsConsentCacheKey(companyId), (customerId, name),
|
||||
new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10) });
|
||||
|
||||
_logger.LogInformation("SMS consent pushed to kiosk for customer {CustomerId} by staff", customerId);
|
||||
return Json(new { success = true });
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Cancels a pending kiosk SMS consent request, freeing the kiosk to return to the Welcome
|
||||
/// screen. Called by staff if they pushed consent accidentally or the customer isn't coming.
|
||||
/// </summary>
|
||||
[HttpPost, ValidateAntiForgeryToken]
|
||||
public IActionResult CancelSmsConsent()
|
||||
{
|
||||
var companyId = HttpContext.User.FindFirst("CompanyId")?.Value;
|
||||
if (int.TryParse(companyId, out var cid))
|
||||
_cache.Remove(SmsConsentCacheKey(cid));
|
||||
return Json(new { success = true });
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Displays the full-screen SMS consent form on the kiosk tablet (anonymous, kiosk layout).
|
||||
/// Loads the customer by ID with ignoreQueryFilters because the kiosk has no tenant context.
|
||||
/// </summary>
|
||||
[AllowAnonymous]
|
||||
public async Task<IActionResult> SmsConsent(int id)
|
||||
{
|
||||
var cookie = ReadKioskCookie();
|
||||
if (cookie == null) return Forbid();
|
||||
|
||||
// Clear the pending entry immediately — the kiosk is now showing the form,
|
||||
// so Welcome must not redirect again if the customer cancels or navigates back.
|
||||
_cache.Remove(SmsConsentCacheKey(cookie.Value.companyId));
|
||||
|
||||
var customer = await _unitOfWork.Customers.GetByIdAsync(id, ignoreQueryFilters: true);
|
||||
if (customer == null) return NotFound();
|
||||
|
||||
var company = await _unitOfWork.Companies.GetByIdAsync(cookie.Value.companyId, ignoreQueryFilters: true);
|
||||
ViewBag.CompanyName = company?.CompanyName;
|
||||
ViewBag.CompanyLogoUrl = !string.IsNullOrEmpty(company?.LogoFilePath) ? Url.Action("Logo", "Kiosk") : null;
|
||||
ViewBag.ShowInactivityTimer = false;
|
||||
ViewBag.CustomerName = !string.IsNullOrWhiteSpace(customer.ContactFirstName)
|
||||
? $"{customer.ContactFirstName} {customer.ContactLastName}".Trim()
|
||||
: customer.CompanyName ?? "Customer";
|
||||
|
||||
return View(id);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Records the customer's SMS consent from the kiosk tablet.
|
||||
/// Sets NotifyBySms, SmsConsentedAt, SmsConsentMethod = "KioskInPerson" on the customer record.
|
||||
/// Cache is already cleared by the GET; this handles the agree/decline outcome.
|
||||
/// </summary>
|
||||
[AllowAnonymous, HttpPost]
|
||||
public async Task<IActionResult> SmsConsent(int id, bool agreed)
|
||||
{
|
||||
var cookie = ReadKioskCookie();
|
||||
if (cookie == null) return Forbid();
|
||||
|
||||
if (agreed)
|
||||
{
|
||||
var customer = await _unitOfWork.Customers.GetByIdAsync(id, ignoreQueryFilters: true);
|
||||
if (customer != null)
|
||||
{
|
||||
customer.NotifyBySms = true;
|
||||
customer.SmsConsentedAt = DateTime.UtcNow;
|
||||
customer.SmsConsentMethod = "KioskInPerson";
|
||||
customer.SmsOptedOutAt = null;
|
||||
await _unitOfWork.Customers.UpdateAsync(customer);
|
||||
await _unitOfWork.CompleteAsync();
|
||||
_logger.LogInformation("SMS consent recorded via kiosk for customer {CustomerId}", id);
|
||||
|
||||
await _inApp.CreateAsync(
|
||||
customer.CompanyId,
|
||||
"SMS Consent Recorded",
|
||||
$"{customer.ContactFirstName} {customer.ContactLastName} agreed to SMS notifications on the kiosk.",
|
||||
"KioskConsent",
|
||||
link: $"/Customers/Details/{id}",
|
||||
customerId: id);
|
||||
}
|
||||
}
|
||||
|
||||
return Redirect("/Kiosk/Welcome");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Serves the company logo for anonymous kiosk pages. Resolves the company from the
|
||||
/// KioskDevice cookie so no tenant context is needed on the anonymous request.
|
||||
|
||||
@@ -72,6 +72,7 @@ public class InAppNotificationService : IInAppNotificationService
|
||||
message = notification.Message,
|
||||
link = notification.Link,
|
||||
notificationType = notification.NotificationType,
|
||||
customerId = notification.CustomerId,
|
||||
createdAt = now.ToString("o")
|
||||
});
|
||||
}
|
||||
|
||||
@@ -26,11 +26,13 @@
|
||||
var totalPages = (int)(ViewBag.TotalPages ?? 1);
|
||||
var totalCount = (int)(ViewBag.TotalCount ?? 0);
|
||||
var impersonatingId = (int?)(ViewBag.ImpersonatingCompanyId);
|
||||
var showChurned = (bool)(ViewBag.ShowChurned ?? false);
|
||||
var churnedCount = (int)(ViewBag.ChurnedCount ?? 0);
|
||||
|
||||
string SortLink(string col)
|
||||
{
|
||||
var dir = (sortColumn == col && sortDirection == "asc") ? "desc" : "asc";
|
||||
return Url.Action("Index", new { searchTerm, sortColumn = col, sortDirection = dir, pageNumber = 1, pageSize })!;
|
||||
return Url.Action("Index", new { searchTerm, sortColumn = col, sortDirection = dir, pageNumber = 1, pageSize, showChurned })!;
|
||||
}
|
||||
|
||||
string SortIcon(string col)
|
||||
@@ -54,6 +56,7 @@
|
||||
<input type="hidden" name="sortColumn" value="@sortColumn" />
|
||||
<input type="hidden" name="sortDirection" value="@sortDirection" />
|
||||
<input type="hidden" name="pageSize" value="@pageSize" />
|
||||
<input type="hidden" name="showChurned" value="@showChurned.ToString().ToLower()" />
|
||||
<div class="col-md-6">
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="bi bi-search"></i></span>
|
||||
@@ -75,6 +78,25 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (churnedCount > 0 && !showChurned)
|
||||
{
|
||||
<div class="alert alert-secondary alert-permanent d-flex align-items-center gap-2 mb-3 py-2">
|
||||
<i class="bi bi-eye-slash text-muted"></i>
|
||||
<span class="small"><strong>@churnedCount</strong> churned @(churnedCount == 1 ? "account" : "accounts") (expired or canceled 14+ days ago) hidden.</span>
|
||||
<a href="@Url.Action("Index", new { searchTerm, sortColumn, sortDirection, pageNumber = 1, pageSize, showChurned = true })"
|
||||
class="btn btn-sm btn-outline-secondary ms-auto py-0">Show churned</a>
|
||||
</div>
|
||||
}
|
||||
else if (showChurned && churnedCount > 0)
|
||||
{
|
||||
<div class="alert alert-warning alert-permanent d-flex align-items-center gap-2 mb-3 py-2">
|
||||
<i class="bi bi-eye text-warning"></i>
|
||||
<span class="small">Showing all accounts including <strong>@churnedCount</strong> churned.</span>
|
||||
<a href="@Url.Action("Index", new { searchTerm, sortColumn, sortDirection, pageNumber = 1, pageSize, showChurned = false })"
|
||||
class="btn btn-sm btn-outline-secondary ms-auto py-0">Hide churned</a>
|
||||
</div>
|
||||
}
|
||||
|
||||
<div class="card shadow-sm">
|
||||
<div class="card-body p-0">
|
||||
@if (Model != null && Model.Any())
|
||||
@@ -313,18 +335,18 @@
|
||||
<nav>
|
||||
<ul class="pagination pagination-sm mb-0">
|
||||
<li class="page-item @(pageNumber == 1 ? "disabled" : "")">
|
||||
<a class="page-link" href="@Url.Action("Index", new { searchTerm, sortColumn, sortDirection, pageNumber = pageNumber - 1, pageSize })">
|
||||
<a class="page-link" href="@Url.Action("Index", new { searchTerm, sortColumn, sortDirection, pageNumber = pageNumber - 1, pageSize, showChurned })">
|
||||
<i class="bi bi-chevron-left"></i>
|
||||
</a>
|
||||
</li>
|
||||
@for (int p = Math.Max(1, pageNumber - 2); p <= Math.Min(totalPages, pageNumber + 2); p++)
|
||||
{
|
||||
<li class="page-item @(p == pageNumber ? "active" : "")">
|
||||
<a class="page-link" href="@Url.Action("Index", new { searchTerm, sortColumn, sortDirection, pageNumber = p, pageSize })">@p</a>
|
||||
<a class="page-link" href="@Url.Action("Index", new { searchTerm, sortColumn, sortDirection, pageNumber = p, pageSize, showChurned })">@p</a>
|
||||
</li>
|
||||
}
|
||||
<li class="page-item @(pageNumber == totalPages ? "disabled" : "")">
|
||||
<a class="page-link" href="@Url.Action("Index", new { searchTerm, sortColumn, sortDirection, pageNumber = pageNumber + 1, pageSize })">
|
||||
<a class="page-link" href="@Url.Action("Index", new { searchTerm, sortColumn, sortDirection, pageNumber = pageNumber + 1, pageSize, showChurned })">
|
||||
<i class="bi bi-chevron-right"></i>
|
||||
</a>
|
||||
</li>
|
||||
@@ -464,6 +486,7 @@
|
||||
const url = new URL(window.location.href);
|
||||
url.searchParams.set('pageSize', size);
|
||||
url.searchParams.set('pageNumber', '1');
|
||||
url.searchParams.set('showChurned', '@showChurned.ToString().ToLower()');
|
||||
window.location.href = url.toString();
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,9 @@
|
||||
@{
|
||||
ViewData["Title"] = "Company Health";
|
||||
|
||||
var showChurned = (bool)(ViewBag.ShowChurned ?? false);
|
||||
var churnedCount = (int)(ViewBag.ChurnedCount ?? 0);
|
||||
|
||||
string RiskBadge(ChurnRisk r) => r switch {
|
||||
ChurnRisk.Healthy => "bg-success",
|
||||
ChurnRisk.AtRisk => "bg-warning text-dark",
|
||||
@@ -73,6 +76,26 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@* Churned account visibility banner *@
|
||||
@if (churnedCount > 0 && !showChurned)
|
||||
{
|
||||
<div class="alert alert-secondary alert-permanent d-flex align-items-center gap-2 mb-3 py-2">
|
||||
<i class="bi bi-eye-slash text-muted"></i>
|
||||
<span class="small"><strong>@churnedCount</strong> churned @(churnedCount == 1 ? "account" : "accounts") (expired or canceled 14+ days ago) hidden from scores and totals.</span>
|
||||
<a href="@Url.Action("Index", new { risk = ViewBag.Risk, search = ViewBag.Search, configIssuesOnly = ViewBag.ConfigIssuesOnly, showChurned = true })"
|
||||
class="btn btn-sm btn-outline-secondary ms-auto py-0">Show churned</a>
|
||||
</div>
|
||||
}
|
||||
else if (showChurned && churnedCount > 0)
|
||||
{
|
||||
<div class="alert alert-warning alert-permanent d-flex align-items-center gap-2 mb-3 py-2">
|
||||
<i class="bi bi-eye text-warning"></i>
|
||||
<span class="small">Showing all accounts including <strong>@churnedCount</strong> churned.</span>
|
||||
<a href="@Url.Action("Index", new { risk = ViewBag.Risk, search = ViewBag.Search, configIssuesOnly = ViewBag.ConfigIssuesOnly, showChurned = false })"
|
||||
class="btn btn-sm btn-outline-secondary ms-auto py-0">Hide churned</a>
|
||||
</div>
|
||||
}
|
||||
|
||||
@* Summary stat cards *@
|
||||
<div class="row g-3 mb-3">
|
||||
<div class="col-6 col-lg-3">
|
||||
@@ -193,6 +216,7 @@
|
||||
<label class="form-check-label small" for="configOnly">Config issues only</label>
|
||||
</div>
|
||||
</div>
|
||||
<input type="hidden" name="showChurned" value="@showChurned.ToString().ToLower()" />
|
||||
<div class="col-auto">
|
||||
<button class="btn btn-sm btn-primary">Filter</button>
|
||||
<a asp-action="Index" class="btn btn-sm btn-outline-secondary ms-1">Clear</a>
|
||||
|
||||
@@ -173,6 +173,7 @@
|
||||
<i class="bi bi-envelope-slash me-1"></i>Email off
|
||||
</span>
|
||||
}
|
||||
<span id="sms-status-section">
|
||||
@if (Model.NotifyBySms)
|
||||
{
|
||||
<span class="badge bg-success bg-opacity-10 text-success border border-success border-opacity-25"
|
||||
@@ -185,12 +186,22 @@
|
||||
<span class="badge bg-secondary bg-opacity-10 text-secondary border border-secondary border-opacity-25">
|
||||
<i class="bi bi-chat-slash me-1"></i>SMS off
|
||||
</span>
|
||||
<a href="/Customers/SmsConsent/@Model.Id"
|
||||
class="badge bg-primary bg-opacity-10 text-primary border border-primary border-opacity-25 text-decoration-none"
|
||||
title="Present SMS consent form to customer">
|
||||
<button type="button" id="btnGetSmsConsent"
|
||||
class="badge bg-primary bg-opacity-10 text-primary border border-primary border-opacity-25 border-0"
|
||||
style="cursor:pointer;"
|
||||
title="Send SMS consent form to the front-desk kiosk tablet"
|
||||
onclick="pushSmsConsent(@Model.Id)">
|
||||
<i class="bi bi-chat-dots me-1"></i>Get SMS Consent
|
||||
</a>
|
||||
</button>
|
||||
<button type="button" id="btnCancelSmsConsent"
|
||||
class="badge bg-warning bg-opacity-10 text-warning border border-warning border-opacity-25 border-0 d-none"
|
||||
style="cursor:pointer;"
|
||||
title="Cancel the pending kiosk consent request"
|
||||
onclick="cancelSmsConsent()">
|
||||
<i class="bi bi-x-circle me-1"></i>Cancel Consent
|
||||
</button>
|
||||
}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -549,3 +560,8 @@
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
@section Scripts {
|
||||
<script src="~/js/customer-details.js" asp-append-version="true"></script>
|
||||
}
|
||||
|
||||
|
||||
+10
-2
@@ -9,7 +9,7 @@
|
||||
<h2 class="fw-bold mb-1" style="font-size:1.6rem;">SMS Notifications</h2>
|
||||
<p class="text-muted mb-4">Please read the following and tap <strong>I Agree</strong> to opt in.</p>
|
||||
|
||||
<form method="post" action="/Customers/SmsConsent/@Model">
|
||||
<form method="post" action="/Kiosk/SmsConsent/@Model">
|
||||
@Html.AntiForgeryToken()
|
||||
<input type="hidden" name="agreed" value="true" />
|
||||
|
||||
@@ -33,7 +33,9 @@
|
||||
</div>
|
||||
|
||||
<div class="d-flex gap-3">
|
||||
<a href="/Customers/Details/@Model" class="btn btn-outline-secondary"
|
||||
<a href="/Kiosk/SmsConsent/@Model?agreed=false"
|
||||
onclick="event.preventDefault(); document.getElementById('declineForm').submit();"
|
||||
class="btn btn-outline-secondary"
|
||||
style="min-height:64px;border-radius:12px;font-size:1.1rem;flex:0 0 auto;padding:0 2rem;">
|
||||
<i class="bi bi-x-lg me-1"></i> No Thanks
|
||||
</a>
|
||||
@@ -42,4 +44,10 @@
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
@* Separate form for decline so "No Thanks" can POST with agreed=false *@
|
||||
<form id="declineForm" method="post" action="/Kiosk/SmsConsent/@Model" style="display:none;">
|
||||
@Html.AntiForgeryToken()
|
||||
<input type="hidden" name="agreed" value="false" />
|
||||
</form>
|
||||
</div>
|
||||
@@ -1914,7 +1914,8 @@
|
||||
const icons = {
|
||||
QuoteApproved: { icon: 'bi-check-circle-fill', cls: 'success', title: 'Quote Approved' },
|
||||
QuoteDeclined: { icon: 'bi-x-circle-fill', cls: 'danger', title: 'Quote Declined' },
|
||||
InvoicePaid: { icon: 'bi-cash-coin', cls: 'primary', title: 'Payment Received' }
|
||||
InvoicePaid: { icon: 'bi-cash-coin', cls: 'primary', title: 'Payment Received' },
|
||||
KioskConsent: { icon: 'bi-chat-fill', cls: 'success', title: 'SMS Consent' }
|
||||
};
|
||||
const t = icons[data.notificationType] || { icon: 'bi-bell', cls: 'info', title: 'Notification' };
|
||||
toastr[t.cls === 'danger' ? 'warning' : t.cls === 'primary' ? 'info' : 'success'](
|
||||
@@ -1922,6 +1923,12 @@
|
||||
`<i class="bi ${t.icon} me-1"></i>${t.title}`,
|
||||
{ timeOut: 10000, extendedTimeOut: 3000, closeButton: true, enableHtml: true }
|
||||
);
|
||||
if (data.notificationType === 'KioskConsent' && data.customerId) {
|
||||
const path = window.location.pathname.toLowerCase();
|
||||
if (path === `/customers/details/${data.customerId}`) {
|
||||
window.updateCustomerSmsStatus?.();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
connection.start().catch(err => console.warn('SignalR connection failed:', err));
|
||||
@@ -2101,8 +2108,14 @@
|
||||
});
|
||||
});
|
||||
|
||||
// Load on page ready
|
||||
document.addEventListener('DOMContentLoaded', load);
|
||||
// Load on page ready and refresh when dropdown is opened
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
load();
|
||||
btn?.addEventListener('show.bs.dropdown', load);
|
||||
});
|
||||
|
||||
// Fallback poll every 60 s in case SignalR misses a push
|
||||
setInterval(load, 60_000);
|
||||
|
||||
return { addItem, incrementBadge, markAllRead, openDetail, markRead };
|
||||
})();
|
||||
|
||||
@@ -60,6 +60,14 @@ body.kiosk-body {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
/* Vertically centre content in any tall kiosk button (covers <a> and <button>) */
|
||||
.kiosk-body .btn,
|
||||
.kiosk-btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
/* Suppress all hover effects on touch screens */
|
||||
@media (hover: none) {
|
||||
.kiosk-body .btn:hover { filter: none; opacity: 1; }
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
"use strict";
|
||||
|
||||
async function pushSmsConsent(customerId) {
|
||||
const tok = document.querySelector('input[name="__RequestVerificationToken"]')?.value ?? '';
|
||||
try {
|
||||
const res = await fetch(`/Kiosk/PushSmsConsent?customerId=${customerId}`, {
|
||||
method: 'POST',
|
||||
headers: { 'RequestVerificationToken': tok }
|
||||
});
|
||||
const data = await res.json();
|
||||
if (data.success) {
|
||||
toastr.success('Consent form sent to the kiosk tablet — hand it to the customer.', 'Sent to Kiosk');
|
||||
document.getElementById('btnGetSmsConsent')?.classList.add('d-none');
|
||||
document.getElementById('btnCancelSmsConsent')?.classList.remove('d-none');
|
||||
} else {
|
||||
toastr.warning(data.message || 'Could not send consent to kiosk.');
|
||||
}
|
||||
} catch {
|
||||
toastr.error('An error occurred. Please try again.');
|
||||
}
|
||||
}
|
||||
|
||||
async function cancelSmsConsent() {
|
||||
const tok = document.querySelector('input[name="__RequestVerificationToken"]')?.value ?? '';
|
||||
try {
|
||||
const res = await fetch('/Kiosk/CancelSmsConsent', {
|
||||
method: 'POST',
|
||||
headers: { 'RequestVerificationToken': tok }
|
||||
});
|
||||
const data = await res.json();
|
||||
if (data.success) {
|
||||
toastr.info('Consent request cancelled — kiosk is free.');
|
||||
document.getElementById('btnCancelSmsConsent')?.classList.add('d-none');
|
||||
document.getElementById('btnGetSmsConsent')?.classList.remove('d-none');
|
||||
}
|
||||
} catch {
|
||||
toastr.error('An error occurred. Please try again.');
|
||||
}
|
||||
}
|
||||
|
||||
window.updateCustomerSmsStatus = function () {
|
||||
const section = document.getElementById('sms-status-section');
|
||||
if (!section) return;
|
||||
const today = new Date().toLocaleDateString('en-US', { month: '2-digit', day: '2-digit', year: 'numeric' });
|
||||
section.innerHTML = `<span class="badge bg-success bg-opacity-10 text-success border border-success border-opacity-25"
|
||||
title="Consented ${today}">
|
||||
<i class="bi bi-chat-fill me-1"></i>SMS on
|
||||
</span>`;
|
||||
};
|
||||
@@ -62,23 +62,25 @@
|
||||
const items = await resp.json();
|
||||
|
||||
if (items.length === 0) {
|
||||
// No catalog match — fall back to AI if available
|
||||
hideStatus();
|
||||
if (typeof window._runInventoryAiLookup === 'function') {
|
||||
showStatus('info', '<span class="spinner-border spinner-border-sm me-1"></span>Not in catalog — searching with AI…');
|
||||
await window._runInventoryAiLookup();
|
||||
} else {
|
||||
showStatus('warning', 'No match found in the catalog. Enter details manually or enable AI Lookup.');
|
||||
}
|
||||
// Nothing in catalog — go straight to AI
|
||||
await runAiOrWarn();
|
||||
return;
|
||||
}
|
||||
|
||||
if (items.length === 1) {
|
||||
// Single exact match (vendor + color name both match precisely) — auto-fill
|
||||
if (items.length === 1 && items[0].isExact) {
|
||||
await fillFields(items[0]);
|
||||
return;
|
||||
}
|
||||
|
||||
// Multiple matches — let the user pick via modal
|
||||
// Exact match exists but so do other results — auto-fill the exact one
|
||||
const exactMatches = items.filter(i => i.isExact);
|
||||
if (exactMatches.length === 1) {
|
||||
await fillFields(exactMatches[0]);
|
||||
return;
|
||||
}
|
||||
|
||||
// No exact match (or ambiguous) — show picker modal with "Not Listed" escape hatch
|
||||
hideStatus();
|
||||
showPickerModal(items);
|
||||
|
||||
@@ -89,6 +91,18 @@
|
||||
}
|
||||
});
|
||||
|
||||
// ── AI fallback helper ───────────────────────────────────────────────────
|
||||
|
||||
async function runAiOrWarn() {
|
||||
hideStatus();
|
||||
if (typeof window._runInventoryAiLookup === 'function') {
|
||||
showStatus('info', '<span class="spinner-border spinner-border-sm me-1"></span>Not in catalog — searching online with AI…');
|
||||
await window._runInventoryAiLookup();
|
||||
} else {
|
||||
showStatus('warning', 'No match found in the catalog. Enter details manually or enable AI Lookup.');
|
||||
}
|
||||
}
|
||||
|
||||
// ── Fill fields from a catalog result ────────────────────────────────────
|
||||
|
||||
async function fillFields(item) {
|
||||
@@ -368,6 +382,12 @@
|
||||
<div class="modal-body p-0">
|
||||
<div class="list-group list-group-flush">${rows}</div>
|
||||
</div>
|
||||
<div class="modal-footer py-2 justify-content-start">
|
||||
<button type="button" class="btn btn-sm btn-outline-secondary" id="catalogPickerNotListed">
|
||||
<i class="bi bi-search me-1"></i>Not listed — search online
|
||||
</button>
|
||||
<span class="text-muted small ms-2">Uses AI to look up the exact product</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>`;
|
||||
@@ -383,6 +403,11 @@
|
||||
});
|
||||
});
|
||||
|
||||
document.getElementById('catalogPickerNotListed').addEventListener('click', function () {
|
||||
bsModal.hide();
|
||||
runAiOrWarn();
|
||||
});
|
||||
|
||||
bsModal.show();
|
||||
}
|
||||
|
||||
|
||||
@@ -26,6 +26,12 @@
|
||||
if (!res.ok) throw new Error("HTTP " + res.status);
|
||||
const data = await res.json();
|
||||
setStatus("#16a34a", "Ready");
|
||||
if (data.smsConsentPending && data.customerId) {
|
||||
active = false;
|
||||
setStatus("#2563eb", "Loading consent…");
|
||||
window.location.href = `/Kiosk/SmsConsent/${data.customerId}`;
|
||||
return;
|
||||
}
|
||||
if (data.hasSession && data.sessionToken) {
|
||||
active = false;
|
||||
setStatus("#2563eb", "Starting…");
|
||||
|
||||
Reference in New Issue
Block a user