Repository navigation
Expand file tree
/
Copy pathSelfVendor.lua
More file actions
1737 lines (1640 loc) · 81.5 KB
/
Copy pathSelfVendor.lua
File metadata and controls
1737 lines (1640 loc) · 81.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
--[[
SelfVendor.lua
Lets players request scripted trades using item keywords in party, raid, instance, say, or
whisper chat. Multiple keywords combine into one queued request. Requests can optionally be
restricted to guild members (`selfVendor.guildOnly`). Automatic Trade Response
(`selfVendor.autoTradeMode`, also set via `/slack vend <mode>`) vends a fixed mode to anyone who
opens a trade with us, jumping the queue, independent of the chat request toggles.
Design decisions worth remembering:
- Everything funnels through a FIFO queue (`self.tradeQueue`) so only one trade is ever
prepared/opened at a time. WoW's trade window, bag manipulation, and item-splitting APIs
are single-actor and asynchronous, so vending to multiple people concurrently would corrupt
state (wrong items ending up in the wrong trade window).
- We enqueue a requester *before* doing any async work (inspecting, bag polling) so their
queue position is stable and can be reported back immediately, even though the inspect/bag
checks that follow are asynchronous.
- Item quantities are handled via C_Container.SplitContainerItem + polling rather than trusting
an immediate stack read, because the client updates container info asynchronously after a
split; polling with backoff (see PollPreparedStack) avoids racing the game's own item move.
- Vantus Runes are intentionally excluded from the buffs/consumables bundle because they are
per-raid-instance items you may not want handed out by
default, unlike flasks/oils/augment runes which are always useful. They get their own mode
instead.
]]
setfenv(1, _G.SlackHacks)
local module = Self:NewModule("SelfVendor", "AceEvent-3.0")
Self.SelfVendor = module
local maxTradeSlots = MAX_TRADABLE_ITEMS or 6
local VendorMode = Enum.SelfVendorMode
--- Look up the saved-variable configuration table for a given vendor mode.
-- Centralized so every read/write of a mode's `enabled`/`runeQuantity`
-- goes through one place instead of repeating the `db.profile.selfVendor.modes[mode]` path.
-- @param mode number Enum.SelfVendorMode value.
-- @return table|nil the mode's profile configuration table, or nil if unknown.
local function modeConfiguration(mode)
local details = SELF_VENDOR_MODES[mode]
if details and details.flaskItemName then mode = VendorMode.FLASK end
return db.profile.selfVendor.modes[mode]
end
--- Resolve which vendor mode a typed slash command corresponds to.
-- SELF_VENDOR_MODES stores a stable `command` string per mode (e.g. "vantusrune") so slash
-- commands stay human-typeable and decoupled from the Enum's numeric values.
-- @param command string lower-cased command word (already stripped of "/slack vendor ").
-- @return number|nil matching Enum.SelfVendorMode value, or nil if no mode uses that command.
local function modeForCommand(command)
for mode, details in pairs(SELF_VENDOR_MODES) do
if details.command == command then return mode end
end
end
local function requestIncludesMode(request, mode)
return request == mode or type(request) == "table" and request[mode] == true
end
local function requestLabel(request)
local labels = {}
for mode, details in pairs(SELF_VENDOR_MODES) do
if requestIncludesMode(request, mode) then labels[#labels + 1] = details.name end
end
table.sort(labels)
return #labels > 0 and table.concat(labels, ", ") or "unknown request"
end
local chatRequestModes = {
flask = VendorMode.FLASK, flasks = VendorMode.FLASK,
crit = VendorMode.CRIT_FLASK, criticalstrike = VendorMode.CRIT_FLASK,
critflask = VendorMode.CRIT_FLASK, criticalstrikeflask = VendorMode.CRIT_FLASK,
mast = VendorMode.MASTERY_FLASK, mastery = VendorMode.MASTERY_FLASK,
mastflask = VendorMode.MASTERY_FLASK, masteryflask = VendorMode.MASTERY_FLASK,
haste = VendorMode.HASTE_FLASK, hasteflask = VendorMode.HASTE_FLASK,
vers = VendorMode.VERSATILITY_FLASK, versatility = VendorMode.VERSATILITY_FLASK,
versability = VendorMode.VERSATILITY_FLASK,
versflask = VendorMode.VERSATILITY_FLASK, versatilityflask = VendorMode.VERSATILITY_FLASK,
versabilityflask = VendorMode.VERSATILITY_FLASK,
oil = VendorMode.OIL, oils = VendorMode.OIL,
rune = VendorMode.AUGMENT_RUNES, runes = VendorMode.AUGMENT_RUNES,
augmentrune = VendorMode.AUGMENT_RUNES, augmentrunes = VendorMode.AUGMENT_RUNES,
vantus = VendorMode.VANTUS_RUNE, vantusrune = VendorMode.VANTUS_RUNE,
vantusrunes = VendorMode.VANTUS_RUNE,
buffs = VendorMode.CONSUMABLES,
consumables = VendorMode.CONSUMABLES,
augments = VendorMode.AUGMENTS,
}
local SELF_VENDOR_ALLOWED_WORDS = { "and", "give", "need", "please" }
--- Parse a chat message into the set of Self Vendor modes it requests.
-- Multi-word phrases ("vantus rune", "augment rune", "<stat> flask") are matched before single
-- words so the trailing word isn't also counted as its own request.
-- @param message string raw chat message text.
-- @return table|nil set of requested Enum.SelfVendorMode values (mode -> true), string|nil reason when nothing matched.
function module:ParseChatRequest(message)
if type(message) ~= "string" then return nil, "message is not text" end
if not db.profile.selfVendor.enabled then return nil, "Self Vendor is disabled" end
local settings = db.profile.selfVendor
local prefix = settings.chatPrefix
if not prefix or prefix == "" then prefix = "!" end
local hasPrefix = message:sub(1, #prefix) == prefix
if settings.requirePrefix and not hasPrefix then return nil, "required prefix is missing" end
if hasPrefix then message = message:sub(#prefix + 1) end
local words = {}
for word in message:lower():gmatch("%w+") do
words[#words + 1] = word
end
local requested = {}
local wordIndex = 1
while wordIndex <= #words do
local word = words[wordIndex]
local nextWord = words[wordIndex + 1]
local mode = chatRequestModes[word]
if (word == "vantus" or word == "augment") and (nextWord == "rune" or nextWord == "runes") then
mode = word == "vantus" and VendorMode.VANTUS_RUNE or VendorMode.AUGMENT_RUNES
wordIndex = wordIndex + 1
end
-- "crit flask" means one crit flask; without consuming "flask" it would also queue the generic
-- Flask mode and hand out a second (spec-recommended) flask.
local modeDetails = mode and SELF_VENDOR_MODES[mode]
if modeDetails and modeDetails.flaskItemName and (nextWord == "flask" or nextWord == "flasks") then
wordIndex = wordIndex + 1
end
if not mode and not tContains(SELF_VENDOR_ALLOWED_WORDS, word) then
return nil, "unrecognized word: " .. word
end
local configuration = mode and modeConfiguration(mode)
if configuration and configuration.enabled then requested[mode] = true end
wordIndex = wordIndex + 1
end
if next(requested) then return requested end
return nil, "no enabled item triggers matched"
end
--- Look up an item's numeric ID by its display name.
-- Thin wrapper over the global ITEM_NAMES lookup table (built in StaticData.lua) that
-- tolerates ITEM_NAMES being unavailable during early load order.
-- @param itemName string exact in-game item name.
-- @return number|nil item ID, or nil if unknown.
local function itemID(itemName)
return ITEM_NAMES and ITEM_NAMES[itemName]
end
--- Normalize and validate a requested BIS data source key ("wowhead"/"icyveins"/"murlok").
-- Falls back to DEFAULT_ENHANCEMENT_SOURCE when no source is given, and returns nil (rather
-- than an invalid string) when the source doesn't actually exist in ENHANCEMENTS_BIS, so
-- callers can safely use the result as a definite "is this valid" check.
-- @param rawSource string|nil user-provided source name, any case.
-- @return string|nil canonical lower-case source key if valid, else nil.
local function enhancementSourceKey(rawSource)
local sourceKey = strlower(rawSource or DEFAULT_ENHANCEMENT_SOURCE or "")
return ENHANCEMENTS_BIS and ENHANCEMENTS_BIS[sourceKey] and sourceKey
end
--- Convert an internal source key into the display name shown to users in chat output.
-- @param sourceKey string one of "wowhead", "icyveins", "murlok".
-- @return string display name (e.g. "Icy Veins"), or the raw key if unrecognized.
local function displayEnhancementSource(sourceKey)
local names = { wowhead = "Wowhead", icyveins = "Icy Veins", murlok = "Murlok M+" }
return names[sourceKey] or sourceKey
end
--- Resolve which flask a class/spec should use, for the "murlok" data source only.
-- Murlok M+ guides don't publish their own flask recommendation, so we deliberately borrow
-- the flask choice from the Icy Veins raid data for the same class/spec rather than leaving
-- it blank. Other sources (wowhead/icyveins) carry their own `Flask` field directly in their
-- spec data and don't need this fallback.
-- @param sourceKey string enhancement data source key.
-- @param classKey string class file name (e.g. "DEATHKNIGHT").
-- @param specKey string spec key as used in ENHANCEMENTS_BIS.
-- @return string|nil flask item name, or nil if source isn't "murlok" or no match found.
local function enhancementFlaskName(sourceKey, classKey, specKey)
if sourceKey ~= "murlok" then return nil end
local classData = ENHANCEMENTS_BIS.icyveins and ENHANCEMENTS_BIS.icyveins[classKey]
local specData = classData and classData[specKey]
return specData and specData.Flask
end
--- Case-insensitively look up a personal BIS override by "Character-Realm" key.
-- Case-insensitive because character/realm names typed in slash commands or read from
-- UnitFullName may not match the exact casing stored in ENHANCEMENTS_BIS_OVERRIDES.
-- @param key string|nil "Character-Realm" identifier to look up.
-- @return table|nil override spec data, string|nil the exact key it was stored under.
local function enhancementOverrideForKey(key)
if not key or not ENHANCEMENTS_BIS_OVERRIDES then return nil end
for overrideKey, override in pairs(ENHANCEMENTS_BIS_OVERRIDES) do
if overrideKey:lower() == key:lower() then return override, overrideKey end
end
end
--- Look up a personal BIS override for a specific unit or a fallback "Name-Realm" string.
-- Overrides are gated behind isSlackwise() because they encode one person's (Slackwise's)
-- personal gear preferences that diverge from the generic class/spec guides, and shouldn't
-- silently apply to other players running this addon.
-- @param unit string|nil unit token (e.g. "target") to resolve a full name from.
-- @param fallbackName string|nil "Name-Realm" string to use if `unit` doesn't resolve.
-- @return table|nil override spec data if one exists for this character.
local function enhancementOverride(unit, fallbackName)
if not isSlackwise() or not ENHANCEMENTS_BIS_OVERRIDES then return nil end
local characterName, realmName = unit and UnitFullName(unit)
local key = characterFullName(characterName, realmName)
if not key and fallbackName then
characterName, realmName = fallbackName:match("^(.+)%-(.+)$")
key = characterFullName(characterName, realmName)
end
return enhancementOverrideForKey(key)
end
--- Find which spec key within a class's BIS data matches a raw (possibly abbreviated) spec name.
-- Searches across every enhancement data source (not just one) because a player's requested
-- source may not have a spec entry that another source does, and we only need to confirm the
-- spec name itself is valid for the class somewhere before doing per-source lookups later.
-- @param classKey string class file name.
-- @param rawSpec string user-typed spec name/abbreviation.
-- @return string|nil canonical spec key if the class/spec combination is known.
local function specNameForClass(classKey, rawSpec)
local specKey = specKeyForName(rawSpec)
for _, sourceData in pairs(ENHANCEMENTS_BIS or {}) do
local classData = sourceData[classKey]
if classData and classData[specKey] then return specKey end
end
end
--- Translate a raw BIS spec-data table (enchants/gems/flask) into a normalized recommendation
-- structure used throughout this module for both gear-check and consumable-check logic.
-- Consumables are always the same four items (flask, Thalassian Phoenix Oil, an augment rune,
-- and the current Vantus Rune) regardless of data source, since only enchants/gems/flask vary
-- by class/spec/source; hard-coding them here keeps that list in exactly one place.
-- @param data table raw spec data (Enchants/Gems/Flask) from ENHANCEMENTS_BIS or an override.
-- @param flaskName string|nil resolved flask name (see enhancementFlaskName); falls back to data.Flask.
-- @return table recommendation with slotKeys/slots/enchantNames/enchantIDs/gemNames/gemEntries/gemIDs/consumables.
local function buildBISEnhancementRecommendation(data, flaskName)
flaskName = flaskName or data.Flask
local slotKeys = { "HEAD", "SHOULDER", "CHEST", "WAIST", "LEGS", "FEET", "WRIST", "HANDS", "FINGER1", "FINGER2", "TRINKET1", "TRINKET2", "BACK", "MAINHAND", "OFFHAND" }
local slots, enchantNames, enchantIDs = {}, {}, {}
for _, slotKey in ipairs(slotKeys) do
local enchantName = data.Enchants and data.Enchants[slotKey]
if enchantName then
enchantNames[slotKey] = enchantName
enchantIDs[slotKey] = ITEM_NAMES[enchantName]
slots[#slots + 1] = SLOT_IDS[slotKey]
end
end
local gemEntries, gemNames, gemIDs = {}, {}, {}
if data.Gems and data.Gems.Primary then gemEntries[#gemEntries + 1] = { itemName = data.Gems.Primary, itemID = ITEM_NAMES[data.Gems.Primary], quantity = 1 } end
if data.Gems and data.Gems.Secondary then gemEntries[#gemEntries + 1] = { itemName = data.Gems.Secondary, itemID = ITEM_NAMES[data.Gems.Secondary], quantity = SECONDARY_GEM_QUANTITY } end
for index, gem in ipairs(gemEntries) do
gemNames[index] = gem.itemName
gemIDs[index] = ITEM_NAMES[gem.itemName]
end
return {
slotKeys = slotKeys, slots = slots, enchantNames = enchantNames, enchantIDs = enchantIDs,
gemNames = gemNames, gemEntries = gemEntries, gemIDs = gemIDs,
consumables = {
{ itemName = flaskName, itemID = ITEM_NAMES[flaskName], kind = "flask", buffName = "Flask" },
{ itemName = "Thalassian Phoenix Oil", itemID = ITEM_NAMES["Thalassian Phoenix Oil"], kind = "oil", buffName = "Thalassian Phoenix Oil", auraSpellID = 1237006 },
{ itemName = RUNE_ITEM_NAMES[1], itemID = RUNE_ITEM_IDS[1], kind = "augmentRune", buffName = "Void-Touched", quantity = 5 },
{ itemName = CURRENT_VANTUS_RUNE_NAME, itemID = ITEM_NAMES[CURRENT_VANTUS_RUNE_NAME], kind = "vantusRune", buffName = "Vantus Rune", quantity = 1 }
}
}
end
local GROUP_CHAT_EVENTS = {
CHAT_MSG_PARTY = true, CHAT_MSG_PARTY_LEADER = true,
CHAT_MSG_RAID = true, CHAT_MSG_RAID_LEADER = true,
CHAT_MSG_INSTANCE_CHAT = true, CHAT_MSG_INSTANCE_CHAT_LEADER = true,
}
--- Determine whether a chat request sender should be vended to.
-- Group channels only accept group members; say/whisper accept anyone nearby. The optional
-- guild-only setting is applied on top of both.
-- @param event string chat event name that carried the request.
-- @param sender string sender name (with or without realm).
-- @return boolean true if eligible, string|nil reason when not eligible.
local function chatSenderIsEligible(event, sender)
if GROUP_CHAT_EVENTS[event] and not groupUnitFor(sender) then
return false, "sender is not in the group"
end
if db.profile.selfVendor.guildOnly and not guildMember(sender) then
return false, "sender is not a guild member"
end
return true
end
--- Find a unit token currently pointing at the named player.
-- Say/whisper requesters usually aren't grouped, and InitiateTrade/CheckInteractDistance need a
-- real unit token, so fall back to target/focus/mouseover and then visible nameplates.
-- @param name string player name (with or without realm).
-- @return string|nil unit token, or nil if the player can't be resolved to a unit right now.
local function unitForName(name)
local unit = groupUnitFor(name)
if unit then return unit end
-- "NPC" is the open trade window's partner, which covers strangers who opened a trade with us.
for _, candidate in ipairs({ "target", "focus", "mouseover", "NPC" }) do
if UnitIsPlayer(candidate) and sameName(UnitName(candidate), name) then return candidate end
end
for index = 1, 40 do
local plate = "nameplate" .. index
if UnitIsPlayer(plate) and sameName(UnitName(plate), name) then return plate end
end
end
--- Ensure `module.pendingUnit` still refers to the pending player.
-- Nameplate/mouseover tokens are transient and can be reassigned to someone else while trade
-- items are being prepared asynchronously, so re-resolve whenever the token no longer matches.
-- @param module table the SelfVendor module.
local function refreshPendingUnit(module)
if not module.pendingName then return end
if module.pendingUnit and sameName(UnitName(module.pendingUnit), module.pendingName) then return end
module.pendingUnit = unitForName(module.pendingName)
end
--- Check whether the trade window is currently open with the named player.
-- @param name string|nil player name (with or without realm).
-- @return boolean true if a trade window is open and its partner is that player.
local function tradeWindowOpenWith(name)
if not name or not (TradeFrame and TradeFrame:IsShown()) then return false end
return sameName(UnitName("NPC"), name)
end
--- Normalize a mode for Automatic Trade Response.
-- Specific stat flasks aren't offered; they collapse to the dynamic Flask mode, which picks the
-- flask from the selected Wowhead/Icy Veins source for the trade partner's spec.
-- @param mode number|nil Enum.SelfVendorMode value.
-- @return number|nil the mode to auto-trade, or nil if it isn't a known mode.
local function autoTradeModeFor(mode)
local details = mode and SELF_VENDOR_MODES[mode]
if not details then return nil end
return details.flaskItemName and VendorMode.FLASK or mode
end
--- Read the configured Automatic Trade Response mode.
-- @return number|nil Enum.SelfVendorMode value to auto-trade, or nil when the feature is Off.
local function autoTradeMode()
local mode = db.profile.selfVendor.autoTradeMode
if mode and mode ~= 0 then return autoTradeModeFor(mode) end
end
--- Determine whether the module needs its events registered.
-- Automatic Trade Response works even when chat requests (the "Enable Self Vendor Module" toggle)
-- are off, so either one keeps the module active; ParseChatRequest still gates chat on `enabled`.
-- @return boolean true if chat requests or Automatic Trade Response are on.
local function moduleShouldBeActive()
return db.profile.selfVendor.enabled or autoTradeMode() ~= nil
end
--- Combine two Self Vendor requests into one set request.
-- @param first table|number|nil request (Enum.SelfVendorMode value or set of values).
-- @param second table|number|nil request (Enum.SelfVendorMode value or set of values).
-- @return table set of every Enum.SelfVendorMode value included in either request.
local function mergeRequests(first, second)
local merged = {}
for mode in pairs(SELF_VENDOR_MODES) do
if requestIncludesMode(first, mode) or requestIncludesMode(second, mode) then merged[mode] = true end
end
return merged
end
--- Compute the full BIS recommendation (gear + consumables) for a unit, given a data source.
-- Falls back through: requested spec -> first available spec for that class (`fallbackSpecKey`)
-- so that a source missing data for a hybrid spec doesn't hard-fail; then applies a personal
-- override (Slackwise-only) if one exists for that exact character, since a maintained personal
-- loadout should always win over generic guide data.
-- @param unit string|nil unit token to inspect (defaults to "player").
-- @param sourceKey string|nil requested/validated enhancement data source.
-- @param characterName string|nil "Name-Realm" fallback used for override lookups.
-- @return table|nil recommendation (see buildBISEnhancementRecommendation), string|nil resolved sourceKey.
local function currentRecommendation(unit, sourceKey, characterName)
local _, classFile = UnitClass(unit or "player")
local specName = getSpecName()
sourceKey = enhancementSourceKey(sourceKey)
local sourceData = sourceKey and ENHANCEMENTS_BIS[sourceKey]
local classData = sourceData and sourceData[classFile]
if not classData then return nil, sourceKey end
local specKey = specKeyForName(specName)
local fallbackSpecKey, fallbackSpecData = next(classData)
if not classData[specKey] then specKey = fallbackSpecKey end
local specData = classData and (classData[specKey] or fallbackSpecData)
local override, overrideKey = enhancementOverride(unit, characterName)
if override then
log("Using enhancement override for " .. overrideKey)
specData = override
end
return specData and buildBISEnhancementRecommendation(specData, enhancementFlaskName(sourceKey, classFile, specKey)), sourceKey
end
--- Transition module state from "pending" to "active" once the trade window has been populated.
-- This is the hand-off point between preparation (finding/splitting items, opening the trade
-- window) and the "trade in progress" phase tracked by UI_INFO_MESSAGE/TRADE_CLOSED. We
-- snapshot pendingName/pendingMode into activeTradeName/activeTradeMode
-- here (rather than leaving them in the pending* fields) so TRADE_CLOSED can
-- still report who/what was vended to even though the pending fields get cleared for the next
-- queued trade.
-- @param module table the SelfVendor module (passed explicitly since this is a local function,
-- not a method, so it can be called from contexts without `self`).
-- @param added number total item quantity actually placed into the trade window.
local function finishTradePopulation(module, added)
if added == 0 then
log("Trade population found no items to add")
prn("no Self Vendor items found in your bags.")
else
log("Added " .. added .. " item entries to the trade window")
end
module.activeTradeName = module.pendingName
module.tradeSucceeded = nil
module.pendingName = nil
module.pendingUnit = nil
module.pendingRequired = nil
module.pendingTradeItems = nil
module.pendingTradeIndex = nil
module.pendingTradeInitiated = nil
module.partnerOpenedTrade = nil
module.activeTradeMode = module.pendingMode
module.pendingMode = nil
end
--- Convert an item ID back into a display name for chat/log output.
-- Falls back to a generic "Item <id>" placeholder rather than erroring or returning nil,
-- so shortage/status messages remain readable even for an item missing from ITEM_NAMES_BY_ID.
-- @param itemID number item ID.
-- @return string display name.
local function itemName(itemID)
return ITEM_NAMES_BY_ID[itemID] or ("Item " .. itemID)
end
--- Parse a free-form "<class> <spec>" command tail into canonical class/spec keys.
-- Class names can be multiple words ("Death Knight"), so we try progressively shorter
-- prefixes of the token list as the candidate class name (longest first) and treat
-- whatever's left as the spec text. This greedy longest-match approach correctly handles
-- both single-word classes ("Druid Balance") and multi-word ones ("Death Knight Blood")
-- without needing a fixed class-name word count.
-- @param rawCommand string remaining command text after "sendaugs", e.g. "death knight blood".
-- @return string|nil classKey, string|nil specName; both nil if no valid combination is found.
local function parseClassAndSpec(rawCommand)
local tokens = {}
for token in (rawCommand or ""):gmatch("%S+") do
tokens[#tokens + 1] = token
end
if #tokens < 2 then return nil, nil end
for classCount = #tokens, 1, -1 do
local className = table.concat(tokens, " ", 1, classCount)
local classKey = classKeyForName(className)
if classKey then
local specText = table.concat(tokens, " ", classCount + 1, #tokens)
local specName = specNameForClass(classKey, specText)
if specName then
return classKey, specName
end
end
end
return nil, nil
end
--- Flatten a recommendation's enchants + gems into a single "itemID -> total quantity needed" map.
-- Used only for the gear-focused `/slack sendaugs` mail flow (not the chat-trade flow, which
-- has its own GetRequiredItems that also accounts for consumables and what's already equipped).
-- @param recommendationData table from buildBISEnhancementRecommendation.
-- @return table map of itemID -> required quantity.
local function buildRequiredForRecommendation(recommendationData)
local required = {}
local function add(itemID, quantity)
if itemID then
required[itemID] = (required[itemID] or 0) + (quantity or 1)
end
end
for _, enchantID in pairs(recommendationData.enchantIDs or {}) do
add(enchantID, 1)
end
for _, gem in ipairs(recommendationData.gemEntries or {}) do
add(gem.itemID, gem.quantity or 1)
end
return required
end
--- Compare a required-items map against current bag contents and report what's missing.
-- @param required table map of itemID -> required quantity.
-- @return table map of itemID -> missing quantity, containing only items that are short.
local function missingListForRequired(required)
local shortages = {}
for itemID, quantity in pairs(required) do
local missing = quantity - bagItemCount(itemID)
if missing > 0 then shortages[itemID] = missing end
end
return shortages
end
--- Produce a deterministic, alphabetically-sorted list of item IDs from a required-items map.
-- Sorting matters because mail attachment slots and trade slots are filled in list order;
-- without a stable sort, repeated runs (e.g. after a partial mail send) could attach items
-- in a different order and confuse the "which slot has what" mental model for the user.
-- @param required table map of itemID -> quantity.
-- @return table array of item IDs sorted by display name.
local function sortedItemIDs(required)
local itemIDs = {}
for itemID in pairs(required) do
itemIDs[#itemIDs + 1] = itemID
end
table.sort(itemIDs, function(left, right)
return itemName(left) < itemName(right)
end)
return itemIDs
end
--- Format a single required/missing item line for shopping-list style chat output.
-- @param itemID number item ID.
-- @param quantity number quantity needed; only shown when greater than 1 to avoid noisy "1x" prefixes.
-- @return string e.g. "- 5x Void-Touched Augment Rune" or "- Flask of the Magisters".
local function shoppingListItem(itemID, quantity)
local prefix = quantity > 1 and quantity .. "x " or ""
return "- " .. prefix .. itemName(itemID)
end
--- Check whether the mail compose window is currently open.
-- The `/slack sendaugs` flow attaches items to mail rather than trading directly, so every
-- attach attempt needs to confirm the frame is actually up before touching cursor/mail APIs.
-- @return boolean true if SendMailFrame exists and is shown.
local function mailFrameOpen()
return SendMailFrame and SendMailFrame:IsShown()
end
--- Move exactly `quantity` of an item from bags into a specific mail attachment slot.
-- Splits the stack first when the bag stack is larger than needed (so we don't over-mail),
-- otherwise picks up the whole matching stack directly. Every cursor operation is checked
-- with GetCursorInfo() because the pickup/split calls are fire-and-forget client requests;
-- if the cursor didn't pick anything up (e.g. bag changed, item moved), we bail out with
-- `false` rather than blindly clicking a mail slot with an empty cursor.
-- @param itemID number item to attach.
-- @param quantity number exact stack size to attach.
-- @param mailIndex number 1-based SendMailItem button index (mail supports up to 12).
-- @return boolean true if the item was successfully attached to that mail slot.
local function attachItemToMail(itemID, quantity, mailIndex)
local bag, slot = findBagItem(itemID, quantity)
if not bag or not slot then return false end
if GetCursorInfo() then ClearCursor() end
local info = C_Container.GetContainerItemInfo(bag, slot)
local stackCount = info and info.stackCount or 0
if stackCount > quantity then
C_Container.SplitContainerItem(bag, slot, quantity)
if not GetCursorInfo() then return false end
else
C_Container.PickupContainerItem(bag, slot)
if not GetCursorInfo() then return false end
end
local button = _G["SendMailItem" .. mailIndex]
if button then
ClickSendMailItemButton(mailIndex)
return true
end
return false
end
--- Add to (or initialize) an itemID's entry in a required-items accumulator map.
-- Small helper to avoid repeating the `required[id] = (required[id] or 0) + qty` idiom
-- across GetRequiredItems' several accumulation sites.
-- @param required table map of itemID -> quantity, mutated in place.
-- @param itemID number|nil item to add; a no-op if nil (keeps call sites branch-free).
-- @param quantity number|nil amount to add; defaults to 1.
local function addRequiredItem(required, itemID, quantity)
if itemID then required[itemID] = (required[itemID] or 0) + (quantity or 1) end
end
--- Check whether a unit currently has a matching buff active, by name substring or spell ID.
-- Iterates the HELPFUL aura list manually (up to 40 slots) rather than using a named-lookup
-- API because we need to match on a partial/lower-cased name (buff tooltip text can vary
-- slightly, e.g. rank suffixes) and, for oils, an exact spell ID is more reliable than name
-- matching since temporary weapon enchants don't always surface a clean aura name.
-- Used only for the CONSUMABLES mode, to decide whether an already-buffed target
-- still needs that particular consumable traded to them.
-- @param unit string|nil unit token to inspect; returns false immediately if nil (can't inspect,
-- e.g. no unit token available for the target of a manual request).
-- @param buffName string|table exact/partial buff name(s) to match against, case-insensitive.
-- @param auraSpellID number|nil optional exact spell ID to match (used for the Phoenix Oil check).
-- @return boolean true if a matching aura was found.
local function hasConsumableBuff(unit, buffName, auraSpellID)
if not unit then return false end
local buffNames = type(buffName) == "table" and buffName or { buffName }
for index = 1, 40 do
local auraData = C_UnitAuras.GetAuraDataByIndex(unit, index, "HELPFUL")
local name = auraData and auraData.name
if auraSpellID and auraData and auraData.spellId == auraSpellID then return true end
if name then
for _, expectedName in ipairs(buffNames) do
if name:lower():find(expectedName:lower(), 1, true) then return true end
end
end
end
return false
end
--- Handler for `/slack sendaugs <class> <spec> [source]` (and the Slackwise-only
-- `/slack sendaugs <character> <realm> [source]` override form). Mails BIS enchants/gems
-- for a class/spec (or a saved personal override) rather than trading them directly, since
-- this command is meant for prepping mail to alts/other players who aren't online/nearby to
-- trade with — unlike the chat-trade flow, which requires the recipient to be in range.
-- Gated to isSlackwise() because this is a personal bulk-mailing tool, not a general feature.
-- @param input string command text after "sendaugs", e.g. "shaman enhancement wowhead" or
-- "Charname Realmname" for a personal override lookup.
function module:SendAugsForClassSpec(input)
if not isSlackwise() then
prn("unknown command.")
return
end
local tokens = {}
for token in (input or ""):gmatch("%S+") do
tokens[#tokens + 1] = token
end
local sourceKey = enhancementSourceKey(tokens[#tokens])
if sourceKey then table.remove(tokens) end
sourceKey = sourceKey or DEFAULT_ENHANCEMENT_SOURCE
if isSlackwise() and #tokens == 2 then
local overrideKey = characterFullName(tokens[1], tokens[2])
local override, resolvedOverrideKey = enhancementOverrideForKey(overrideKey)
if override then
local recommendationData = buildBISEnhancementRecommendation(override)
local required = buildRequiredForRecommendation(recommendationData)
local shortages = missingListForRequired(required)
if not mailFrameOpen() then
prn("open the mail compose window first.")
for itemID, quantity in pairs(shortages) do print(shoppingListItem(itemID, quantity)) end
return
end
if next(shortages) then
prn("missing items for " .. resolvedOverrideKey .. ":")
for itemID, quantity in pairs(shortages) do print(shoppingListItem(itemID, quantity)) end
return
end
local orderedIDs = sortedItemIDs(required)
for mailIndex, itemID in ipairs(orderedIDs) do
if mailIndex > 12 or not attachItemToMail(itemID, required[itemID], mailIndex) then
prn("failed to attach items for " .. resolvedOverrideKey .. ".")
return
end
end
prn("BIS enchants and gems for " .. resolvedOverrideKey .. " have been added to the letter.")
return
end
end
local classKey, resolvedSpec = parseClassAndSpec(table.concat(tokens, " "))
if not classKey or not resolvedSpec then
prn("unknown class/spec for sendaugs: " .. strtrim(input or ""))
print("Usage: /slack sendaugs <class> <spec> [wowhead|icyveins|murlok]")
if isSlackwise() then prn("personal overrides use /slack sendaugs <character> <realm> [wowhead|icyveins|murlok]") end
return
end
local sourceData = ENHANCEMENTS_BIS and ENHANCEMENTS_BIS[sourceKey]
local classData = sourceData and sourceData[classKey]
local specData = classData and classData[resolvedSpec]
if not specData then
prn("no " .. displayEnhancementSource(sourceKey) .. " BIS data found for " .. displayClassName(classKey) .. " / " .. displaySpecName(resolvedSpec) .. ".")
return
end
local recommendationData = buildBISEnhancementRecommendation(specData, enhancementFlaskName(sourceKey, classKey, resolvedSpec))
local required = buildRequiredForRecommendation(recommendationData)
local shortages = missingListForRequired(required)
if not mailFrameOpen() then
prn("open the mail compose window first.")
if next(shortages) then
prn("buy these items from the auction house for " .. displayClassName(classKey) .. " / " .. displaySpecName(resolvedSpec) .. ":")
for itemID, quantity in pairs(shortages) do
print(shoppingListItem(itemID, quantity))
end
else
prn("you already have everything needed for " .. displayClassName(classKey) .. " / " .. displaySpecName(resolvedSpec) .. ".")
end
return
end
if next(shortages) then
prn("missing items for " .. displayClassName(classKey) .. " / " .. displaySpecName(resolvedSpec) .. ":")
for itemID, quantity in pairs(shortages) do
print(shoppingListItem(itemID, quantity))
end
prn("buy the missing items from the auction house, then reopen the mail compose window.")
return
end
local orderedIDs = sortedItemIDs(required)
local mailCount = 0
for _, itemID in ipairs(orderedIDs) do
if mailCount >= 12 then break end
local quantity = required[itemID]
local bag, slot = findBagItem(itemID, quantity)
if not bag or not slot then
prn("unable to find " .. itemName(itemID) .. " x" .. quantity .. " in your bags.")
return
end
local info = C_Container.GetContainerItemInfo(bag, slot)
local stackCount = info and info.stackCount or 0
if stackCount < quantity then
prn("not enough " .. itemName(itemID) .. " in a single stack for mail.")
return
end
if not attachItemToMail(itemID, quantity, mailCount + 1) then
prn("failed to attach " .. itemName(itemID) .. " x" .. quantity .. " to the mail.")
return
end
mailCount = mailCount + 1
end
prn("BIS enchants and gems for " .. displayClassName(classKey) .. " / " .. displaySpecName(resolvedSpec) .. " have been added to the letter.")
end
--- Toggle Self Vendor chat requests on/off (persisted setting + Ace3 Enable/Disable).
-- Delegates to AceAddon's Enable/Disable so OnEnable/OnDisable run their event
-- (un)registration side effects consistently, rather than duplicating that logic here. The module
-- stays enabled while Automatic Trade Response is on, since that works without chat requests.
-- @param enabled boolean whether Self Vendor chat requests should be accepted.
function module:SetEnabled(enabled)
db.profile.selfVendor.enabled = enabled
log("Self Vendor enabled state changed to " .. tostring(enabled))
if moduleShouldBeActive() then self:Enable() else self:Disable() end
end
--- Set the Automatic Trade Response mode, which auto-trades that mode's items to anyone who opens a
-- trade with us, regardless of which mode checkboxes are enabled.
-- @param mode number|nil Enum.SelfVendorMode value, or 0/nil to turn the feature Off.
-- @return boolean true if the mode was valid and applied.
function module:SetAutoTradeMode(mode)
mode = tonumber(mode) or 0
if mode ~= 0 then
mode = autoTradeModeFor(mode)
if not mode then return false end
end
db.profile.selfVendor.autoTradeMode = mode
log("Self Vendor Automatic Trade Response changed to " .. tostring(mode))
if moduleShouldBeActive() then self:Enable() else self:Disable() end
local registry = LibStub("AceConfigRegistry-3.0", true)
if registry then registry:NotifyChange("SlackHacks") end
return true
end
--- Enable or disable a single vendor mode (e.g. turn off Vantus Rune requests without
-- disabling Consumables). No-ops silently for an unknown mode so callers (options UI)
-- don't need to guard against invalid Enum values themselves.
-- @param mode number Enum.SelfVendorMode value.
-- @param enabled boolean whether this specific mode should respond to its trigger/command.
function module:SetModeEnabled(mode, enabled)
local configuration = modeConfiguration(mode)
if not configuration then return end
configuration.enabled = enabled
end
--- Set how many Augment Runes are traded as a single stack for the AUGMENT_RUNES mode.
-- Clamped to [1, 100] to keep the value sane for the options UI slider/input and to avoid
-- someone accidentally configuring an absurd or non-positive quantity that would then fail
-- every stack-preparation attempt.
-- @param value number|string requested rune quantity (string tolerated since options widgets
-- sometimes hand back text-box input).
function module:SetRuneQuantity(value)
local configuration = modeConfiguration(VendorMode.AUGMENT_RUNES)
if configuration then configuration.runeQuantity = math.max(1, math.min(100, tonumber(value) or 1)) end
end
--- Change which BIS data source (Wowhead/Icy Veins/Murlok M+) is used for gear/consumable
-- recommendations. Validates the key first so a bad/typo'd source never gets persisted,
-- which would otherwise silently break every subsequent recommendation lookup.
-- @param sourceKey string requested source key, any case.
-- @return boolean true if the source was valid and applied.
function module:SetSource(sourceKey)
sourceKey = enhancementSourceKey(sourceKey)
if not sourceKey then return false end
db.profile.selfVendor.source = sourceKey
log("Self Vendor source changed to " .. sourceKey)
return true
end
--- Stop vending to whoever is currently being vended to, without starting the next player.
-- Bumps `serviceToken` so in-flight bag prep, stack polling, and trade population callbacks for the
-- cancelled player stop, and closes any open trade window so it can't complete half-populated.
-- @param keepTradeOpen boolean|nil leave the trade window open (used when a different player opened
-- it with us and is about to be vended to through Automatic Trade Response).
-- @return string|nil name of the cancelled player, table|number|nil their request (Enum.SelfVendorMode value or set of values).
function module:CancelCurrentService(keepTradeOpen)
local name = self.activeTradeName or self.pendingName
if not name then return nil end
local mode = self.activeTradeName and self.activeTradeMode or self.pendingMode
self.serviceToken = (self.serviceToken or 0) + 1
if not keepTradeOpen and TradeFrame and TradeFrame:IsShown() then CloseTrade() end
-- Item prep may have left a split stack on the cursor; don't leave it there for the next player.
if GetCursorInfo() then ClearCursor() end
self.pendingName = nil
self.pendingUnit = nil
self.pendingMode = nil
self.pendingRequired = nil
self.pendingTradeItems = nil
self.pendingTradeIndex = nil
self.pendingTradeInitiated = nil
self.partnerOpenedTrade = nil
self.inspectGUID = nil
self.activeTradeName = nil
self.activeTradeMode = nil
self.tradeAccepted = nil
self.tradeSucceeded = nil
self.tradeCanceled = nil
self.tradeClosing = nil
log("Cancelled Self Vendor service for " .. name)
return name, mode
end
--- Clear the entire queue, including whoever is currently being vended to.
function module:ClearQueue()
local count = self.tradeQueue and #self.tradeQueue or 0
self.tradeQueue = {}
if self:CancelCurrentService() then count = count + 1 end
self:RefreshQueueWindow()
log("Self Vendor queue manually cleared; removed " .. count .. " entries")
prn("cleared " .. count .. " player(s) from the Self Vendor queue.")
end
--- Resolve typed slash command text into an Automatic Trade Response mode.
-- Accepts chat request aliases ("vantus", "flask") and SELF_VENDOR_MODES commands ("vantusrune"),
-- with spaces ignored so "vantus rune" works as well. Stat flask words ("crit flask") resolve to
-- the dynamic Flask mode, since specific flasks aren't offered for Automatic Trade Response.
-- @param text string lower-cased mode text.
-- @return number|nil matching Enum.SelfVendorMode value.
local function modeForSlashText(text)
local compact = text:gsub("%s+", "")
return autoTradeModeFor(chatRequestModes[compact] or modeForCommand(compact))
end
--- Print usage for the `/slack vend <mode>` slash command, including the current mode.
local function printVendSlashUsage()
local commands = {}
for _, details in pairs(SELF_VENDOR_MODES) do
if not details.flaskItemName then commands[#commands + 1] = details.command end
end
table.sort(commands)
local mode = autoTradeMode()
prn("Automatic Trade Response is " .. (mode and SELF_VENDOR_MODES[mode].name or "Off") .. ".")
print("Usage: /slack vend <off|" .. table.concat(commands, "|") .. ">")
end
--- Handle `/slack vend <mode>` (also routed from `vendor` and `trade`): set the Automatic Trade
-- Response mode. Also accepts `toggle` (chat requests on/off) and `clearqueue`.
-- @param input string text after the slash command word.
function module:HandleSlash(input)
local command = strlower(strtrim(input or ""))
if command == "" then
printVendSlashUsage()
elseif command == "off" or command == "none" or command == "0" then
self:SetAutoTradeMode(0)
prn("Automatic Trade Response: Off")
elseif command == "toggle" then
self:SetEnabled(not db.profile.selfVendor.enabled)
prn("Self Vendor: " .. (db.profile.selfVendor.enabled and "ON" or "OFF"))
elseif command == "clearqueue" then
self:ClearQueue()
else
local mode = modeForSlashText(command)
if mode then
self:SetAutoTradeMode(mode)
prn("Automatic Trade Response: " .. SELF_VENDOR_MODES[autoTradeModeFor(mode)].name)
else
prn("unknown Self Vendor mode '" .. command .. "'.")
printVendSlashUsage()
end
end
end
function module:OnInitialize()
if db.profile.selfVendor.source ~= "wowhead" and db.profile.selfVendor.source ~= "icyveins" then
db.profile.selfVendor.source = "icyveins"
end
log("Self Vendor initialized; enabled=" .. tostring(db.profile.selfVendor.enabled) .. ", autoTradeMode=" .. tostring(db.profile.selfVendor.autoTradeMode))
-- TRADE_SHOW fires for trades we open too; remember who we last opened one with so Automatic
-- Trade Response only answers trades other players open with us, not our own manual trades.
hooksecurefunc("InitiateTrade", function(unitOrName)
module.selfInitiatedTradeName = unitOrName and UnitName(unitOrName) or unitOrName
end)
if not moduleShouldBeActive() then self:Disable() end
end
function module:OnEnable()
log("Self Vendor enabled; registering events")
-- Chat events stay registered even when only Automatic Trade Response is on; ParseChatRequest
-- rejects them while chat requests are disabled.
self:RegisterEvent("CHAT_MSG_PARTY", "CHAT_MSG_GROUP")
self:RegisterEvent("CHAT_MSG_PARTY_LEADER", "CHAT_MSG_GROUP")
self:RegisterEvent("CHAT_MSG_RAID", "CHAT_MSG_GROUP")
self:RegisterEvent("CHAT_MSG_RAID_LEADER", "CHAT_MSG_GROUP")
self:RegisterEvent("CHAT_MSG_INSTANCE_CHAT", "CHAT_MSG_GROUP")
self:RegisterEvent("CHAT_MSG_INSTANCE_CHAT_LEADER", "CHAT_MSG_GROUP")
self:RegisterEvent("CHAT_MSG_SAY", "CHAT_MSG_GROUP")
self:RegisterEvent("CHAT_MSG_WHISPER", "CHAT_MSG_GROUP")
self:RegisterEvent("TRADE_SHOW")
self:RegisterEvent("INSPECT_READY")
self:RegisterEvent("UI_INFO_MESSAGE")
self:RegisterEvent("TRADE_ACCEPT_UPDATE")
self:RegisterEvent("TRADE_CLOSED")
self:RegisterEvent("TRADE_REQUEST_CANCEL")
self:RegisterEvent("GROUP_ROSTER_UPDATE")
self.wasInGroup = IsInGroup()
end
--- Turn Automatic Trade Response Off after leaving a group, when that option is enabled.
-- Tracks the previous group state because GROUP_ROSTER_UPDATE fires for every roster change, not
-- just for leaving.
function module:GROUP_ROSTER_UPDATE()
local inGroup = IsInGroup()
local leftGroup = self.wasInGroup and not inGroup
self.wasInGroup = inGroup
if not leftGroup or not db.profile.selfVendor.autoTradeOffAfterGroup or not autoTradeMode() then return end
log("Left group; turning Automatic Trade Response off")
prn("left group; Automatic Trade Response turned Off.")
self:SetAutoTradeMode(0)
end
function module:OnDisable()
log("Self Vendor disabled; unregistering events")
if self.queueFrame then self.queueFrame:Hide() end
self.pendingBagUpdate = nil
self.pendingMode = nil
self.pendingTradeInitiated = nil
self.partnerOpenedTrade = nil
self.activeTradeName = nil
self.activeTradeMode = nil
self.tradeAccepted = nil
self.tradeSucceeded = nil
self.tradeCanceled = nil
self.tradeClosing = nil
self.tradeQueue = {}
self:UnregisterAllEvents()
end
function module:PollPreparedStack(bag, slot, itemID, quantity, onSuccess, onFailure)
local delay = 0.1
local token = self.serviceToken
local function check()
if self.serviceToken ~= token or not self.pendingName then return end
local info = C_Container.GetContainerItemInfo(bag, slot)
local actualItemID = itemIDFromInfo(info)
local actualQuantity = info and info.stackCount or 0
log("Prepared stack poll: expectedItem=" .. itemID .. ", actualItem=" .. tostring(actualItemID) .. ", expectedQuantity=" .. quantity .. ", actualQuantity=" .. actualQuantity .. ", nextDelay=" .. delay)
if actualItemID == itemID and actualQuantity == quantity then
onSuccess()
return
end
if delay >= 3 then
log("Prepared stack did not reach the expected quantity after polling")
onFailure()
return
end
delay = math.min(delay + 0.1, 3)
C_Timer.After(delay, check)
end
C_Timer.After(delay, check)
end
function module:NotifyTradeUnavailable(name)
if not name then return end
SendChatMessage("You're too far away to trade with me. Move closer and I'll try again.", "WHISPER", nil, name)
-- TargetUnit is protected (hardware-event only); DoEmote accepts the name directly instead.
DoEmote("BECKON", name)
end
local TRADE_INTERACT_DISTANCE = 2
local function inTradeRange(unit)
return unit and CheckInteractDistance(unit, TRADE_INTERACT_DISTANCE)
end
function module:FailPendingTrade(message)
self:NotifyTradeUnavailable(self.pendingName)
log("Self Vendor failed: " .. message)
if message then prn(message) end
self.pendingName = nil
self.pendingUnit = nil
self.pendingRequired = nil
self.pendingTradeItems = nil
self.pendingTradeIndex = nil
self.pendingTradeInitiated = nil
self.inspectGUID = nil
self.pendingMode = nil
self:StartNextQueuedTrade()
end
function module:ReportMissingItems(shortages)
if self.pendingName then
DoEmote("SORRY", self.pendingName)
SendChatMessage("Sorry, I'm missing these items and need to restock:", "WHISPER", nil, self.pendingName)
for itemID, quantity in pairs(shortages) do
SendChatMessage(shoppingListItem(itemID, quantity), "WHISPER", nil, self.pendingName)
end
end
log("Self Vendor trade blocked because required items are missing")
self.pendingName = nil
self.pendingUnit = nil
self.pendingRequired = nil
self.pendingTradeItems = nil
self.pendingTradeIndex = nil
self.pendingTradeInitiated = nil
self.inspectGUID = nil
self.pendingMode = nil
self:StartNextQueuedTrade()
end