Created
August 11, 2023 09:20
-
-
Save jackbillstrom/c140c0fdcd6066603b12670b012980a6 to your computer and use it in GitHub Desktop.
Custom OrderID for Vendr Orders
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.Extensions.DependencyInjection; | |
using Umbraco.Cms.Core.Composing; | |
using Umbraco.Cms.Core.DependencyInjection; | |
using Vendr.Core.Generators; | |
namespace My.Ecommerce.Web.Compositions; | |
public class CustomComposer : IComposer | |
{ | |
public void Compose(IUmbracoBuilder builder) | |
{ | |
// Överskugga standard IOrderNumberGenerator med vår anpassade. | |
builder.Services.AddSingleton<IOrderNumberGenerator, CustomOrderNumberGenerator>(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Vendr.Core.Generators; | |
namespace My.Ecommerce.Web.Extensions; | |
public class CustomOrderNumberGenerator : IOrderNumberGenerator | |
{ | |
private static readonly DateTime StartDate = new DateTime(2020, 1, 1); | |
private static int _lastSecond; | |
private static int _counter; | |
private static readonly object LockObj = new object(); // Objektet används för låsning av trådar | |
// Genererar ett slumpmässigt nummer baserat på tiden och en räknare | |
private string GenerateRandomNumber() | |
{ | |
var now = DateTime.UtcNow; | |
var totalSeconds = (int)(now - StartDate).TotalSeconds; | |
lock (LockObj) // Lås på LockObj istället | |
{ | |
if (_lastSecond != now.Second) | |
{ | |
_lastSecond = now.Second; | |
_counter = 0; | |
} | |
else | |
{ | |
_counter = (_counter + 1) % 100; // Nollställ om det når 100 | |
} | |
return totalSeconds.ToString("D7") + _counter.ToString("D2"); | |
} | |
} | |
public string GenerateCartNumber(Guid storeId) | |
{ | |
return "C" + GenerateRandomNumber(); | |
} | |
public string GenerateOrderNumber(Guid storeId) | |
{ | |
return "W" + GenerateRandomNumber(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output example:
W11390823500
Can maximum handle up to 99 orders per second tho.