Repository navigation
Expand file tree
/
Copy pathData.lua
More file actions
695 lines (601 loc) · 23.4 KB
/
Copy pathData.lua
File metadata and controls
695 lines (601 loc) · 23.4 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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
--[[
Copperwise: Data.lua
Pattern: Facade
Single interface for all data access:
- SavedVariables initialisation with defaults
- CRUD for transaction entries
- Aggregation: daily and monthly totals
- Automatic cleanup of old entries
]]
local ADDON_NAME, ns = ...
local Copperwise = ns.Copperwise
local L = ns.L
local Data = {}
Copperwise:RegisterModule("Data", Data)
-------------------------------------------------------------------------------
-- Constants
-------------------------------------------------------------------------------
local MAX_ENTRIES = 5000 -- Max entries per character
local CLEANUP_AGE_DAYS = 365 -- Delete entries older than N days
local SECONDS_PER_DAY = 86400
-------------------------------------------------------------------------------
-- SavedVariables defaults
-------------------------------------------------------------------------------
local DB_DEFAULTS = {
characters = {},
settings = {
showMinimap = true, -- button position/visibility: settings.minimap (LibDBIcon)
theme = "dashboard_cards",
},
modules = {}, -- per-feature namespaced data
}
-------------------------------------------------------------------------------
-- Helpers
-------------------------------------------------------------------------------
--- Returns the current character's key: "Name-Realm"
--- @return string
function Data:GetCharKey()
local name = UnitName("player")
local realm = GetRealmName()
return name .. "-" .. realm
end
--- Today's date as "YYYY-MM-DD"
--- @return string
function Data:GetDateKey()
return date("%Y-%m-%d")
end
--- Yesterday's date as "YYYY-MM-DD"
--- (crosses month/year boundaries correctly, because time()-86400
--- lands in the previous day in any time zone)
--- @return string
function Data:GetYesterdayDateKey()
return date("%Y-%m-%d", time() - SECONDS_PER_DAY)
end
--- Current month as "YYYY-MM"
--- @return string
function Data:GetMonthKey()
return date("%Y-%m")
end
--- Deep-copies defaults into target (never overwrites existing values)
--- @param target table
--- @param defaults table
local function ApplyDefaults(target, defaults)
for k, v in pairs(defaults) do
if type(v) == "table" then
if type(target[k]) ~= "table" then
target[k] = {}
end
ApplyDefaults(target[k], v)
elseif target[k] == nil then
target[k] = v
end
end
end
-------------------------------------------------------------------------------
-- Lifecycle (called from Core)
-------------------------------------------------------------------------------
--- SavedVariables initialisation
function Data:OnInitialize()
-- Create, or merge with defaults
if not CopperwiseDB then
CopperwiseDB = {}
end
ApplyDefaults(CopperwiseDB, DB_DEFAULTS)
self:ImportFromGoldLedger()
CopperwiseDB.settings.language = nil -- language picker removed (English only)
-- Make sure the current character has a data table
self:EnsureCharacterData()
-- Remove old entries
self:CleanupOldEntries()
end
local function DeepCopy(value)
if type(value) ~= "table" then return value end
local copy = {}
for k, v in pairs(value) do copy[k] = DeepCopy(v) end
return copy
end
--- One-time import for players switching from GoldLedger, which Copperwise is
--- based on. A SavedVariables table is only loaded with the addon that owns it,
--- so this works when GoldLedger is still enabled on the first Copperwise login;
--- after that GoldLedger can be disabled. Only runs while Copperwise has no data.
function Data:ImportFromGoldLedger()
local old = _G.GoldLedgerDB
if type(old) ~= "table" or type(old.characters) ~= "table" then return end
if next(CopperwiseDB.characters) ~= nil or CopperwiseDB.importedFromGoldLedger then return end
local characters, entries = 0, 0
for key, charData in pairs(old.characters) do
CopperwiseDB.characters[key] = DeepCopy(charData)
characters = characters + 1
entries = entries + (type(charData.entries) == "table" and #charData.entries or 0)
end
if type(old.warbandBank) == "table" then
CopperwiseDB.warbandBank = DeepCopy(old.warbandBank)
end
if type(old.settings) == "table" and old.settings.goalAmount then
CopperwiseDB.settings.goalAmount = old.settings.goalAmount
end
CopperwiseDB.importedFromGoldLedger = time()
C_Timer.After(2, function()
print("|cffb87333Copperwise|r " .. L["IMPORTED_GOLDLEDGER"]:format(entries, characters))
end)
end
--- Makes sure the current character has a data table
function Data:EnsureCharacterData()
local key = self:GetCharKey()
if not CopperwiseDB.characters[key] then
CopperwiseDB.characters[key] = {
entries = {},
daily = {},
monthly = {},
}
end
return CopperwiseDB.characters[key]
end
-------------------------------------------------------------------------------
-- Module Namespace API (Ace3-inspired)
-- Feature modules get their own section in CopperwiseDB.modules[name]
-------------------------------------------------------------------------------
--- Registers a feature module namespace with defaults
--- @param name string Namespace name (e.g. "auction")
--- @param defaults table Default structure
--- @return table Reference to the namespace data in CopperwiseDB.modules[name]
function Data:RegisterNamespace(name, defaults)
if not CopperwiseDB.modules then
CopperwiseDB.modules = {}
end
if not CopperwiseDB.modules[name] then
CopperwiseDB.modules[name] = {}
end
-- Merge defaults (never overwrites existing values)
if defaults then
local function applyDefaults(target, defs)
for k, v in pairs(defs) do
if type(v) == "table" then
if type(target[k]) ~= "table" then target[k] = {} end
applyDefaults(target[k], v)
elseif target[k] == nil then
target[k] = v
end
end
end
applyDefaults(CopperwiseDB.modules[name], defaults)
end
return CopperwiseDB.modules[name]
end
--- Returns a feature module's namespace data
--- @param name string Namespace name
--- @return table|nil
function Data:GetNamespace(name)
return CopperwiseDB and CopperwiseDB.modules and CopperwiseDB.modules[name]
end
-------------------------------------------------------------------------------
-- Facade API: CRUD
-------------------------------------------------------------------------------
--- Adds a transaction entry
--- @param amount number Amount in copper (positive = income, negative = expense)
--- @param source string|nil Source: "vendor", "ah", "mail", "quest", "loot", "trade", "unknown"
--- @param meta table|nil Optional metadata { itemName, ahType, quantity, unitPrice, grossAmount, cutAmount }
--- Stored as-is, never interpreted by the core. Used by modules (AuctionTracker).
--- @return table|nil The stored entry (callers may annotate it, e.g. vendor sale item names)
function Data:AddEntry(amount, source, meta)
if amount == 0 then return end
local charData = self:EnsureCharacterData()
local now = time()
local dateKey = self:GetDateKey()
local monthKey = self:GetMonthKey()
local entryType = amount > 0 and "income" or "expense"
local absAmount = math.abs(amount)
-- 1. Append to the log
local entry = {
timestamp = now,
amount = absAmount,
type = entryType,
source = source or "unknown",
}
if type(meta) == "table" then
entry.itemName = meta.itemName
entry.ahType = meta.ahType
entry.quantity = meta.quantity
entry.unitPrice = meta.unitPrice
entry.grossAmount = meta.grossAmount
entry.cutAmount = meta.cutAmount
end
table.insert(charData.entries, entry)
self:TrimEntries(charData)
-- 2. Update the daily total
if not charData.daily[dateKey] then
charData.daily[dateKey] = { income = 0, expense = 0 }
end
charData.daily[dateKey][entryType] = charData.daily[dateKey][entryType] + absAmount
-- 3. Update the monthly total
if not charData.monthly[monthKey] then
charData.monthly[monthKey] = { income = 0, expense = 0 }
end
charData.monthly[monthKey][entryType] = charData.monthly[monthKey][entryType] + absAmount
return entry
end
--- Size limit: drop the oldest entries
function Data:TrimEntries(charData)
while #charData.entries > MAX_ENTRIES do
table.remove(charData.entries, 1)
end
end
--- Records a move of gold between the character and a bank it still owns
--- (warband bank). Logged with type "transfer" so it shows in the transaction
--- list but is excluded from income/expense totals, charts and session stats.
--- @param amount number Copper delta on the character (negative = deposit, positive = withdrawal)
--- @param source string|nil Source key, default "bank"
function Data:AddTransfer(amount, source)
if amount == 0 then return end
local charData = self:EnsureCharacterData()
table.insert(charData.entries, {
timestamp = time(),
amount = math.abs(amount),
type = "transfer",
direction = amount < 0 and "deposit" or "withdraw",
source = source or "bank",
})
self:TrimEntries(charData)
end
-------------------------------------------------------------------------------
-- Warband bank balance (account-wide, so stored outside per-character data)
-------------------------------------------------------------------------------
--- Caches the warband bank balance from the server
function Data:RefreshWarbandBankMoney()
if not (C_Bank and C_Bank.FetchDepositedMoney and Enum and Enum.BankType) then return end
local amount = C_Bank.FetchDepositedMoney(Enum.BankType.Account)
if type(amount) ~= "number" then return end
CopperwiseDB.warbandBank = { amount = amount, updated = time() }
end
--- Last known warband bank balance in copper (0 if never seen)
--- @return number
function Data:GetWarbandBankMoney()
local wb = CopperwiseDB and CopperwiseDB.warbandBank
return wb and wb.amount or 0
end
--- Returns the totals for a day
--- @param dateKey string|nil Date "YYYY-MM-DD", nil = today
--- @return table {income=number, expense=number}
function Data:GetDailySummary(dateKey)
dateKey = dateKey or self:GetDateKey()
local charData = self:EnsureCharacterData()
return charData.daily[dateKey] or { income = 0, expense = 0 }
end
--- Returns the totals for a month
--- @param monthKey string|nil Month "YYYY-MM", nil = current
--- @return table {income=number, expense=number}
function Data:GetMonthlySummary(monthKey)
monthKey = monthKey or self:GetMonthKey()
local charData = self:EnsureCharacterData()
return charData.monthly[monthKey] or { income = 0, expense = 0 }
end
--- Returns per-day data for the current month's chart (legacy)
--- @return table[] { {day=1, income=N, expense=N}, ... }, number maxValue
function Data:GetMonthlyChartData()
return self:GetChartData("30d")
end
--- Returns chart data for a period
--- @param period string "7d"|"30d"|"all"
--- @return table[] { {label=string, dateKey=string, income=N, expense=N}, ... }, number maxValue, number count
function Data:GetChartData(period)
local charData = self:EnsureCharacterData()
local result = {}
local maxVal = 1
if period == "7d" then
-- Last 7 days
local now = time()
for i = 6, 0, -1 do
local t = now - i * SECONDS_PER_DAY
local dateKey = date("%Y-%m-%d", t)
local dayNum = tonumber(date("%d", t))
local summary = charData.daily[dateKey] or { income = 0, expense = 0 }
table.insert(result, {
label = tostring(dayNum),
dateKey = dateKey,
income = summary.income,
expense = summary.expense,
})
maxVal = math.max(maxVal, summary.income, summary.expense)
end
return result, maxVal, 7
elseif period == "all" then
-- Every day with data, sorted by date
local dateKeys = {}
for dateKey in pairs(charData.daily) do
table.insert(dateKeys, dateKey)
end
table.sort(dateKeys)
for _, dateKey in ipairs(dateKeys) do
local summary = charData.daily[dateKey]
local dayNum = dateKey:match("%d+-%d+-(%d+)")
table.insert(result, {
label = dayNum,
dateKey = dateKey,
income = summary.income,
expense = summary.expense,
})
maxVal = math.max(maxVal, summary.income, summary.expense)
end
local count = #result
if count == 0 then count = 1 end
return result, maxVal, count
else -- "30d" default: last 30 days
local now = time()
for i = 29, 0, -1 do
local t = now - i * SECONDS_PER_DAY
local dateKey = date("%Y-%m-%d", t)
local dayNum = tonumber(date("%d", t))
local summary = charData.daily[dateKey] or { income = 0, expense = 0 }
table.insert(result, {
label = tostring(dayNum),
dateKey = dateKey,
income = summary.income,
expense = summary.expense,
})
maxVal = math.max(maxVal, summary.income, summary.expense)
end
return result, maxVal, 30
end
end
--- Returns the last N entries, newest first
--- @param count number Number of entries
--- @return table[] Array of entries
function Data:GetRecentEntries(count)
count = count or 50
local charData = self:EnsureCharacterData()
local entries = charData.entries
local result = {}
local start = math.max(1, #entries - count + 1)
for i = #entries, start, -1 do
table.insert(result, entries[i])
end
return result
end
--- Returns the addon settings
--- @return table
function Data:GetSettings()
return CopperwiseDB.settings
end
-------------------------------------------------------------------------------
-- Reset & Cleanup
-------------------------------------------------------------------------------
--- Resets the current character's data
function Data:ResetCharacterData()
local key = self:GetCharKey()
CopperwiseDB.characters[key] = nil
self:EnsureCharacterData()
end
-------------------------------------------------------------------------------
-- Goal API
-------------------------------------------------------------------------------
--- Sets the savings goal (in copper)
--- @param amount number Amount in copper
function Data:SetGoal(amount)
CopperwiseDB.settings.goalAmount = amount
end
--- Returns the current goal in copper, 0 if none
--- @return number
function Data:GetGoal()
return CopperwiseDB.settings.goalAmount or 0
end
--- Clears the goal
function Data:ClearGoal()
CopperwiseDB.settings.goalAmount = nil
end
--- Returns progress towards the goal
--- @return table|nil {goal, current, progress(0-1), remaining, estDays}
function Data:GetGoalProgress()
local goal = self:GetGoal()
if goal <= 0 then return nil end
-- Gold moved into the warband bank still counts towards the goal
local currentGold = (GetMoney() or 0) + self:GetWarbandBankMoney()
local progress = currentGold / goal
local remaining = goal - currentGold
-- Days estimate: average daily net income
local charData = self:EnsureCharacterData()
local totalNet = 0
local days = 0
for _, summary in pairs(charData.daily) do
totalNet = totalNet + (summary.income - summary.expense)
days = days + 1
end
local avgDaily = days > 0 and (totalNet / days) or 0
local estDays = (avgDaily > 0 and remaining > 0) and math.ceil(remaining / avgDaily) or nil
return {
goal = goal,
current = currentGold,
progress = math.min(1, progress),
remaining = remaining,
estDays = estDays,
}
end
-------------------------------------------------------------------------------
-- Multi-character API
-------------------------------------------------------------------------------
--- Returns a summary for every character over a period
--- @param period string|nil "day"|"week"|"month" (default: "month")
--- @return table[] { {name, income, expense, net}, ... }
function Data:GetAllCharactersSummary(period)
period = period or "month"
local result = {}
if not CopperwiseDB or not CopperwiseDB.characters then return result end
local dateKey = self:GetDateKey()
local monthKey = self:GetMonthKey()
for charKey, charData in pairs(CopperwiseDB.characters) do
local income, expense = 0, 0
if period == "day" then
local daily = charData.daily and charData.daily[dateKey]
if daily then
income, expense = daily.income, daily.expense
end
elseif period == "week" then
local now = time()
local cutoff = now - 7 * SECONDS_PER_DAY
if charData.daily then
for dk, daily in pairs(charData.daily) do
local y, m, d = dk:match("^(%d+)-(%d+)-(%d+)$")
if y then
local t = time({ year = tonumber(y), month = tonumber(m), day = tonumber(d), hour = 0 })
if t >= cutoff then
income = income + (daily.income or 0)
expense = expense + (daily.expense or 0)
end
end
end
end
else -- "month"
local monthly = charData.monthly and charData.monthly[monthKey]
if monthly then
income, expense = monthly.income, monthly.expense
end
end
table.insert(result, {
name = charKey,
income = income,
expense = expense,
net = income - expense,
})
end
table.sort(result, function(a, b) return a.net > b.net end)
return result
end
-------------------------------------------------------------------------------
-- Source Breakdown API
-------------------------------------------------------------------------------
--- All sources, in display order
Data.ALL_SOURCES = {"vendor", "repair", "ah", "mail", "quest", "loot", "trade", "bank", "guildbank", "unknown"}
--- Returns the per-source breakdown for a period
--- @param period string "today"|"week"|"month"|"all"
--- @return table sourceTotals { [source] = {income=N, expense=N} }
--- @return table grandTotals {income=N, expense=N}
function Data:GetSourceBreakdown(period)
local charData = self:EnsureCharacterData()
-- Work out the cutoff
local cutoff = 0
if period == "today" then
local d = date("*t")
d.hour, d.min, d.sec = 0, 0, 0
cutoff = time(d)
elseif period == "week" then
cutoff = time() - 7 * SECONDS_PER_DAY
elseif period == "month" then
cutoff = time() - 30 * SECONDS_PER_DAY
end
-- "all" → cutoff = 0, every entry
local sourceTotals = {}
for _, src in ipairs(self.ALL_SOURCES) do
sourceTotals[src] = { income = 0, expense = 0 }
end
local grandTotals = { income = 0, expense = 0 }
for _, entry in ipairs(charData.entries) do
-- Bank transfers are neither income nor expense
if entry.timestamp >= cutoff and entry.type ~= "transfer" then
local src = entry.source or "unknown"
if not sourceTotals[src] then
sourceTotals[src] = { income = 0, expense = 0 }
end
sourceTotals[src][entry.type] = sourceTotals[src][entry.type] + entry.amount
grandTotals[entry.type] = grandTotals[entry.type] + entry.amount
end
end
return sourceTotals, grandTotals
end
-------------------------------------------------------------------------------
-- Filtered Entries API (pagination + search)
-------------------------------------------------------------------------------
--- Returns filtered entries, paginated
--- @param options table { page=1, perPage=50, source="all", entryType="all", minAmount=0 }
--- @return table { entries={...}, total=N, page=N, totalPages=N }
function Data:GetFilteredEntries(options)
options = options or {}
local page = options.page or 1
local perPage = options.perPage or 50
local sourceFilter = options.source or "all"
local typeFilter = options.entryType or "all"
local minAmount = options.minAmount or 0
local charData = self:EnsureCharacterData()
-- Filter every entry (reverse order, newest first)
local filtered = {}
for i = #charData.entries, 1, -1 do
local entry = charData.entries[i]
local match = true
if sourceFilter ~= "all" and (entry.source or "unknown") ~= sourceFilter then
match = false
end
if typeFilter ~= "all" and entry.type ~= typeFilter then
match = false
end
if minAmount > 0 and entry.amount < minAmount then
match = false
end
if match then
filtered[#filtered + 1] = entry
end
end
local total = #filtered
local totalPages = perPage > 0 and math.ceil(total / perPage) or 0
-- Take the requested page
local startIdx = (page - 1) * perPage + 1
local endIdx = math.min(page * perPage, total)
local entries = {}
if startIdx <= total then
for i = startIdx, endIdx do
entries[#entries + 1] = filtered[i]
end
end
return {
entries = entries,
total = total,
page = page,
totalPages = totalPages,
}
end
-------------------------------------------------------------------------------
-- Export API
-------------------------------------------------------------------------------
--- Returns every entry for the current character as CSV
--- @return string CSV data
function Data:GetExportCSV()
local charData = self:EnsureCharacterData()
local lines = { "timestamp,date,time,type,amount_copper,amount_gold,source" }
for _, entry in ipairs(charData.entries) do
local dateStr = date("%Y-%m-%d", entry.timestamp)
local timeStr = date("%H:%M:%S", entry.timestamp)
local goldAmount = entry.amount / 10000
-- Transfers export as "bank_deposit" / "bank_withdraw"
local typeStr = entry.type == "transfer" and ("bank_" .. (entry.direction or "deposit")) or entry.type
table.insert(lines, ("%d,%s,%s,%s,%d,%.2f,%s"):format(
entry.timestamp, dateStr, timeStr,
typeStr, entry.amount, goldAmount,
entry.source or "unknown"
))
end
return table.concat(lines, "\n")
end
--- Removes entries older than CLEANUP_AGE_DAYS
function Data:CleanupOldEntries()
local charData = self:EnsureCharacterData()
local cutoff = time() - (CLEANUP_AGE_DAYS * SECONDS_PER_DAY)
local entries = charData.entries
local cleaned = {}
for _, entry in ipairs(entries) do
if entry.timestamp >= cutoff then
table.insert(cleaned, entry)
end
end
charData.entries = cleaned
-- Remove old daily totals
local dateCutoff = date("%Y-%m-%d", cutoff)
for dateKey in pairs(charData.daily) do
if dateKey < dateCutoff then
charData.daily[dateKey] = nil
end
end
-- Remove old monthly totals
local monthCutoff = date("%Y-%m", cutoff)
for monthKey in pairs(charData.monthly) do
if monthKey < monthCutoff then
charData.monthly[monthKey] = nil
end
end
end