PointsHistoryModel.swift 14.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
//
//  PointsHistoryModel.swift
//  SwiftWarplyFramework
//
//  Created by Warply on 25/06/2025.
//  Copyright © 2025 Warply. All rights reserved.
//

import Foundation

// MARK: - Points History Model

public class PointsHistoryModel {
    
    // MARK: - Properties
    
    public var entryId: String?
    public var entryDate: Date?
    public var entryType: String? // "earned", "spent", "expired", "bonus", "refund"
    public var pointsAmount: Int?
    public var pointsBalance: Int?
    public var source: String? // "purchase", "bonus", "referral", "campaign", "manual"
    public var description: String?
    public var expirationDate: Date?
    public var transactionId: String?
    public var campaignId: String?
    public var couponId: String?
    public var merchantName: String?
    public var merchantId: String?
    public var productName: String?
    public var productId: String?
    public var category: String?
    public var reference: String?
    public var status: String?
    
    // MARK: - Computed Properties
    
    /// Formatted entry date
    public var formattedDate: String? {
        guard let date = entryDate else { return nil }
        let formatter = DateFormatter()
        formatter.dateStyle = .medium
        formatter.timeStyle = .short
        return formatter.string(from: date)
    }
    
    /// Formatted expiration date
    public var formattedExpirationDate: String? {
        guard let date = expirationDate else { return nil }
        let formatter = DateFormatter()
        formatter.dateStyle = .medium
        return formatter.string(from: date)
    }
    
    /// Entry type display name
    public var entryTypeDisplayName: String {
        guard let type = entryType?.lowercased() else { return "Unknown" }
        
        switch type {
        case "earned":
            return "Points Earned"
        case "spent":
            return "Points Spent"
        case "expired":
            return "Points Expired"
        case "bonus":
            return "Bonus Points"
        case "refund":
            return "Points Refunded"
        case "adjustment":
            return "Points Adjustment"
        case "transfer":
            return "Points Transfer"
        case "redemption":
            return "Points Redemption"
        default:
            return type.capitalized
        }
    }
    
    /// Source display name
    public var sourceDisplayName: String {
        guard let source = source?.lowercased() else { return "Unknown" }
        
        switch source {
        case "purchase":
            return "Purchase"
        case "bonus":
            return "Bonus"
        case "referral":
            return "Referral"
        case "campaign":
            return "Campaign"
        case "manual":
            return "Manual Adjustment"
        case "signup":
            return "Sign Up Bonus"
        case "birthday":
            return "Birthday Bonus"
        case "review":
            return "Review Bonus"
        case "social":
            return "Social Media"
        case "promotion":
            return "Promotion"
        default:
            return source.capitalized
        }
    }
    
    /// Status display name
    public var statusDisplayName: String {
        guard let status = status?.lowercased() else { return "Completed" }
        
        switch status {
        case "completed", "success":
            return "Completed"
        case "pending":
            return "Pending"
        case "failed", "error":
            return "Failed"
        case "cancelled", "canceled":
            return "Cancelled"
        case "expired":
            return "Expired"
        case "reversed":
            return "Reversed"
        default:
            return status.capitalized
        }
    }
    
    /// Formatted points amount with sign
    public var formattedPointsAmount: String {
        guard let amount = pointsAmount else { return "0" }
        
        let formatter = NumberFormatter()
        formatter.numberStyle = .decimal
        formatter.positivePrefix = "+"
        formatter.negativePrefix = "-"
        
        return formatter.string(from: NSNumber(value: amount)) ?? "\(amount)"
    }
    
    /// Formatted points balance
    public var formattedPointsBalance: String {
        guard let balance = pointsBalance else { return "0" }
        
        let formatter = NumberFormatter()
        formatter.numberStyle = .decimal
        
        return formatter.string(from: NSNumber(value: balance)) ?? "\(balance)"
    }
    
    /// Whether this entry is positive (earned points)
    public var isPositive: Bool {
        guard let amount = pointsAmount else { return false }
        return amount > 0
    }
    
    /// Whether this entry is negative (spent/expired points)
    public var isNegative: Bool {
        guard let amount = pointsAmount else { return false }
        return amount < 0
    }
    
    /// Whether points are expired or will expire soon
    public var isExpiredOrExpiring: Bool {
        guard let expirationDate = expirationDate else { return false }
        
        // Check if expired or expiring within 30 days
        let thirtyDaysFromNow = Calendar.current.date(byAdding: .day, value: 30, to: Date()) ?? Date()
        return expirationDate <= thirtyDaysFromNow
    }
    
    /// Days until expiration (negative if expired)
    public var daysUntilExpiration: Int? {
        guard let expirationDate = expirationDate else { return nil }
        
        let calendar = Calendar.current
        let components = calendar.dateComponents([.day], from: Date(), to: expirationDate)
        return components.day
    }
    
    // MARK: - Initialization
    
    public init() {
        // Empty initializer
    }
    
    public init(dictionary: [String: Any]) {
        parseFromDictionary(dictionary)
    }
    
    // MARK: - Parsing
    
    private func parseFromDictionary(_ dictionary: [String: Any]) {
        // Parse entry identification
        entryId = dictionary["entry_id"] as? String ?? dictionary["id"] as? String
        reference = dictionary["reference"] as? String ?? dictionary["ref"] as? String
        
        // Parse entry details
        entryType = dictionary["entry_type"] as? String ?? dictionary["type"] as? String
        source = dictionary["source"] as? String
        status = dictionary["status"] as? String
        description = dictionary["description"] as? String ?? dictionary["desc"] as? String
        
        // Parse points information
        if let pointsAmountValue = dictionary["points_amount"] as? Int {
            pointsAmount = pointsAmountValue
        } else if let pointsAmountString = dictionary["points_amount"] as? String {
            pointsAmount = Int(pointsAmountString)
        } else if let pointsValue = dictionary["points"] as? Int {
            pointsAmount = pointsValue
        } else if let pointsString = dictionary["points"] as? String {
            pointsAmount = Int(pointsString)
        }
        
        if let pointsBalanceValue = dictionary["points_balance"] as? Int {
            pointsBalance = pointsBalanceValue
        } else if let pointsBalanceString = dictionary["points_balance"] as? String {
            pointsBalance = Int(pointsBalanceString)
        } else if let balanceValue = dictionary["balance"] as? Int {
            pointsBalance = balanceValue
        } else if let balanceString = dictionary["balance"] as? String {
            pointsBalance = Int(balanceString)
        }
        
        // Parse merchant information
        merchantName = dictionary["merchant_name"] as? String ?? dictionary["merchant"] as? String
        merchantId = dictionary["merchant_id"] as? String
        
        // Parse product information
        productName = dictionary["product_name"] as? String ?? dictionary["product"] as? String
        productId = dictionary["product_id"] as? String
        category = dictionary["category"] as? String
        
        // Parse related IDs
        transactionId = dictionary["transaction_id"] as? String
        campaignId = dictionary["campaign_id"] as? String
        couponId = dictionary["coupon_id"] as? String
        
        // Parse entry date
        if let dateString = dictionary["entry_date"] as? String {
            entryDate = parseDate(from: dateString)
        } else if let dateString = dictionary["date"] as? String {
            entryDate = parseDate(from: dateString)
        } else if let timestamp = dictionary["timestamp"] as? TimeInterval {
            entryDate = Date(timeIntervalSince1970: timestamp)
        } else if let timestampString = dictionary["timestamp"] as? String,
                  let timestampValue = Double(timestampString) {
            entryDate = Date(timeIntervalSince1970: timestampValue)
        }
        
        // Parse expiration date
        if let expirationString = dictionary["expiration_date"] as? String {
            expirationDate = parseDate(from: expirationString)
        } else if let expirationString = dictionary["expires_at"] as? String {
            expirationDate = parseDate(from: expirationString)
        } else if let expirationTimestamp = dictionary["expiration_timestamp"] as? TimeInterval {
            expirationDate = Date(timeIntervalSince1970: expirationTimestamp)
        }
    }
    
    // MARK: - Helper Methods
    
    /// Parse date from string with multiple format support
    private func parseDate(from dateString: String) -> Date? {
        let formatters = [
            "yyyy-MM-dd HH:mm:ss",
            "yyyy-MM-dd'T'HH:mm:ss.SSSZ",
            "yyyy-MM-dd'T'HH:mm:ssZ",
            "yyyy-MM-dd'T'HH:mm:ss",
            "yyyy-MM-dd",
            "dd/MM/yyyy HH:mm:ss",
            "dd/MM/yyyy",
            "MM/dd/yyyy HH:mm:ss",
            "MM/dd/yyyy",
            "dd-MM-yyyy HH:mm:ss",
            "dd-MM-yyyy"
        ]
        
        for format in formatters {
            let formatter = DateFormatter()
            formatter.dateFormat = format
            formatter.locale = Locale(identifier: "en_US_POSIX")
            
            if let date = formatter.date(from: dateString) {
                return date
            }
        }
        
        return nil
    }
    
    /// Get points entry summary for display
    public func getSummary() -> String {
        var summary = entryTypeDisplayName
        
        let formattedAmount = formattedPointsAmount
        summary += " \(formattedAmount) points"
        
        let source = sourceDisplayName
        if source != "Unknown" {
            summary += " from \(source)"
        }
        
        if let merchantName = merchantName {
            summary += " at \(merchantName)"
        }
        
        return summary
    }
    
    /// Get expiration warning text
    public func getExpirationWarning() -> String? {
        guard let days = daysUntilExpiration else { return nil }
        
        if days < 0 {
            return "Expired \(abs(days)) days ago"
        } else if days == 0 {
            return "Expires today"
        } else if days <= 7 {
            return "Expires in \(days) day\(days == 1 ? "" : "s")"
        } else if days <= 30 {
            return "Expires in \(days) days"
        }
        
        return nil
    }
    
    /// Check if entry matches search criteria
    public func matches(searchText: String) -> Bool {
        let searchLower = searchText.lowercased()
        
        let searchableFields = [
            entryId,
            description,
            merchantName,
            productName,
            category,
            source,
            reference,
            entryType
        ].compactMap { $0?.lowercased() }
        
        return searchableFields.contains { $0.contains(searchLower) }
    }
    
    // MARK: - Dictionary Conversion
    
    /// Convert points history model to dictionary for API requests
    public func toDictionary() -> [String: Any] {
        var dictionary: [String: Any] = [:]
        
        if let entryId = entryId { dictionary["entry_id"] = entryId }
        if let entryType = entryType { dictionary["entry_type"] = entryType }
        if let pointsAmount = pointsAmount { dictionary["points_amount"] = pointsAmount }
        if let pointsBalance = pointsBalance { dictionary["points_balance"] = pointsBalance }
        if let source = source { dictionary["source"] = source }
        if let description = description { dictionary["description"] = description }
        if let merchantName = merchantName { dictionary["merchant_name"] = merchantName }
        if let merchantId = merchantId { dictionary["merchant_id"] = merchantId }
        if let productName = productName { dictionary["product_name"] = productName }
        if let productId = productId { dictionary["product_id"] = productId }
        if let category = category { dictionary["category"] = category }
        if let reference = reference { dictionary["reference"] = reference }
        if let status = status { dictionary["status"] = status }
        if let transactionId = transactionId { dictionary["transaction_id"] = transactionId }
        if let campaignId = campaignId { dictionary["campaign_id"] = campaignId }
        if let couponId = couponId { dictionary["coupon_id"] = couponId }
        
        if let entryDate = entryDate {
            dictionary["timestamp"] = entryDate.timeIntervalSince1970
        }
        
        if let expirationDate = expirationDate {
            dictionary["expiration_timestamp"] = expirationDate.timeIntervalSince1970
        }
        
        return dictionary
    }
    
    // MARK: - Debug Description
    
    public var debugDescription: String {
        return """
        PointsHistoryModel {
            entryId: \(entryId ?? "nil")
            date: \(formattedDate ?? "nil")
            type: \(entryTypeDisplayName)
            amount: \(formattedPointsAmount)
            balance: \(formattedPointsBalance)
            source: \(sourceDisplayName)
            merchant: \(merchantName ?? "nil")
            product: \(productName ?? "nil")
            status: \(statusDisplayName)
            expirationDate: \(formattedExpirationDate ?? "nil")
            description: \(description ?? "nil")
        }
        """
    }
}

// MARK: - Equatable

extension PointsHistoryModel: Equatable {
    public static func == (lhs: PointsHistoryModel, rhs: PointsHistoryModel) -> Bool {
        return lhs.entryId == rhs.entryId && lhs.entryDate == rhs.entryDate
    }
}

// MARK: - Hashable

extension PointsHistoryModel: Hashable {
    public func hash(into hasher: inout Hasher) {
        hasher.combine(entryId)
        hasher.combine(entryDate)
    }
}

// MARK: - Comparable (for sorting by date)

extension PointsHistoryModel: Comparable {
    public static func < (lhs: PointsHistoryModel, rhs: PointsHistoryModel) -> Bool {
        guard let lhsDate = lhs.entryDate, let rhsDate = rhs.entryDate else {
            return false
        }
        return lhsDate < rhsDate
    }
}