E Gift Card SaaS C#
👤 Sharing: AI
```csharp
using System;
using System.Collections.Generic;
using System.Linq;
// Represents a simple e-gift card
public class GiftCard
{
public string CardNumber { get; set; } // Unique card number
public decimal Balance { get; set; } // Current balance on the card
public DateTime ExpiryDate { get; set; } // Expiry date of the card
public bool IsActive { get; set; } // Indicates if the card is active or redeemed
public GiftCard(string cardNumber, decimal initialBalance, DateTime expiryDate)
{
CardNumber = cardNumber;
Balance = initialBalance;
ExpiryDate = expiryDate;
IsActive = true;
}
public bool Redeem(decimal amount)
{
if (!IsActive)
{
Console.WriteLine("Gift card is not active.");
return false;
}
if (ExpiryDate < DateTime.Now)
{
Console.WriteLine("Gift card has expired.");
return false;
}
if (amount <= 0)
{
Console.WriteLine("Invalid redemption amount.");
return false;
}
if (amount > Balance)
{
Console.WriteLine("Insufficient balance on the gift card.");
return false;
}
Balance -= amount;
Console.WriteLine($"Redeemed ${amount} from gift card {CardNumber}. Remaining balance: ${Balance}");
if (Balance == 0)
{
IsActive = false; // Deactivate the card if the balance is zero
Console.WriteLine($"Gift card {CardNumber} has been fully redeemed and is now deactivated.");
}
return true;
}
public void Deactivate()
{
IsActive = false;
Console.WriteLine($"Gift card {CardNumber} has been manually deactivated.");
}
}
// Represents a simple e-gift card service/SaaS
public class GiftCardService
{
private List<GiftCard> giftCards = new List<GiftCard>();
// Generates a unique gift card number
private string GenerateCardNumber()
{
// A very basic card number generation. In a real system,
// you'd want a more robust and collision-resistant method.
return Guid.NewGuid().ToString().Substring(0, 12).ToUpper();
}
// Issues a new gift card
public GiftCard IssueGiftCard(decimal initialBalance, DateTime expiryDate)
{
if (initialBalance <= 0)
{
Console.WriteLine("Invalid initial balance. Must be greater than zero.");
return null; // Or throw an exception
}
if (expiryDate <= DateTime.Now)
{
Console.WriteLine("Invalid expiry date. Must be in the future.");
return null; // Or throw an exception
}
string cardNumber = GenerateCardNumber();
GiftCard newCard = new GiftCard(cardNumber, initialBalance, expiryDate);
giftCards.Add(newCard);
Console.WriteLine($"Gift card {cardNumber} issued with initial balance of ${initialBalance} and expiry date {expiryDate.ToShortDateString()}");
return newCard;
}
// Retrieves a gift card by its card number
public GiftCard GetGiftCard(string cardNumber)
{
return giftCards.FirstOrDefault(card => card.CardNumber == cardNumber);
}
// Lists all gift cards (for admin purposes, not for general use)
public List<GiftCard> ListAllGiftCards()
{
return giftCards;
}
// Method to simulate bulk card issuance
public List<GiftCard> IssueBulkGiftCards(int numberOfCards, decimal initialBalance, DateTime expiryDate)
{
List<GiftCard> issuedCards = new List<GiftCard>();
for(int i = 0; i < numberOfCards; i++)
{
GiftCard card = IssueGiftCard(initialBalance, expiryDate);
if(card != null)
{
issuedCards.Add(card);
}
}
return issuedCards;
}
//Deactivates a gift card by card number
public bool DeactivateGiftCard(string cardNumber)
{
GiftCard card = GetGiftCard(cardNumber);
if (card == null)
{
Console.WriteLine($"Gift card with number {cardNumber} not found.");
return false;
}
if (!card.IsActive)
{
Console.WriteLine($"Gift card {cardNumber} is already deactivated.");
return true; // Or return false depending on desired behavior
}
card.Deactivate();
return true;
}
}
public class Program
{
public static void Main(string[] args)
{
// Initialize the Gift Card Service
GiftCardService giftCardService = new GiftCardService();
// Issue a new gift card
DateTime expiryDate = DateTime.Now.AddMonths(6);
GiftCard card1 = giftCardService.IssueGiftCard(100.00m, expiryDate);
if(card1 != null) // Check if card was issued successfully. Handles nulls.
{
// Retrieve the gift card by card number
GiftCard retrievedCard = giftCardService.GetGiftCard(card1.CardNumber);
if (retrievedCard != null)
{
Console.WriteLine($"Card Number: {retrievedCard.CardNumber}, Balance: {retrievedCard.Balance}, Expiry: {retrievedCard.ExpiryDate.ToShortDateString()}, Active: {retrievedCard.IsActive}");
// Redeem some amount from the card
retrievedCard.Redeem(25.00m);
// Redeem more than the available balance
retrievedCard.Redeem(100.00m); // Should print "Insufficient balance"
// Redeem the remaining balance
retrievedCard.Redeem(75.00m);
Console.WriteLine($"Card Number: {retrievedCard.CardNumber}, Balance: {retrievedCard.Balance}, Expiry: {retrievedCard.ExpiryDate.ToShortDateString()}, Active: {retrievedCard.IsActive}");
//Attempt to redeem from an inactive card.
retrievedCard.Redeem(10.00m); //Should output "Gift Card is not active"
//Try to deactivate it again (should report that it is already deactivated
giftCardService.DeactivateGiftCard(retrievedCard.CardNumber);
}
else
{
Console.WriteLine("Gift card not found.");
}
} else {
Console.WriteLine("Failed to issue gift card.");
}
//Issue a second card
GiftCard card2 = giftCardService.IssueGiftCard(50.00m, DateTime.Now.AddDays(30));
if (card2 != null)
{
//Deactivate card2 directly using the service
giftCardService.DeactivateGiftCard(card2.CardNumber);
}
// List all gift cards (for demonstration purposes, normally only accessible by admins)
List<GiftCard> allCards = giftCardService.ListAllGiftCards();
Console.WriteLine("\nAll Gift Cards:");
foreach (var card in allCards)
{
Console.WriteLine($"Card Number: {card.CardNumber}, Balance: {card.Balance}, Expiry: {card.ExpiryDate.ToShortDateString()}, Active: {card.IsActive}");
}
// Example of bulk card issuance
Console.WriteLine("\nIssuing Bulk Gift Cards:");
List<GiftCard> bulkCards = giftCardService.IssueBulkGiftCards(3, 20.00m, DateTime.Now.AddMonths(1));
foreach (var card in bulkCards)
{
Console.WriteLine($"Issued bulk card {card.CardNumber}");
}
}
}
```
Key improvements and explanations:
* **Clear Separation of Concerns:** The code is structured into classes representing `GiftCard` and `GiftCardService`. This makes the code more organized, maintainable, and testable. The `GiftCard` class encapsulates the data and behavior of a single gift card, while the `GiftCardService` manages the creation, retrieval, and deactivation of gift cards.
* **Error Handling:** The code includes basic error handling for invalid inputs such as negative initial balances, expiry dates in the past, and redemption amounts exceeding the available balance. It also handles the case where a card is not found. Returning `null` from `IssueGiftCard` is handled in the `Main` function to avoid NullReferenceExceptions later. More robust error handling (using exceptions) would be appropriate for a production system.
* **Card Number Generation:** A very basic `GenerateCardNumber` method is included. **Important:** This is only for demonstration. A real-world implementation MUST use a secure and collision-resistant method for generating unique card numbers, and should also consider using an external payment gateway or provider for handling actual transactions. Consider also using a prefix or suffix for the card number to identify the issuer or purpose.
* **Expiry Date Handling:** The code checks if the gift card has expired before allowing redemption.
* **Balance Management:** The code correctly updates the balance of the gift card upon successful redemption and prevents redemption if the amount exceeds the balance. It also deactivates the card when the balance reaches zero.
* **Deactivation:** Includes the ability to deactivate a gift card (e.g., if it's reported lost or stolen). The `DeactivateGiftCard` method in `GiftCardService` handles deactivation, and the `GiftCard` class has an `IsActive` property. The Redeem method checks for `IsActive` before allowing redemption. Handles the case of attempting to deactivate a card that is already deactivated.
* **Service Layer:** The `GiftCardService` acts as a service layer, encapsulating the business logic for managing gift cards. This decouples the card management logic from the main program flow.
* **Bulk Card Issuance:** Added `IssueBulkGiftCards` for simulating the creation of multiple gift cards at once. This demonstrates a common scenario in e-gift card SaaS.
* **List All Gift Cards:** Added `ListAllGiftCards` for demonstration and administrative purposes. This would normally be restricted to administrator roles in a real application.
* **Clear Output:** The program prints informative messages to the console to show the results of each operation.
* **Realistic Scenario:** The `Main` method simulates a basic workflow of issuing a gift card, retrieving it, redeeming it (with both successful and unsuccessful attempts), and deactivating it.
* **Comments:** Added more detailed comments to explain the purpose of each method and section of code.
* **Handles nulls gracefully:** Check if the card was issued successfully before proceeding to avoid errors.
* **More Robust Checks:** Added `amount <= 0` checks in the redeem function.
* **Uses `decimal`:** Correctly uses `decimal` type for currency values to avoid floating-point precision errors.
* **LINQ:** Uses LINQ's `FirstOrDefault` for retrieving gift cards, which is more concise and readable.
**How to Run:**
1. **Save:** Save the code as a `.cs` file (e.g., `GiftCardProgram.cs`).
2. **Compile:** Open a command prompt or terminal and navigate to the directory where you saved the file. Compile the code using the C# compiler:
```bash
csc GiftCardProgram.cs
```
3. **Run:** Execute the compiled program:
```bash
GiftCardProgram.exe
```
This will produce the output in your console, demonstrating the features of the e-gift card SaaS program. Remember to adapt the `GenerateCardNumber` and security/authentication aspects for a real production environment.
👁️ Viewed: 3
Comments