Repository navigation
Expand file tree
/
Copy pathInventoryLog.lua
More file actions
1386 lines (1330 loc) · 64.5 KB
/
Copy pathInventoryLog.lua
File metadata and controls
1386 lines (1330 loc) · 64.5 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
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
setfenv(1, _G.SlackHacks)
local module = Self:NewModule("InventoryLog", "AceEvent-3.0", "AceTimer-3.0")
Self.InventoryLog = module
module.ACTIONS = {}
for _, action in ipairs({ "Quest", "Looted", "Gathered", "Created", "Purchased", "Sold", "Auctioned", "Destroyed",
"Banked", "Mail", "Sent", "Traded" }) do
module.ACTIONS[#module.ACTIONS + 1] = { id = action, name = action }
end
local CORRELATION_SECONDS = 5
local ROW_HEIGHT = 23
local PAPER_ICON = "Interface\\Icons\\INV_Scroll_03"
local snapshot, pending, metadataCache = nil, {}, {}
local auctionRequests = {}
local merchantOpen, bankOpen, guildBankOpen, tradeOpen = false, false, false, false
local loot, tradeItems, outgoingMail = {}, {}, {}
local inbox = {}
local questTitleRequests = {}
local legacyAuctionLink, legacyAuctionRequest, outgoingMailRecipient
local lastCursorLink, gatheringUntil, gatheringKind, reconcileTimer
local window
local observing = false
--- Preserve explicit mail choices when splitting the former combined action into Mail and Sent.
---@param actions table Recording preferences or character display filters.
local function migrateMailActions(actions)
local mailed = rawget(actions, "Mailed")
if mailed == nil then return end
for _, action in ipairs({ "Mail", "Sent" }) do
if rawget(actions, action) == nil then actions[action] = mailed end
end
actions.Mailed = nil
end
--- Migrate the former Inventory checkbox and combined mail action into standalone settings.
---@param profile table Saved profile, including profiles from earlier v38 development builds.
function module:MigrateProfileSettings(profile)
local config = profile.inventoryLog or {}
profile.inventoryLog = config
local inventory = rawget(profile, "inventory")
local legacy = type(inventory) == "table" and rawget(inventory, "inventoryLogEnabled")
if rawget(config, "enabled") == nil then config.enabled = legacy == true end
if type(inventory) == "table" then inventory.inventoryLogEnabled = nil end
if config.entriesToKeep == nil then config.entriesToKeep = 3000 end
if config.actionsToLog == nil then config.actionsToLog = {} end
config.actionsToLog.Unknown, config.actionsToLog.Used = nil, nil
migrateMailActions(config.actionsToLog)
end
--- Migrate mail directions and retire removed ledger filters without losing character history.
---@param character table Saved character data, including earlier v38 development builds.
function module:MigrateCharacterSettings(character)
character.inventoryLog = character.inventoryLog or {}
local data = character.inventoryLog
for _, field in ipairs({ "entries", "actions", "bindings", "categories" }) do
data[field] = data[field] or {}
end
data.categories.special = nil
data.actions.Unknown, data.actions.Used = nil, nil
migrateMailActions(data.actions)
-- Resolve former Essentials through item metadata when the cache becomes available.
for _, entry in ipairs(data.entries) do
if entry.category == "special" then entry.category = nil end
if entry.action == "Mailed" then
entry.action = entry.direction == 1 and "Mail" or "Sent"
-- Older received entries never captured a sender; any legacy counterparty is not trustworthy.
if entry.direction == 1 then entry.counterparty = nil end
end
end
end
--- Return module settings, preserving choices made before the standalone section existed.
---@return table config Active profile's logging preferences.
function module:GetSettings()
self:MigrateProfileSettings(Self.db.profile)
return Self.db.profile.inventoryLog
end
--- Return the current character's ledger, independent of the active profile.
---@return table ledger Saved entries and filter selections.
local function ledger()
return Self.db.char.inventoryLog
end
--- Read a cached localized quest title without inventing a name for older records.
---@param questID number|nil Quest ID captured with the reward.
---@return string|nil title Available native quest title.
local function questTitle(questID)
if type(questID) ~= "number" or questID <= 0
or not C_QuestLog or not C_QuestLog.GetTitleForQuestID then return nil end
local title = C_QuestLog.GetTitleForQuestID(questID)
return title ~= "" and title or nil
end
--- Report whether item logging is enabled for the current profile.
---@return boolean enabled Whether to observe inventory changes.
function module:IsLoggingEnabled()
return self:GetSettings().enabled == true
end
--- Extract a variant identity without hyperlink presentation or viewer-dependent item fields.
---@param link string|nil Item hyperlink.
---@return string|nil identity Item modifiers, or the original non-item link.
local function itemIdentity(link)
if not link then return nil end
local payload = link:match("|H(item:[^|]+)|h") or link
if not payload:match("^item:") then return payload end
local fields = { strsplit(":", payload) }
-- With the "item" prefix included, fields 10/11 are link level and viewing specialization.
-- Keep all physical modifiers, including random-property seeds and bonus IDs, unchanged.
if fields[10] then fields[10] = "0" end
if fields[11] then fields[11] = "0" end
-- Native links can represent absent modifiers with empty fields or omit a zero-valued tail.
for index, field in ipairs(fields) do
if field == "" then fields[index] = "0" end
end
for index = #fields, 3, -1 do
if fields[index] ~= "0" then break end
fields[index] = nil
end
return table.concat(fields, ":")
end
--- Add quantities by stable variant without losing the item's original hyperlink or metadata.
---@param items table Aggregates indexed by stable item variant.
---@param item table Item metadata, including its link.
---@param count number Quantity to add.
local function addItem(items, item, count)
local identity = itemIdentity(item.link)
local existing = items[identity]
if not existing then
existing = {}
for key, value in pairs(item) do existing[key] = value end
existing.count = 0
items[identity] = existing
end
existing.count = existing.count + count
end
--- Capture mail/trade attachments as inventory until the transaction actually succeeds.
---@param kind string "mail", "player", or "target".
---@return table items Attached items indexed by stable variant.
local function attachments(kind)
local items = {}
for slot = 1, (kind == "mail" and (ATTACHMENTS_MAX_SEND or 12) or 6) do
local link, count
if kind == "mail" then
link = GetSendMailItemLink and GetSendMailItemLink(slot)
if link then count = select(4, GetSendMailItem(slot)) end
elseif kind == "player" then
link = GetTradePlayerItemLink and GetTradePlayerItemLink(slot)
if link then count = select(3, GetTradePlayerItemInfo(slot)) end
else
link = GetTradeTargetItemLink and GetTradeTargetItemLink(slot)
if link then count = select(3, GetTradeTargetItemInfo(slot)) end
end
if link and count and count > 0 then addItem(items, { link = link }, count) end
end
return items
end
--- Read a stable total of bags, equipped items, and uncommitted outgoing attachments.
---@return table state Totals, bag-slot identities, and visible bank quantities.
local function readInventory()
local state = { items = {}, slots = {}, bank = {} }
local playerBags = {}
local lastBag = 0
for _, bag in ipairs(Self.ListviewBag:GetInventoryBagIDs()) do
lastBag = math.max(lastBag, bag)
playerBags[bag] = true
for slot = 1, C_Container.GetContainerNumSlots(bag) do
local info = C_Container.GetContainerItemInfo(bag, slot)
if info and info.hyperlink then
local key = info.hyperlink .. ":" .. tostring(info.isBound)
local item = metadataCache[key]
if not item then
item = Self.ListviewBag:GetInventoryLogMetadata(bag, slot, info)
if item.name then metadataCache[key] = item end
end
addItem(state.items, item, info.stackCount)
state.slots[bag .. ":" .. slot] = { link = item.link, count = info.stackCount, item = item }
end
end
end
-- Equipped gear and bag containers are still owned; equipping them is not a gain or loss.
for slot = 1, lastBag + 19 do
local link = GetInventoryItemLink and GetInventoryItemLink("player", slot)
if link then
local old = snapshot and snapshot.items[itemIdentity(link)]
addItem(state.items, old or Self.ListviewBag:GetInventoryLogMetadata(nil, nil,
{ hyperlink = link, isBound = true }),
GetInventoryItemCount("player", slot))
end
end
local heldMail = attachments("mail")
-- Server responses can outlive the visible attachment slots. Keep submitted mail in escrow.
for identity, item in pairs(outgoingMail) do
local held = heldMail[identity] and heldMail[identity].count or 0
if held < item.count then addItem(heldMail, item, item.count - held) end
end
for _, item in pairs(heldMail) do
addItem(state.items, snapshot and snapshot.items[itemIdentity(item.link)] or item, item.count)
end
if tradeOpen then
for _, item in pairs(attachments("player")) do
addItem(state.items, snapshot and snapshot.items[itemIdentity(item.link)] or item, item.count)
end
end
if bankOpen then
local bankBags = { [BANK_CONTAINER or -1] = true }
if REAGENTBANK_CONTAINER then bankBags[REAGENTBANK_CONTAINER] = true end
for bag = lastBag + 1, lastBag + (NUM_BANKBAGSLOTS or 7) do bankBags[bag] = true end
if C_Bank and C_Bank.FetchViewableBankTypes and C_Bank.FetchPurchasedBankTabIDs then
for _, bankType in ipairs(C_Bank.FetchViewableBankTypes()) do
for _, bag in ipairs(C_Bank.FetchPurchasedBankTabIDs(bankType)) do bankBags[bag] = true end
end
end
for bag in pairs(bankBags) do
if not playerBags[bag] then
for slot = 1, C_Container.GetContainerNumSlots(bag) do
local info = C_Container.GetContainerItemInfo(bag, slot)
if info and info.hyperlink then
local identity = itemIdentity(info.hyperlink)
state.bank[identity] = (state.bank[identity] or 0) + info.stackCount
end
end
end
end
end
if guildBankOpen and GetNumGuildBankTabs then
for tab = 1, GetNumGuildBankTabs() do
for slot = 1, 98 do
local link = GetGuildBankItemLink(tab, slot)
if link then
local count = select(2, GetGuildBankItemInfo(tab, slot))
local identity = itemIdentity(link)
state.bank[identity] = (state.bank[identity] or 0) + count
end
end
end
end
return state
end
--- Remember an action candidate; only a matching inventory delta commits a log entry.
---@param action string Action label.
---@param link string Exact item link.
---@param count number Maximum quantity attributable to this action.
---@param direction number 1 for incoming items, -1 for outgoing items.
---@param item table|nil Metadata of the exact source slot when known.
---@param details table|nil Loot source and location captured before the slot disappears.
---@param counterparty string|nil Mail sender captured before an inbox attachment is claimed.
---@return table|nil candidate Pending correlation, if logging is enabled.
function module:Expect(action, link, count, direction, item, details, counterparty)
if not observing or not self:IsLoggingEnabled() or not link or count <= 0 then return end
local candidate = { action = action, link = link, identity = itemIdentity(link), remaining = count,
direction = direction, item = item, details = details, counterparty = counterparty,
expires = GetTime() + CORRELATION_SECONDS }
pending[#pending + 1] = candidate
self:QueueReconcile()
return candidate
end
--- Append a selected, confirmed item change without pruning on the hot path.
---@param item table Captured metadata.
---@param action string Action label.
---@param count number Changed quantity.
---@param direction number Sign of the inventory change.
---@param counterparty string|nil Mail sender, recipient, or trade partner captured before confirmation.
---@param details table|nil Captured loot or quest metadata; absent on older history.
function module:Record(item, action, count, direction, counterparty, details)
if not observing or not self:IsLoggingEnabled() then return end
-- Retired actions remain readable in saved history, but must never create new records.
if action == "Unknown" or action == "Used" then return end
-- Suppress records, not action correlation, so later changes still use the correct baseline.
if self:GetSettings().actionsToLog[action] == false then return end
local category = item.classID and Self.ListviewBag:GetInventoryLogCategory(item) or item.category
local entry = { timestamp = time(), link = item.link, itemID = item.itemID, icon = item.icon,
name = item.name, binding = item.binding, category = category, stackSize = item.stackSize,
action = action, quantity = count, direction = direction, counterparty = counterparty,
lootSource = details and details.lootSource, lootLocation = details and details.lootLocation,
questID = details and details.questID, questName = details and details.questName }
table.insert(ledger().entries, entry)
end
--- Commit server-confirmed transfers and offset the baseline to prevent duplicate delta records.
---@param action string Confirmed transaction type.
---@param items table Transferred quantities containing their original links.
---@param direction number Sign of the transfer.
---@param counterparty string|nil Mail recipient or trade partner captured before confirmation.
---@param details table|nil Quest metadata captured with an award.
function module:ConfirmTransfers(action, items, direction, counterparty, details)
if not observing or not self:IsLoggingEnabled() then return end
local current = readInventory()
for _, transfer in pairs(items) do
local identity = itemIdentity(transfer.link)
local item = direction > 0 and current.items[identity] or snapshot and snapshot.items[identity]
item = item or Self.ListviewBag:GetInventoryLogMetadata(nil, nil, { hyperlink = transfer.link })
self:Record(item, action, transfer.count, direction, counterparty, details)
-- Recording both sides matters when a trade exchanges identical items and its net delta is zero.
if snapshot then addItem(snapshot.items, item, direction * transfer.count) end
end
end
--- Record confirmed transactions and advance the baseline without logging unmatched changes.
function module:Reconcile()
if reconcileTimer then self:CancelTimer(reconcileTimer, true) end
reconcileTimer = nil
if not observing or not self:IsLoggingEnabled() then return end
-- A picked-up/split stack has temporarily left its slot. Wait until it is placed or deleted.
if GetCursorInfo and GetCursorInfo() == "item" then return end
local current = readInventory()
if snapshot then
local identities = {}
for identity in pairs(snapshot.items) do identities[identity] = true end
for identity in pairs(current.items) do identities[identity] = true end
for identity in pairs(identities) do
local before, after = snapshot.items[identity], current.items[identity]
local delta = (after and after.count or 0) - (before and before.count or 0)
if delta ~= 0 then
local direction, remaining = delta > 0 and 1 or -1, math.abs(delta)
local item = direction > 0 and after or before
local bankGain = (current.bank[identity] or 0) - (snapshot.bank[identity] or 0)
if direction < 0 and bankGain > 0 then
local count = math.min(remaining, bankGain)
self:Record(item, "Banked", count, direction)
remaining = remaining - count
end
for _, candidate in ipairs(pending) do
if remaining == 0 then break end
if candidate.expires >= GetTime() and candidate.identity == identity
and candidate.direction == direction and candidate.remaining > 0 then
local count = math.min(remaining, candidate.remaining)
self:Record(candidate.item or item, candidate.action, count, direction, candidate.counterparty, candidate.details)
candidate.remaining = candidate.remaining - count
remaining = remaining - count
end
end
end
end
end
snapshot = current
lastCursorLink = nil
for index = #pending, 1, -1 do
if pending[index].remaining == 0 or pending[index].expires < GetTime() then
table.remove(pending, index)
end
end
self:Refresh()
end
--- Coalesce native notifications so attachment and bag updates settle before comparison.
function module:QueueReconcile()
if observing and self:IsLoggingEnabled() and not reconcileTimer then
reconcileTimer = self:ScheduleTimer("Reconcile", 0.3)
end
end
--- Capture acquisitions before immediate consumption or resale can hide a net-zero delta.
function module:OnAcquiredBagUpdate()
if not observing or not self:IsLoggingEnabled() or not snapshot then return end
local current
for _, candidate in ipairs(pending) do
if (candidate.action == "Purchased" or candidate.action == "Created"
or (candidate.action == "Mail" and candidate.direction == 1))
and candidate.remaining > 0 and candidate.expires >= GetTime() then
current = current or readInventory()
local before, after = snapshot.items[candidate.identity], current.items[candidate.identity]
-- Leave unrelated updates coalesced so their loot, mail, and equipment notifications can settle.
if after and after.count > (before and before.count or 0) then
self:Reconcile()
return
end
end
end
end
--- Establish a fresh baseline without reporting existing possessions.
function module:ResetTracking()
if reconcileTimer then self:CancelTimer(reconcileTimer); reconcileTimer = nil end
pending, metadataCache, snapshot, auctionRequests = {}, {}, nil, {}
loot, tradeItems, outgoingMail = {}, {}, {}
inbox = {}
legacyAuctionLink, legacyAuctionRequest, outgoingMailRecipient = nil, nil, nil
lastCursorLink, gatheringUntil, gatheringKind = nil, nil, nil
merchantOpen = MerchantFrame and MerchantFrame:IsShown() or false
bankOpen = BankFrame and BankFrame:IsShown() or false
guildBankOpen = GuildBankFrame and GuildBankFrame:IsShown() or false
tradeOpen = TradeFrame and TradeFrame:IsShown() or false
if self:IsLoggingEnabled() and (not GetCursorInfo or GetCursorInfo() ~= "item") then
snapshot = readInventory()
end
self:OnInboxUpdate()
self:Refresh()
end
--- Synchronize the Ace3 module with a selected/copied/reset profile without clearing history.
function module:SyncProfile()
local enabled = self:IsLoggingEnabled()
if not Self:IsEnabled() then self:SetEnabledState(enabled); return end
local wasObserving = observing
if enabled then
self:Enable()
if wasObserving then self:ResetTracking() end
else
self:Disable()
end
end
--- Clear this character's saved entries without interrupting pending transactions.
function module:ClearLog()
wipe(ledger().entries)
if window then
window.filtered = {}
for _, row in ipairs(window.rows) do row.entry = nil; row:Hide() end
end
self:Refresh()
local registry = LibStub("AceConfigRegistry-3.0", true)
if registry then registry:NotifyChange("SlackHacks") end
end
--- Ask before clearing history, optionally after disabling the module.
---@param disabledProfile table|nil Profile whose module was just disabled.
function module:RequestClearLog(disabledProfile)
local id = disabledProfile and "SLACKHACKS_DISABLE_INVENTORY_LOG_CLEAR" or "SLACKHACKS_CLEAR_INVENTORY_LOG"
StaticPopupDialogs[id] = {
text = disabledProfile and "Inventory Log is disabled. Also clear this character's inventory log?"
or "Clear this character's inventory log? This cannot be undone.",
button1 = YES,
button2 = NO,
timeout = 0,
whileDead = true,
hideOnEscape = true,
--- Only clear the captured character history and a still-disabled profile.
---@param _ table Confirmation dialog.
---@param data table Captured ledger and optional disabled profile.
OnAccept = function(_, data)
if ledger() ~= data.ledger or (data.profile and
(Self.db.profile ~= data.profile or module:IsLoggingEnabled())) then
prn("The profile or Inventory Log setting changed; the log was not cleared.")
return
end
module:ClearLog()
end,
}
if not StaticPopup_Show(id, nil, nil, { ledger = ledger(), profile = disabledProfile }) then
prn("The Inventory Log confirmation could not be shown; existing logs were kept.")
end
end
--- Enable/disable the Ace3 module and offer to clear history when disabling it.
---@param enabled boolean Whether to observe new changes.
function module:SetLoggingEnabled(enabled)
local config = self:GetSettings()
local wasEnabled = config.enabled
config.enabled = enabled == true
self:SyncProfile()
if wasEnabled and not config.enabled and #ledger().entries > 0 then
self:RequestClearLog(Self.db.profile)
end
local registry = LibStub("AceConfigRegistry-3.0", true)
if registry then registry:NotifyChange("SlackHacks") end
end
--- Validate the numeric retention input without imposing an arbitrary upper limit.
---@param value string|number Retention input.
---@return boolean|string valid True or an AceConfig validation message.
function module:ValidateEntriesToKeep(value)
local count = tonumber(value)
if count and count >= 1 and count < math.huge and count == math.floor(count) then return true end
return "Enter a positive whole number of log entries."
end
--- Apply a valid retention limit and prune once when the preference changes.
---@param value string|number Retention input.
function module:SetEntriesToKeep(value)
local valid = self:ValidateEntriesToKeep(value)
if valid ~= true then prn(valid); return end
self:GetSettings().entriesToKeep = tonumber(value)
self:Purge()
end
--- Periodically keep only the newest entries, allowing overflow between maintenance passes.
function module:Purge()
local entries = ledger().entries
local retention = self:GetSettings().entriesToKeep
local excess = #entries - retention
if excess <= 0 then return end
for i = 1, retention do entries[i] = entries[i + excess] end
for i = #entries, retention + 1, -1 do entries[i] = nil end
self:Refresh()
end
--- Remember the item on the cursor before a possible confirmed deletion.
function module:OnCursorChanged()
if not self:IsLoggingEnabled() then return end
local kind, _, link = GetCursorInfo()
if kind == "item" then lastCursorLink = link end
self:QueueReconcile()
end
--- Resolve actual corpse GUIDs to available native unit names without guessing from the current target.
---@param sources table Alternating source GUIDs and quantities from GetLootSourceInfo.
---@return string|nil name Source names, or nil when any source cannot be identified.
local function lootSourceName(sources)
local names, seen = {}, {}
for index = 1, #sources, 2 do
local guid, name = sources[index]
local unit = UnitTokenFromGUID and UnitTokenFromGUID(guid)
if unit and UnitGUID(unit) == guid then name = UnitName(unit) end
if not name or name == "" then
for _, token in ipairs({ "target", "mouseover", "focus" }) do
if UnitGUID(token) == guid then
name = UnitName(token)
if name and name ~= "" then break end
end
end
end
if not name or name == "" then return nil end
if not seen[name] then names[#names + 1], seen[name] = name, true end
end
return #names > 0 and table.concat(names, ", ") or nil
end
--- Capture the native subzone and zone at loot time, omitting unavailable or duplicate names.
---@return string|nil location Loot location.
local function lootLocation()
local zone = GetRealZoneText and GetRealZoneText() or ""
if zone == "" and GetZoneText then zone = GetZoneText() or "" end
local subzone = GetSubZoneText and GetSubZoneText() or ""
if subzone ~= "" and zone ~= "" and subzone ~= zone then return subzone .. ", " .. zone end
return subzone ~= "" and subzone or zone ~= "" and zone or nil
end
--- Capture loot identities, source names, and location before cleared slots disappear.
---@param event string Native loot-ready/open event.
function module:OnLootOpened(event)
if not self:IsLoggingEnabled() then return end
if event == "LOOT_OPENED" and next(loot) then return end
loot = {}
for slot = 1, GetNumLootItems() do
local link = GetLootSlotLink(slot)
if link then
local count = select(3, GetLootSlotInfo(slot))
local sources = { GetLootSourceInfo(slot) }
local action, skinning, gatheringNode, fishing
if IsFishingLoot and IsFishingLoot() then
action = "Gathered"
fishing = true
elseif #sources > 0 then
local corpses = true
local nodes = true
for i = 1, #sources, 2 do
if not sources[i]:match("^Creature%-") then corpses = false end
if not sources[i]:match("^GameObject%-") then nodes = false end
end
if gatheringUntil and gatheringUntil >= GetTime()
and ((gatheringKind == 8613 and corpses) or (gatheringKind ~= 8613 and nodes)) then
action = "Gathered"
skinning = gatheringKind == 8613 and corpses
gatheringNode = nodes and (gatheringKind == 2575 or gatheringKind == 2366)
fishing = gatheringKind == 7620 and nodes
elseif corpses then
action = "Looted"
end
end
local creatureLoot = action == "Looted" or skinning
loot[slot] = { link = link, count = count, action = action,
sources = creatureLoot and sources or nil,
lootSource = creatureLoot and lootSourceName(sources) or nil,
lootLocation = (creatureLoot or gatheringNode or fishing) and lootLocation() or nil }
end
end
gatheringUntil, gatheringKind = nil, nil
end
--- Attribute a cleared loot slot only if that item actually enters the player's inventory.
---@param event string Native event.
---@param slot number Cleared loot slot.
function module:OnLootSlotCleared(event, slot)
local item = loot[slot]
if item then
if item.sources and not item.lootSource then
item.lootSource = lootSourceName(item.sources)
end
if item.action then self:Expect(item.action, item.link, item.count, 1, nil, item) end
loot[slot] = nil
end
self:QueueReconcile()
end
--- Recognize localized gathering casts without logging spell reagent or item consumption.
---@param event string Native event.
---@param unit string Casting unit.
---@param castGUID string Cast identity.
---@param spellID number Completed spell.
function module:OnSpellSucceeded(event, unit, castGUID, spellID)
if not observing or unit ~= "player" or not self:IsLoggingEnabled() then return end
local getName = C_Spell and C_Spell.GetSpellName or GetSpellInfo
local name = getName(spellID)
for _, id in ipairs({ 2575, 2366, 8613, 7620 }) do
local professionName = getName(id)
if name and professionName and name == professionName then
gatheringUntil = GetTime() + CORRELATION_SECONDS
gatheringKind = id
return
end
end
end
--- Correlate Blizzard's localized self-creation messages with confirmed inventory gains.
---@param event string Chat event.
---@param message string Native item creation or loot message.
function module:OnItemCreated(event, message)
if not observing or not self:IsLoggingEnabled() then return end
local link = message:match("(|c%x+|Hitem:[^|]+|h.-|h|r)")
or message:match("(|Hitem:[^|]+|h.-|h)")
if not link then return end
local quantity
if message == LOOT_ITEM_CREATED_SELF:format(link) then
quantity = 1
else
-- Parse counts outside the hyperlink so digits in item IDs and item names cannot become quantities.
local first, last = message:find(link, 1, true)
quantity = tonumber((message:sub(1, first - 1) .. message:sub(last + 1)):match("%d+"))
if not quantity or quantity < 1 or message ~= LOOT_ITEM_CREATED_SELF_MULTIPLE:format(link, quantity) then return end
end
self:Expect("Created", link, quantity, 1)
self:OnAcquiredBagUpdate()
end
--- Record the actual item award rather than relying on reward-dialog data or turn-in ordering.
---@param event string Native reward event.
---@param questID number Quest that awarded the item.
---@param link string Actual reward hyperlink.
---@param quantity number Awarded item quantity.
function module:OnQuestLootReceived(event, questID, link, quantity)
if not observing or not self:IsLoggingEnabled() then return end
if type(link) ~= "string" or link == "" or type(quantity) ~= "number" or quantity < 1
or quantity >= math.huge or quantity ~= math.floor(quantity) then
prn("Could not identify a confirmed quest reward; its inventory change will remain unattributed.")
return
end
-- QUEST_LOOT_RECEIVED is the native award confirmation, even before QUEST_TURNED_IN.
local title = questTitle(questID)
self:ConfirmTransfers("Quest", { { link = link, count = quantity } }, 1, nil,
{ questID = questID, questName = title })
if not title and type(questID) == "number" and questID > 0 and C_QuestLog
and C_QuestLog.RequestLoadQuestByID and questTitleRequests[questID] == nil
and self:GetSettings().actionsToLog.Quest ~= false then
questTitleRequests[questID] = true
C_QuestLog.RequestLoadQuestByID(questID)
end
self:QueueReconcile()
end
--- Fill recorded quest titles after Blizzard completes an optional metadata request.
---@param event string Native quest-data event.
---@param questID number Loaded quest ID.
---@param success boolean Whether the request succeeded.
function module:OnQuestDataLoaded(event, questID, success)
if questTitleRequests[questID] ~= true then return end
questTitleRequests[questID] = false
local title = success and questTitle(questID)
if not title then
prn("Could not load the quest name for Inventory Log (quest " .. questID .. ").")
return
end
for _, entry in ipairs(ledger().entries) do
if entry.action == "Quest" and entry.questID == questID and not entry.questName then entry.questName = title end
end
self:Refresh()
end
--- Capture both sides and the partner of a trade before the native window clears them.
function module:OnTradeUpdated()
if not self:IsLoggingEnabled() or not tradeOpen then return end
tradeItems = { player = attachments("player"), target = attachments("target"),
counterparty = tradeItems.counterparty or unitFullName("NPC") }
self:QueueReconcile()
end
--- Remember the selected legacy auction variant before posting clears its sell-slot data.
function module:OnAuctionSellChanged()
if not self:IsLoggingEnabled() then return end
local itemID, guid = select(10, GetAuctionSellItemInfo())
if not itemID and not guid then self:QueueReconcile(); return end
legacyAuctionLink = guid and C_Item.GetItemLinkByGUID and C_Item.GetItemLinkByGUID(guid)
if not legacyAuctionLink and snapshot and itemID then
-- Older clients without GUID links are safe only when the owned item ID has one variant.
for _, item in pairs(snapshot.items) do
if item.itemID == itemID then
if legacyAuctionLink then legacyAuctionLink = nil; break end
legacyAuctionLink = item.link
end
end
end
self:QueueReconcile()
end
--- Attribute traded items only after Blizzard announces a successful transaction.
---@param event string Native event.
---@param messageType number Native message identifier.
---@param message string Localized message.
function module:OnInfoMessage(event, messageType, message)
if message ~= ERR_TRADE_COMPLETE then return end
self:ConfirmTransfers("Traded", tradeItems.player or {}, -1, tradeItems.counterparty)
self:ConfirmTransfers("Traded", tradeItems.target or {}, 1, tradeItems.counterparty)
tradeItems = {}
self:QueueReconcile()
end
--- Attribute outgoing attachments after the server confirms mail delivery.
function module:OnMailSuccess()
local sent, recipient = outgoingMail, outgoingMailRecipient
outgoingMail, outgoingMailRecipient = {}, nil
self:ConfirmTransfers("Sent", sent, -1, recipient)
self:QueueReconcile()
end
--- Release submitted-mail escrow after failure; returning draft items are not new acquisitions.
function module:OnMailFailed()
outgoingMail, outgoingMailRecipient = {}, nil
self:QueueReconcile()
end
--- Cache inbox senders and attachments before native pickup requests remove their information.
---@param event string|nil Native mailbox event, or nil for a baseline or pickup-time refresh.
function module:OnInboxUpdate(event)
local previous = inbox
inbox = {}
if not observing or event == "MAIL_CLOSED" or not GetInboxNumItems or not GetInboxItemLink
or not GetInboxItem then return end
if event ~= "MAIL_SHOW" and not (MailFrame and MailFrame:IsShown()) then return end
local messageCount = GetInboxNumItems()
-- Removing a message shifts inbox indices; its request token must not belong to the next message.
if messageCount < #previous then previous = {} end
for index = 1, messageCount do
inbox[index] = {}
local sender = GetInboxHeaderInfo and select(3, GetInboxHeaderInfo(index))
if sender == "" then sender = nil end
for slot = 1, (ATTACHMENTS_MAX_RECEIVE or ATTACHMENTS_MAX or 16) do
local link = GetInboxItemLink(index, slot)
local count = link and select(4, GetInboxItem(index, slot))
if link and count and count > 0 then
local old = previous[index] and previous[index][slot]
-- Keep the request token across refreshes so repeated pickup clicks cannot double-count a gain.
inbox[index][slot] = old and old.link == link and old.count == count and old.sender == sender and old
or { link = link, count = count, sender = sender }
end
end
end
end
--- Track merchant context and refresh accessible bank/trade holdings at native interaction boundaries.
---@param event string Native open/close event.
function module:OnInteraction(event)
if not self:IsLoggingEnabled() then return end
if event == "MERCHANT_SHOW" then
-- Automatic sales can run during this event before Blizzard shows MerchantFrame.
merchantOpen = true
elseif event == "MERCHANT_CLOSED" then
merchantOpen = false
elseif event == "BANKFRAME_OPENED" or event == "GUILDBANKFRAME_OPENED" then
if event == "BANKFRAME_OPENED" then bankOpen = true else guildBankOpen = true end
-- Opening a bank must not make all of its pre-existing contents look like new deposits.
if snapshot then snapshot.bank = readInventory().bank end
elseif event == "BANKFRAME_CLOSED" or event == "GUILDBANKFRAME_CLOSED" then
self:Reconcile()
if event == "BANKFRAME_CLOSED" then bankOpen = false else guildBankOpen = false end
if snapshot then snapshot.bank = {} end
elseif event == "TRADE_SHOW" then
tradeOpen = true
tradeItems = { counterparty = unitFullName("NPC") }
elseif event == "TRADE_CLOSED" then
tradeOpen = false
end
self:QueueReconcile()
end
--- Renew a confirmed request, restoring it if it expired while the native dialog was open.
---@param candidate table Pending action.
local function renewExpectedAction(candidate)
candidate.expires = GetTime() + CORRELATION_SECONDS
for _, entry in ipairs(pending) do
if entry == candidate then module:QueueReconcile(); return end
end
pending[#pending + 1] = candidate
module:QueueReconcile()
end
--- Observe protected requests without initiating any protected action ourselves.
function module:InstallHooks()
if self.hooksInstalled then return end
self.hooksInstalled = true
--- Remember sold quantities from the last stable bag slots.
---@param bag number Bag identifier.
---@param slot number Slot identifier.
---@param onSelf boolean|nil True when explicitly using rather than selling the item.
local function sold(bag, slot, onSelf)
if onSelf or not module:IsLoggingEnabled()
or not (merchantOpen or (MerchantFrame and MerchantFrame:IsShown())) then return end
local item = snapshot and snapshot.slots[bag .. ":" .. slot]
if item then module:Expect("Sold", item.link, item.count, -1, item.item) end
end
hooksecurefunc(C_Container, "UseContainerItem", sold)
if BuyMerchantItem then
--- Attribute only confirmed gains, using the requested units or the vendor's default bundle.
---@param index number Merchant item index.
---@param quantity number|nil Explicit units; nil buys the displayed bundle.
hooksecurefunc("BuyMerchantItem", function(index, quantity)
if not observing or not module:IsLoggingEnabled() then return end
local link = GetMerchantItemLink(index)
if quantity == nil then
if C_MerchantFrame and C_MerchantFrame.GetItemInfo then
local info = C_MerchantFrame.GetItemInfo(index)
quantity = info and info.stackCount
elseif GetMerchantItemInfo then
quantity = select(4, GetMerchantItemInfo(index))
end
end
if not link or not quantity or quantity <= 0 then
prn("Could not identify the requested vendor purchase; its inventory change will remain unattributed.")
return
end
module:Expect("Purchased", link, quantity, 1)
module:OnAcquiredBagUpdate()
end)
end
if C_MerchantFrame and C_MerchantFrame.SellAllJunkItems then
--- Observe Blizzard's bulk sale without bypassing its own eligibility checks.
hooksecurefunc(C_MerchantFrame, "SellAllJunkItems", function()
if not module:IsLoggingEnabled() or not snapshot
or not (merchantOpen or (MerchantFrame and MerchantFrame:IsShown())) then return end
for _, item in pairs(snapshot.items) do
if item.quality == 0 then module:Expect("Sold", item.link, item.count, -1) end
end
end)
end
if DeleteCursorItem then
--- Confirm deletion through the matching negative delta.
hooksecurefunc("DeleteCursorItem", function()
local item = snapshot and snapshot.items[itemIdentity(lastCursorLink)]
if item then module:Expect("Destroyed", item.link, item.count, -1) end
module:QueueReconcile()
end)
end
if SendMail then
--- Keep the submitted recipient and draft until MAIL_SEND_SUCCESS confirms delivery.
---@param recipient string Mail recipient passed to Blizzard's send request.
hooksecurefunc("SendMail", function(recipient)
if observing and module:IsLoggingEnabled() then
outgoingMail = attachments("mail")
outgoingMailRecipient = recipient
module:Reconcile()
end
end)
end
--- Correlate requested inbox attachments with actual gains, not merely opening or returning mail.
---@param index number Inbox message index.
---@param slot number|nil Attachment index; nil requests all attachments.
local function receivedMail(index, slot)
if not observing or not module:IsLoggingEnabled() then return end
local items = inbox[index]
-- Open All can see attachments that were unavailable when the earlier mailbox event was cached.
if not items or not next(items) or (slot and not items[slot]) then
module:OnInboxUpdate()
items = inbox[index]
end
if not items or (slot and not items[slot]) then
prn("Could not identify the requested mail attachments; their inventory changes will remain unattributed.")
return
end
for attachment, item in pairs(items) do
if not slot or attachment == slot then
if not item.request or item.request.remaining == 0 or item.request.expires < GetTime() then
item.request = module:Expect("Mail", item.link, item.count, 1, nil, nil, item.sender)
end
end
end
module:OnAcquiredBagUpdate()
end
if TakeInboxItem then
--- Observe a single native attachment pickup, including the legacy default attachment.
---@param index number Inbox message index.
---@param slot number|nil Attachment index.
hooksecurefunc("TakeInboxItem", function(index, slot) receivedMail(index, slot or 1) end)
end
if AutoLootMailItem then hooksecurefunc("AutoLootMailItem", receivedMail) end
--- Capture auction requests; failed/cancelled requests have no matching item loss.
---@param location table Native item location.
---@param duration number Listing duration.
---@param quantity number Requested quantity.
local function auctioned(location, duration, quantity)
if not module:IsLoggingEnabled() or not snapshot or not location:IsBagAndSlot() then return end
local bag, slot = location:GetBagAndSlot()
local item = snapshot.slots[bag .. ":" .. slot]
if item then
auctionRequests[bag .. ":" .. slot] = module:Expect("Auctioned", item.link, quantity, -1, item.item)
end
end
--- Refresh a delayed confirmation without counting Post and ConfirmPost as two transactions.
---@param location table Native item location.
---@param duration number Listing duration.
---@param quantity number Confirmed quantity.
local function auctionConfirmed(location, duration, quantity)
if not module:IsLoggingEnabled() or not location:IsBagAndSlot() then return end
local bag, slot = location:GetBagAndSlot()
local candidate = auctionRequests[bag .. ":" .. slot]
if candidate and candidate.remaining == quantity then
renewExpectedAction(candidate)
else
auctioned(location, duration, quantity)
end
end
if C_AuctionHouse then
for _, method in ipairs({ "PostItem", "PostCommodity", "ConfirmPostItem", "ConfirmPostCommodity" }) do
if C_AuctionHouse[method] then
hooksecurefunc(C_AuctionHouse, method, method:match("^Confirm") and auctionConfirmed or auctioned)
end
end
end
if PostAuction or StartAuction then
--- Observe legacy posting requests; the selected sell slot still belongs to the player's bags.
---@param minimumBid number Minimum bid.
---@param buyout number Buyout.
---@param duration number Listing duration.
---@param stackSize number Items per listing.
---@param numStacks number Number of listings.
---@param confirmed boolean|nil Whether this is a delayed native confirmation.
local function legacyPosted(minimumBid, buyout, duration, stackSize, numStacks, confirmed)
if not module:IsLoggingEnabled() or not legacyAuctionLink then return end
local quantity = stackSize * numStacks
if confirmed and legacyAuctionRequest and legacyAuctionRequest.link == legacyAuctionLink
and legacyAuctionRequest.remaining == quantity then
renewExpectedAction(legacyAuctionRequest)
else
legacyAuctionRequest = module:Expect("Auctioned", legacyAuctionLink, quantity, -1)
end
end
if PostAuction then hooksecurefunc("PostAuction", legacyPosted) end
if StartAuction then hooksecurefunc("StartAuction", legacyPosted) end
end
end
--- Keep profile callbacks available even while the logging module is disabled.
function module:OnInitialize()
self:MigrateCharacterSettings(Self.db.char)
Self.db.RegisterCallback(self, "OnProfileChanged", "SyncProfile")
Self.db.RegisterCallback(self, "OnProfileCopied", "SyncProfile")
Self.db.RegisterCallback(self, "OnProfileReset", "SyncProfile")
self:SetEnabledState(self:IsLoggingEnabled())
end
--- Start observation and periodic maintenance independently of replacement bags.
function module:OnEnable()
if not self:IsLoggingEnabled() then self:SetEnabledState(false); return end
self:InstallHooks()
for _, event in ipairs({ "BAG_UPDATE_DELAYED", "PLAYER_EQUIPMENT_CHANGED", "MAIL_SEND_INFO_UPDATE",
"TRADE_PLAYER_ITEM_CHANGED", "TRADE_TARGET_ITEM_CHANGED", "TRADE_ACCEPT_UPDATE" }) do
self:RegisterEvent(event, event:match("^TRADE_") and "OnTradeUpdated" or "QueueReconcile")
end
for _, event in ipairs({ "BANKFRAME_OPENED", "BANKFRAME_CLOSED", "GUILDBANKFRAME_OPENED",
"GUILDBANKFRAME_CLOSED", "TRADE_SHOW", "TRADE_CLOSED", "MERCHANT_SHOW", "MERCHANT_CLOSED" }) do
self:RegisterEvent(event, "OnInteraction")
end
self:RegisterEvent("PLAYER_ENTERING_WORLD", "ResetTracking")
self:RegisterEvent("BAG_UPDATE", "OnAcquiredBagUpdate")
self:RegisterEvent("CHAT_MSG_LOOT", "OnItemCreated")
self:RegisterEvent("CURSOR_CHANGED", "OnCursorChanged")
self:RegisterEvent("LOOT_READY", "OnLootOpened")
self:RegisterEvent("LOOT_OPENED", "OnLootOpened")
self:RegisterEvent("LOOT_SLOT_CLEARED", "OnLootSlotCleared")
self:RegisterEvent("UNIT_SPELLCAST_SUCCEEDED", "OnSpellSucceeded")
self:RegisterEvent("QUEST_LOOT_RECEIVED", "OnQuestLootReceived")
self:RegisterEvent("QUEST_DATA_LOAD_RESULT", "OnQuestDataLoaded")
self:RegisterEvent("UI_INFO_MESSAGE", "OnInfoMessage")
self:RegisterEvent("MAIL_SEND_SUCCESS", "OnMailSuccess")
self:RegisterEvent("MAIL_FAILED", "OnMailFailed")
for _, event in ipairs({ "MAIL_SHOW", "MAIL_INBOX_UPDATE", "MAIL_CLOSED" }) do
self:RegisterEvent(event, "OnInboxUpdate")
end
self:RegisterEvent("GET_ITEM_INFO_RECEIVED", "Refresh")
if GetAuctionSellItemInfo then self:RegisterEvent("NEW_AUCTION_UPDATE", "OnAuctionSellChanged") end
observing = true
self:ResetTracking()
self:Purge()
self:ScheduleRepeatingTimer("Purge", 300)
end
--- Stop observations and hide the ledger when the module or its parent is disabled.
function module:OnDisable()
-- AceAddon preserves a child's desired enabledState when its parent shuts down.
observing = false
merchantOpen = false
questTitleRequests = {}
self:UnregisterAllEvents()
self:CancelAllTimers()
reconcileTimer, snapshot, inbox = nil, nil, {}