-
Notifications
You must be signed in to change notification settings - Fork 86
/
lootsheet-simple.js
1891 lines (1604 loc) · 58.2 KB
/
lootsheet-simple.js
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
class LootSheet5eNPCHelper {
/**
* Retrieve the loot permission for a player, given the current actor system.
*
* It first tries to get an entry from the actor's permissions, if none is found it uses default, otherwise returns 0.
*
*/
static getLootPermissionForPlayer(actorData, player) {
let defaultPermission = actorData.ownership.default
if (player.playerId in actorData.ownership) {
return actorData.ownership[player.playerId]
} else if (typeof defaultPermission !== 'undefined') {
return defaultPermission
} else {
return 0
}
}
/**
* Handles Currency from currency.TYPE.value to currency.TYPE for backwords support
* @param {string} folderPath - The directory to loop through
*/
static convertCurrencyFromObject(currency) {
Object.entries(currency).map(([key, value]) => {
currency[key] = value?.value ?? value ?? 0
})
return currency
}
}
class QuantityDialog extends Dialog {
constructor(callback, options) {
if (typeof options !== 'object') {
options = {}
}
let applyChanges = false
super({
title: game.i18n.localize('LOOTSHEET.QuantityWindow'),
content: `
<form>
<div class="form-group">
<label>${game.i18n.localize('LOOTSHEET.Quantity')}:</label>
<input type=number min="1" id="quantity" name="quantity" value="1">
</div>
</form>`,
buttons: {
yes: {
icon: "<i class='fas fa-check'></i>",
label: options.acceptLabel ? options.acceptLabel : 'Accept',
callback: () => (applyChanges = true),
},
no: {
icon: "<i class='fas fa-times'></i>",
label: 'Cancel',
},
},
default: 'yes',
close: () => {
if (applyChanges) {
var quantity = document.getElementById('quantity').value
if (isNaN(quantity)) {
// console.log("Loot Sheet | Item quantity invalid");
return ui.notifications.error(`Item quantity invalid.`)
}
callback(quantity)
}
},
})
}
}
class LootSheet5eNPC extends dnd5e.applications.actor.ActorSheet5eNPC2 {
static SOCKET = 'module.lootsheet-simple'
get template() {
// adding the #equals and #unequals handlebars helper
Handlebars.registerHelper('equals', function (arg1, arg2, options) {
return arg1 == arg2 ? options.fn(this) : options.inverse(this)
})
// Register the 'ifnot' helper
Handlebars.registerHelper('ifnot', function (condition, options) {
// Check if the condition is false, null, undefined, or falsy
if (!condition) {
return options.fn(this) // Render the block if the condition is falsy
} else {
return options.inverse(this) // Render the else block if the condition is true
}
})
Handlebars.registerHelper('unequals', function (arg1, arg2, options) {
return arg1 != arg2 ? options.fn(this) : options.inverse(this)
})
Handlebars.registerHelper('ifnoteq', function (a, b, options) {
if (a != b) {
return options.fn(this)
}
return options.inverse(this)
})
Handlebars.registerHelper('debug', function (context) {
console.log('lootsheet debug', context)
})
Handlebars.registerHelper('lootsheetprice', function (basePrice, modifier) {
return (Math.round(basePrice * modifier * 100) / 100).toLocaleString('en')
})
Handlebars.registerHelper('lootsheetstackweight', function (weight, qty) {
let showStackWeight = game.settings.get('lootsheet-simple', 'showStackWeight')
if (showStackWeight) {
return `/${(weight.value * qty).toLocaleString('en')}`
} else {
return ''
}
})
Handlebars.registerHelper('lootsheetweight', function (weight) {
return (Math.round(weight.value * 1e5) / 1e5).toString()
})
const path = 'systems/dnd5e/templates/actors/'
if (!game.user.isGM && this.actor.limited) return path + 'limited-sheet.hbs'
return 'modules/lootsheet-simple/template/npc-sheet.hbs'
}
static get defaultOptions() {
const options = super.defaultOptions
foundry.utils.mergeObject(options, {
classes: ['dnd5e2 sheet actor npc vertical-tabs loot-sheet-npc'],
width: 890,
height: 750,
})
return options
}
async getData() {
const sheetData = await super.getData()
// Prepare GM Settings
this._prepareGMSettings(sheetData.actor)
// Prepare isGM attribute in sheet Data
if (game.user.isGM) sheetData.isGM = true
else sheetData.isGM = false
let lootsheettype = await this.actor.getFlag('lootsheet-simple', 'lootsheettype')
if (!lootsheettype) await this.actor.setFlag('lootsheet-simple', 'lootsheettype', 'Loot')
lootsheettype = await this.actor.getFlag('lootsheet-simple', 'lootsheettype')
let priceModifier = 1.0
if (lootsheettype === 'Merchant') {
priceModifier = await this.actor.getFlag('lootsheet-simple', 'priceModifier')
if (typeof priceModifier !== 'number')
await this.actor.setFlag('lootsheet-simple', 'priceModifier', 1.0)
priceModifier = await this.actor.getFlag('lootsheet-simple', 'priceModifier')
}
let totalWeight = 0
this.actor.items.contents.forEach((item) => {
try {
let weight = Math.round((item.system.quantity * item.system.weight.value * 100) / 100)
totalWeight += isNaN(weight) ? 0 : weight
} catch (error) {
console.error('An error occurred while calculating weight:', error)
totalWeight += 0
}
})
if (game.settings.get('lootsheet-simple', 'includeCurrencyWeight')) {
let weight = (
Object.values(this.actor.system.currency).reduce(function (accumVariable, curValue) {
return accumVariable + curValue
}, 0) / 50
).toNearest(0.01)
totalWeight += isNaN(weight) ? 0 : weight
}
let totalPrice = 0
this.actor.items.contents.forEach((item) => {
if (item.system.price) {
let priceInGp = item.system.price.value
switch (item.system.price.denomination) {
case 'pp':
priceInGp = item.system.price.value * 10
break
case 'ep':
priceInGp = item.system.price.value / 5
break
case 'sp':
priceInGp = item.system.price.value / 10
break
case 'cp':
priceInGp = item.system.price.value / 100
break
default:
//this is gp, no conversion
break
}
totalPrice += Math.round((item.system.quantity * priceInGp * priceModifier * 100) / 100)
}
})
let totalQuantity = 0
this.actor.items.contents.forEach((item) => {
let addQuantity = Math.round((item.system.quantity * 100) / 100)
totalQuantity += isNaN(addQuantity) ? 0 : addQuantity
})
let selectedRollTable = await this.actor.getFlag('lootsheet-simple', 'rolltable')
let clearInventory = await this.actor.getFlag('lootsheet-simple', 'clearInventory')
let itemQty = await this.actor.getFlag('lootsheet-simple', 'itemQty')
let itemQtyLimit = await this.actor.getFlag('lootsheet-simple', 'itemQtyLimit')
let shopQty = await this.actor.getFlag('lootsheet-simple', 'shopQty')
sheetData.lootsheettype = lootsheettype
sheetData.selectedRollTable = selectedRollTable
sheetData.itemQty = itemQty
sheetData.itemQtyLimit = itemQtyLimit
sheetData.shopQty = shopQty
sheetData.clearInventory = clearInventory
sheetData.totalItems = this.actor.items.contents.length
sheetData.totalWeight = totalWeight.toLocaleString('en')
sheetData.totalPrice = totalPrice.toLocaleString('en')
sheetData.totalQuantity = totalQuantity
sheetData.priceModifier = priceModifier
sheetData.rolltables = game.tables.contents
// console.log(game.tables);
sheetData.lootCurrency = game.settings.get('lootsheet-simple', 'lootCurrency')
sheetData.lootAll = game.settings.get('lootsheet-simple', 'lootAll')
sheetData.system.currency = LootSheet5eNPCHelper.convertCurrencyFromObject(
sheetData.system.currency,
)
// console.log("sheetdata", sheetData);
// console.log("this actor", this.actor);
// Return data for rendering
return sheetData
}
/* -------------------------------------------- */
/* Event Listeners and Handlers
/* -------------------------------------------- */
/**
* Activate event listeners using the prepared sheet HTML
* @param html {HTML} The prepared HTML object ready to be rendered into the DOM
*/
activateListeners(html) {
super.activateListeners(html)
if (this.options.editable) {
// Toggle Permissions
html.find('.permission-proficiency').click((ev) => this._onCyclePermissionProficiency(ev))
html
.find('.permission-proficiency-bulk')
.click((ev) => this._onCyclePermissionProficiencyBulk(ev))
// Price Modifier
html.find('.price-modifier').click((ev) => this._priceModifier(ev))
html.find('.merchant-settings').change((ev) => this._merchantSettingChange(ev))
html.find('.update-inventory').click((ev) => this._merchantInventoryUpdate(ev))
html.find('.clear-inventory.slide-toggle').click((ev) => this._clearInventoryChange(ev))
const selectRollTable = document.getElementById('lootsheet-rolltable')
const buttonUpdateInventory = document.getElementById('update-inventory')
if (selectRollTable) {
buttonUpdateInventory.disabled = !selectRollTable.value
selectRollTable.addEventListener('change', function () {
// Enable the button only if the selected value is not blank
buttonUpdateInventory.disabled = !selectRollTable.value
})
}
}
// Split Coins
html
.find('.split-coins')
.removeAttr('disabled')
.click((ev) => this._distributeCoins(ev))
// Buy Item
html.find('.item-buy').click((ev) => this._buyItem(ev))
html.find('.item-buyall').click((ev) => this._buyItem(ev, 1))
// Loot Item
html.find('.item-loot').click((ev) => this._lootItem(ev))
html.find('.item-lootall').click((ev) => this._lootItem(ev, 1))
// Loot Currency
html
.find('.currency-loot')
.removeAttr('disabled')
.click((ev) => this._lootCoins(ev))
// Loot All
html
.find('.loot-all')
.removeAttr('disabled')
.click((ev) => this._lootAll(ev, html))
// Sheet Type
html.find('.sheet-type').change((ev) => this._changeSheetType(ev, html))
// Select the <nav> element and find all <a> elements inside it
const nav = $('.loot-sheet-npc nav.tabs')
const links = nav.find('a.item.control')
// Check if the first tab's data-tab attribute is not "features"
if (links.first().attr('data-tooltip') !== 'DND5E.Inventory') {
// Move the second <a> to the first position
if (links.eq(1).length) {
links.eq(1).insertBefore(links.eq(0)) // Move the second <a> before the first <a>
}
// Move the fifth <a> to the second position
if (links.eq(4).length) {
links.eq(4).insertAfter(nav.find('a.item.control').first()) // Move the fifth <a> to after the new first <a>
}
// Remove the remaining <a> elements (original first, third, and fourth)
nav.find('a.item.control').slice(2).remove() // Remove from the third onward
// Set the data-tab attribute to features
nav.find('a.item.control').first().attr('data-tab', 'features')
// Check if no <li> elements have the 'active' class
if (!nav.find('a.active').length) {
// Add the "active" class to the new first <a> element if no other <li> is active
nav.find('a.item.control').first().addClass('active')
}
}
// Roll Table
//html.find('.sheet-type').change(ev => this._changeSheetType(ev, html));
}
/* -------------------------------------------- */
/**
* Handle merchant settings change
* @private
*/
async _merchantSettingChange(event) {
event.preventDefault()
// console.log("Loot Sheet | Merchant settings changed");
const moduleNamespace = 'lootsheet-simple'
const expectedKeys = [
'rolltable',
'shopQty',
'itemQty',
'itemQtyLimit',
// 'clearInventory',
'itemOnlyOnce',
]
let targetKey = event.target.name.split('.')[3]
console.log(event)
if (expectedKeys.indexOf(targetKey) === -1) {
// console.log(`Loot Sheet | Error changing stettings for "${targetKey}".`);
return ui.notifications.error(`Error changing stettings for "${targetKey}".`)
}
if (targetKey == 'clearInventory' || targetKey == 'itemOnlyOnce') {
//console.log(targetKey + ' set to ' + event.target.checked)
await this.actor.setFlag(moduleNamespace, targetKey, event.target.checked)
} else if (event.target.value) {
//console.log(targetKey + ' set to ' + event.target.value)
await this.actor.setFlag(moduleNamespace, targetKey, event.target.value)
} else {
//console.log(targetKey + ' set to ' + event.target.value)
await this.actor.unsetFlag(moduleNamespace, targetKey, event.target.value)
}
}
/**
* Handle clear inventory settings change
* @private
*/
async _clearInventoryChange(event) {
// Prevent default behavior of label-click that directly interacts with the checkbox
event.preventDefault()
const clickedElement = $(event.currentTarget)
// Find the checkbox and icon within the label
const checkbox = clickedElement.find('input[type="checkbox"]')[0]
const icon = clickedElement.find('i')[0]
// Toggle the checkbox checked state
checkbox.checked = !checkbox.checked
// Update the icon class based on the checkbox state
if (checkbox.checked) {
icon.classList.remove('fa-toggle-off')
icon.classList.add('fa-toggle-on')
} else {
icon.classList.remove('fa-toggle-on')
icon.classList.add('fa-toggle-off')
}
// console.log("Loot Sheet | ClearInventory Changed");
await this.actor.setFlag('lootsheet-simple', 'clearInventory', checkbox.checked)
}
/* -------------------------------------------- */
/**
* Handle merchant inventory update
* @private
*/
async _merchantInventoryUpdate(event, html) {
event.preventDefault()
const moduleNamespace = 'lootsheet-simple'
const rolltableName = this.actor.getFlag(moduleNamespace, 'rolltable')
const shopQtyFormula = this.actor.getFlag(moduleNamespace, 'shopQty') || '1'
const itemQtyFormula = this.actor.getFlag(moduleNamespace, 'itemQty') || '1'
const itemQtyLimit = this.actor.getFlag(moduleNamespace, 'itemQtyLimit') || '0'
const clearInventory = this.actor.getFlag(moduleNamespace, 'clearInventory')
const itemOnlyOnce = this.actor.getFlag(moduleNamespace, 'itemOnlyOnce')
const reducedVerbosity = game.settings.get('lootsheet-simple', 'reduceUpdateVerbosity')
let shopQtyRoll = new Roll(shopQtyFormula)
await shopQtyRoll.evaluate()
// console.log("Adding ${shopQtyRoll.result} items.");
let rolltable = game.tables.getName(rolltableName)
if (!rolltable) {
return ui.notifications.error(`No Rollable Table found with name "${rolltableName}".`)
}
if (itemOnlyOnce) {
if (rolltable.results.length < shopQtyRoll.result) {
return ui.notifications.error(
`Cannot create a merchant with ${shopQtyRoll.result} unqiue entries if the rolltable only contains ${rolltable.results.length} items`,
)
}
}
if (clearInventory) {
let currentItems = this.actor.items.map((i) => i.id)
await this.actor.deleteEmbeddedDocuments('Item', currentItems)
}
// console.log(`Loot Sheet | Adding ${shopQtyRoll.result} new items`);
for (let i = 0; i < shopQtyRoll.result; i++) {
const rollResult = await rolltable.roll()
let itemToAdd = null
if (rollResult.results[0].documentCollection === 'Item') {
itemToAdd = game.items.get(rollResult.results[0].documentId)
} else {
// Try to find it in the compendium
const items = game.packs.get(rollResult.results[0].documentCollection)
itemToAdd = await items.getDocument(rollResult.results[0].documentId)
}
if (!itemToAdd || itemToAdd === null) {
return ui.notifications.error(`No item found "${rollResult.results[0].documentId}".`)
}
if (itemToAdd.type === 'spell') {
itemToAdd = await Item5e.createScrollFromSpell(itemToAdd)
}
let itemQtyRoll = new Roll(itemQtyFormula)
await itemQtyRoll.evaluate()
//console.log(itemQtyRoll.total);
// console.log(
// `Loot Sheet | Adding ${itemQtyRoll.total} x ${itemToAdd.name}`
// );
let existingItem = this.actor.items.find((item) => item.name == itemToAdd.name)
if (existingItem === undefined) {
// console.log(`Loot Sheet | ${itemToAdd.name} does not exist.`);
const createdItems = await this.actor.createEmbeddedDocuments('Item', [
itemToAdd.toObject(),
])
let newItem = createdItems[0]
if (itemQtyLimit > 0 && Number(itemQtyLimit) < Number(itemQtyRoll.total)) {
await newItem.update({
'system.quantity': itemQtyLimit,
})
if (!reducedVerbosity)
ui.notifications.info(`Added new ${itemQtyLimit} x ${itemToAdd.name}.`)
} else {
await newItem.update({
'system.quantity': itemQtyRoll.total,
})
if (!reducedVerbosity)
ui.notifications.info(`Added new ${itemQtyRoll.total} x ${itemToAdd.name}.`)
}
} else {
// console.log(
// `Loot Sheet | Item ${itemToAdd.name} exists.`,
// existingItem
// );
// console.log("existingqty", existingItem.system.quantity);
// console.log("toadd", itemQtyRoll.total);
let newQty = Number(existingItem.system.quantity) + Number(itemQtyRoll.total)
//console.log("newqty", newQty);
if (itemQtyLimit > 0 && Number(itemQtyLimit) === Number(existingItem.system.quantity)) {
if (!reducedVerbosity)
ui.notifications.info(
`${itemToAdd.name} already at maximum quantity (${itemQtyLimit}).`,
)
} else if (itemQtyLimit > 0 && Number(itemQtyLimit) < Number(newQty)) {
let updateItem = {
_id: existingItem.id,
data: {
quantity: itemQtyLimit,
},
}
await this.actor.updateEmbeddedDocuments('Item', [updateItem])
if (!reducedVerbosity)
ui.notifications.info(
`Added additional quantity to ${itemToAdd.name} to the specified maximum of ${itemQtyLimit}.`,
)
} else {
let updateItem = {
_id: existingItem.id,
system: {
quantity: newQty,
},
}
//console.log(updateItem);
await this.actor.updateEmbeddedDocuments('Item', [updateItem])
if (!reducedVerbosity)
ui.notifications.info(
`Added additional ${itemQtyRoll.total} quantity to ${existingItem.name}.`,
)
}
}
}
}
_createRollTable() {
let type = 'weapon'
game.packs.map((p) => p.collection)
const pack = game.packs.find((p) => p.collection === 'dnd5e.items')
let i = 0
let output = []
pack.getIndex().then((index) =>
index.forEach(function (arrayItem) {
var x = arrayItem._id
i++
pack.getEntity(arrayItem._id).then((packItem) => {
if (packItem.type === type) {
let newItem = {
_id: packItem._id,
flags: {},
type: 1,
text: packItem.name,
img: packItem.img,
collection: 'Item',
resultId: packItem._id,
weight: 1,
range: [i, i],
drawn: false,
}
output.push(newItem)
}
})
}),
)
return
}
/* -------------------------------------------- */
/**
* Handle sheet type change
* @private
*/
async _changeSheetType(event, html) {
event.preventDefault()
// console.log("Loot Sheet | Sheet Type changed", event);
let currentActor = this.actor
let selectedIndex = event.target.selectedIndex
let selectedItem = event.target[selectedIndex].value
await currentActor.setFlag('lootsheet-simple', 'lootsheettype', selectedItem)
}
/* -------------------------------------------- */
/**
* Handle buy item
* @private
*/
_buyItem(event, all = 0) {
event.preventDefault()
// console.log("Loot Sheet | Buy Item clicked");
let targetGm = null
game.users.forEach((u) => {
if (u.isGM && u.active && u.viewedScene === game.user.viewedScene) {
targetGm = u
}
})
if (!targetGm) {
return ui.notifications.error(
'No active GM on your scene, they must be online and on the same scene to purchase an item.',
)
}
if (this.token === null) {
return ui.notifications.error(`You must purchase items from a token.`)
}
// console.log(game.user.character);
if (!game.user.character) {
// console.log("Loot Sheet | No active character for user");
return ui.notifications.error(`No active character for user.`)
}
const itemId = $(event.currentTarget).parents('.item').attr('data-item-id')
const targetItem = this.actor.getEmbeddedDocument('Item', itemId)
const item = {
itemId: itemId,
quantity: 1,
}
const packet = {
type: 'buy',
buyerId: game.user.character._id,
tokenId: this.token.id,
itemId: itemId,
quantity: 1,
processorId: targetGm.id,
}
if (targetItem.system.quantity === item.quantity) {
console.log('LootSheet5e', 'Sending buy request to ' + targetGm.name, packet)
game.socket.emit(LootSheet5eNPC.SOCKET, packet)
return
}
if (all || event.shiftKey) {
const d = new QuantityDialog(
(quantity) => {
packet.quantity = quantity
console.log('LootSheet5e', 'Sending buy request to ' + targetGm.name, packet)
game.socket.emit(LootSheet5eNPC.SOCKET, packet)
},
{
acceptLabel: 'Purchase',
},
)
d.render(true)
} else {
game.socket.emit(LootSheet5eNPC.SOCKET, packet)
}
}
/* -------------------------------------------- */
/**
* Handle Loot item
* @private
*/
_lootItem(event, all = 0) {
event.preventDefault()
// console.log("Loot Sheet | Loot Item clicked");
let targetGm = null
game.users.forEach((u) => {
if (u.isGM && u.active && u.viewedScene === game.user.viewedScene) {
targetGm = u
}
})
if (!targetGm) {
return ui.notifications.error(
'No active GM on your scene, they must be online and on the same scene to purchase an item.',
)
}
if (this.token === null) {
return ui.notifications.error(`You must loot items from a token.`)
}
if (!game.user.character) {
// console.log("Loot Sheet | No active character for user");
return ui.notifications.error(`No active character for user.`)
}
const itemId = $(event.currentTarget).parents('.item').attr('data-item-id')
const targetItem = this.actor.getEmbeddedDocument('Item', itemId)
const item = {
itemId: itemId,
quantity: 1,
}
if (all || event.shiftKey) {
item.quantity = targetItem.system.quantity
}
const packet = {
type: 'loot',
looterId: game.user.character._id,
tokenId: this.token.id,
items: [item],
processorId: targetGm.id,
}
if (targetItem.system.quantity === item.quantity) {
console.log('LootSheet5e', 'Sending loot request to ' + targetGm.name, packet)
game.socket.emit(LootSheet5eNPC.SOCKET, packet)
return
}
const d = new QuantityDialog(
(quantity) => {
packet.items[0]['quantity'] = quantity
console.log('LootSheet5e', 'Sending loot request to ' + targetGm.name, packet)
game.socket.emit(LootSheet5eNPC.SOCKET, packet)
},
{
acceptLabel: 'Loot',
},
)
d.render(true)
}
/* -------------------------------------------- */
/**
* Handle Loot coins
* @private
*/
_lootCoins(event) {
event.preventDefault()
if (!game.settings.get('lootsheet-simple', 'lootCurrency')) {
return
}
// console.log("Loot Sheet | Loot Coins clicked");
let targetGm = null
game.users.forEach((u) => {
if (u.isGM && u.active && u.viewedScene === game.user.viewedScene) {
targetGm = u
}
})
if (!targetGm) {
return ui.notifications.error(
'No active GM on your scene, they must be online and on the same scene to loot coins.',
)
}
if (this.token === null) {
return ui.notifications.error(`You must loot coins from a token.`)
}
if (!game.user.character) {
// console.log("Loot Sheet | No active character for user");
return ui.notifications.error(`No active character for user.`)
}
const packet = {
type: 'lootCoins',
looterId: game.user.character._id,
tokenId: this.token.id,
processorId: targetGm.id,
}
console.log('LootSheet5e', 'Sending loot request to ' + targetGm.name, packet)
game.socket.emit(LootSheet5eNPC.SOCKET, packet)
}
/* -------------------------------------------- */
/**
* Handle Loot all
* @private
*/
_lootAll(event, html) {
event.preventDefault()
// console.log("Loot Sheet | Loot All clicked");
this._lootCoins(event)
let targetGm = null
game.users.forEach((u) => {
if (u.isGM && u.active && u.viewedScene === game.user.viewedScene) {
targetGm = u
}
})
if (!targetGm) {
return ui.notifications.error(
'No active GM on your scene, they must be online and on the same scene to purchase an item.',
)
}
if (this.token === null) {
return ui.notifications.error(`You must loot items from a token.`)
}
if (!game.user.character) {
// console.log("Loot Sheet | No active character for user");
return ui.notifications.error(`No active character for user.`)
}
const itemTargets = html.find('.item[data-item-id]')
if (!itemTargets) {
return
}
const items = []
for (let i of itemTargets) {
const itemId = i.getAttribute('data-item-id')
const item = this.actor.getEmbeddedDocument('Item', itemId)
items.push({
itemId: itemId,
quantity: item.system.quantity,
})
}
if (items.length === 0) {
return
}
const packet = {
type: 'loot',
looterId: game.user.character._id,
tokenId: this.token.id,
items: items,
processorId: targetGm.id,
}
console.log('LootSheet5e', 'Sending loot request to ' + targetGm.name, packet)
game.socket.emit(LootSheet5eNPC.SOCKET, packet)
}
/* -------------------------------------------- */
/**
* Handle price modifier
* @private
*/
async _priceModifier(event) {
event.preventDefault()
let priceModifier = await this.actor.getFlag('lootsheet-simple', 'priceModifier')
if (typeof priceModifier !== 'number') priceModifier = 1.0
priceModifier = Math.round(priceModifier * 100)
const maxModifier = game.settings.get('lootsheet-simple', 'maxPriceIncrease')
var html =
"<p>Use this slider to increase or decrease the price of all items in this inventory. <i class='fa fa-question-circle' title='This uses a percentage factor where 100% is the current price, 0% is 0, and 200% is double the price.'></i></p>"
html +=
'<p><input name="price-modifier-percent" id="price-modifier-percent" type="range" min="0" max="' +
maxModifier +
'" value="' +
priceModifier +
'" class="slider"></p>'
html +=
'<p><label>Percentage:</label> <input type=number min="0" max="' +
maxModifier +
'" value="' +
priceModifier +
'" id="price-modifier-percent-display"></p>'
html +=
'<script>var pmSlider = document.getElementById("price-modifier-percent"); var pmDisplay = document.getElementById("price-modifier-percent-display"); pmDisplay.value = pmSlider.value; pmSlider.oninput = function() { pmDisplay.value = this.value; }; pmDisplay.oninput = function() { pmSlider.value = this.value; };</script>'
let d = new Dialog({
title: 'Price Modifier',
content: html,
buttons: {
one: {
icon: '<i class="fas fa-check"></i>',
label: 'Update',
callback: () =>
this.actor.setFlag(
'lootsheet-simple',
'priceModifier',
document.getElementById('price-modifier-percent').value / 100,
),
},
two: {
icon: '<i class="fas fa-times"></i>',
label: 'Cancel',
callback: () => console.log('Loot Sheet | Price Modifier Cancelled'),
},
},
default: 'two',
close: () => console.log('Loot Sheet | Price Modifier Closed'),
})
d.render(true)
}
/* -------------------------------------------- */
/**
* Handle distribution of coins
* @private
*/
_distributeCoins(event) {
event.preventDefault()
let targetGm = null
game.users.forEach((u) => {
if (u.isGM && u.active && u.viewedScene === game.user.viewedScene) {
targetGm = u
}
})
if (!targetGm) {
return ui.notifications.error(
'No active GM on your scene, they must be online and on the same scene to purchase an item.',
)
}
if (this.token === null) {
return ui.notifications.error(`You must loot items from a token.`)
}
if (game.user.isGM) {
//don't use socket
let container = canvas.tokens.get(this.token.id)
this._hackydistributeCoins(container.actor)
return
}
const packet = {
type: 'distributeCoins',
looterId: game.user.character._id,
tokenId: this.token.id,
processorId: targetGm.id,
}
console.log('Loot Sheet | Sending distribute coins request to ' + targetGm.name, packet)
game.socket.emit(LootSheet5eNPC.SOCKET, packet)
}
_hackydistributeCoins(containerActor) {
//This is identical as the distributeCoins function defined in the init hook which for some reason can't be called from the above _distributeCoins method of the lootsheet-simple class. I couldn't be bothered to figure out why a socket can't be called as the GM... so this is a hack but it works.
let actorData = containerActor.system
let observers = []
let players = game.users.players
// Calculate observers
for (let player of players) {
let playerPermission = LootSheet5eNPCHelper.getLootPermissionForPlayer(actorData, player)
if (player != 'default' && playerPermission >= 2) {
let actor = game.actors.get(player.system.character)
if (actor != null && (player.system.role === 1 || player.system.role === 2))
observers.push(actor)
}
}
if (observers.length === 0) return
// Calculate split of currency
let currencySplit = foundry.utils.duplicate(
LootSheet5eNPCHelper.convertCurrencyFromObject(containerActor.system.currency),
)
// keep track of the remainder
let currencyRemainder = {}
for (let c in currencySplit) {
if (observers.length) {
// calculate remainder
currencyRemainder[c] = currencySplit[c] % observers.length
currencySplit[c] = Math.floor(currencySplit[c] / observers.length)
} else currencySplit[c] = 0
}
// add currency to actors existing coins
let msg = []
for (let u of observers) {