-
Notifications
You must be signed in to change notification settings - Fork 0
/
Better Airline Club.user.js
2812 lines (2389 loc) · 119 KB
/
Better Airline Club.user.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
// ==UserScript==
// @name [BETA] BAC with H/T/D/T
// @namespace http://tampermonkey.net/
// @version 2.0.2
// @description Enhances airline-club.com and v2.airline-club.com airline management game (protip: Sign into your 2 accounts with one on each domain to avoid extra logout/login). Install this script with automatic updates by first installing TamperMonkey/ViolentMonkey/GreaseMonkey and installing it as a userscript.
// @author Aphix/Torus (original "Cost Per PAX" portion by Alrianne @ https://github.com/wolfnether/Airline_Club_Mod/)
// @match https://*.airline-club.com/
// @icon https://www.google.com/s2/favicons?domain=airline-club.com
// @downloadURL https://github.com/Bohaska/bac/raw/main/Better%20Airline%20Club.user.js
// @updateURL https://github.com/Bohaska/bac/raw/main/Better%20Airline%20Club.user.js
// @grant none
// ==/UserScript==
// ---- BEGIN of Section where user is expected to tweak things to make it how they like -------
var MIN_PLANES_TO_HIGHLIGHT = 500; // Changes which planes get the gold shadow/highlight on plane purchase table (not affected by filters in table header)
var REMOVE_MOVING_BACKGROUND = true; // perf enhancement, less noisy (gradients & transparency are still expensive in 2024, and my GPU has AI work to better spend it's time on)
var SOLID_BACKGROUND_COLOR = `rgb(83, 85, 113)`; // only matters if remove_moving_background is true
// Default filter values for plane purchase table header:
var DEFAULT_MIN_PLANES_IN_CIRCULATION_FILTER = 450; // Changes default minimum number of planes in circulation to remove from plane purchase table
var DEFAULT_MIN_FLIGHT_RANGE_FILTER = 1000;
var DEFAULT_RUNWAY_LENGTH_FILTER = 3000;
var DEFAULT_MIN_CAPACITY_FILTER = 0;
// ---- END of Section where user is expected to tweak things to make it how they like -------
// Plugin code starts here and goes to the end...
// Feel free to leave a comment on the gist if you have any questions or requests: https://gist.github.com/aphix/fdeeefbc4bef1ec580d72639bbc05f2d
// Want to donate? Don't. Buy yourself some ETH. If that works out nice and you want to pay it back later then find me on github.
// Note from Fly or die: I've released v2 of this mod. Thanks continentalysky for the commission!
function reportAjaxError(jqXHR, textStatus, errorThrown) {
console.error(JSON.stringify(jqXHR));
console.error("AJAX error: " + textStatus + ' : ' + errorThrown);
// throw errorThrown;
}
function _request(url, method = 'GET', data = undefined) {
return new Promise((resolve, reject) => {
$.ajax({
url,
type: method,
contentType: 'application/json; charset=utf-8',
data: data ? JSON.stringify(data) : data,
dataType: 'json',
success: resolve,
error: (...args) => {
reportAjaxError(...args);
reject(...args);
}
})
})
}
function getFactorPercent(consumption, subType) {
return (consumption.capacity[subType] > 0)
? parseInt(consumption.soldSeats[subType] / consumption.capacity[subType] * 100)
: null;
}
function getLoadFactorsFor(consumption) {
var factor = {};
for (let key in consumption.capacity) {
factor[key] = getFactorPercent(consumption, key) || '-';
}
return factor;
}
function _seekSubVal(val, ...subKeys) {
if (subKeys.length === 0) {
return val;
}
return _seekSubVal(val[subKeys[0]], ...subKeys.slice(1));
}
function averageFromSubKey(array, ...subKeys) {
return array.map(obj => _seekSubVal(obj, ...subKeys)).reduce((sum, val) => sum += (val || 0), 0) / array.length;
}
function _populateDerivedFieldsOnLink(link) {
link.totalCapacity = link.capacity.economy + link.capacity.business + link.capacity.first
link.totalCapacityHistory = link.capacityHistory.economy + link.capacityHistory.business + link.capacityHistory.first
link.totalPassengers = link.passengers.economy + link.passengers.business + link.passengers.first
link.totalLoadFactor = link.totalCapacityHistory > 0 ? Math.round(link.totalPassengers / link.totalCapacityHistory * 100) : 0
var assignedModel
if (link.assignedAirplanes && link.assignedAirplanes.length > 0) {
assignedModel = link.assignedAirplanes[0].airplane.name
} else {
assignedModel = "-"
}
link.model = assignedModel //so this can be sorted
link.profitMarginPercent = link.revenue === 0
? 0
: ((link.profit + link.revenue) / link.revenue) * 100;
link.profitMargin = link.profitMarginPercent > 100
? link.profitMarginPercent - 100
: (100 - link.profitMarginPercent) * -1;
link.profitPerPax = link.totalPassengers === 0
? 0
:link.profit / link.totalPassengers;
link.profitPerFlight = link.profit / link.frequency;
link.profitPerHour = link.profit / link.duration;
//console.dir(link);
}
function getAirportText(city, airportCode) {
if (city) {
return city + " (" + airportCode + ")"
} else {
return airportCode
}
}
function plotHistory(linkConsumptions) {
plotLinkCharts(linkConsumptions)
$("#linkHistoryDetails").show()
}
function getShortModelName(airplaneName) {
var sections = airplaneName.trim().split(' ').slice(1);
return sections
.map(str => (str.includes('-')
|| str.length < 4
|| /^[A-Z0-9\-]+[a-z]{0,4}$/.test(str))
? str
: str[0].toUpperCase())
.join(' ');
}
function getStyleFromTier(tier) {
const stylesFromGoodToBad = [
'color:#29FF66;',
'color:#5AB874;',
'color:inherit;',
'color:#FA8282;',
//'color:#FF3D3D;',
//'color:#B30E0E;text-shadow:0px 0px 2px #CCC;',
'color:#FF6969;',
'color:#FF3D3D;font-weight: bold;',
// 'color:#FF3D3D;text-decoration:underline',
];
return stylesFromGoodToBad[tier];
}
function getTierFromPercent(val, min = 0, max = 100) {
var availableRange = max - min;
var ranges = [
.95,
.80,
.75,
.6,
.5
].map(multiplier => (availableRange * multiplier) + min);
var tier;
if (val > ranges[0]) {
return 0;
} else if (val > ranges[1]) {
return 1;
} else if (val > ranges[2]) {
return 2;
} else if (val > ranges[3]) {
return 3;
} else if (val > ranges[4]) {
return 4;
}
return 5;
}
async function loadCompetitionForLink(airlineId, link) {
const linkConsumptions = await _request(`airports/${link.fromAirportId}/to/${link.toAirportId}`);
$("#linkCompetitons .data-row").remove()
$.each(linkConsumptions, function(index, linkConsumption) {
var row = $("<div class='table-row data-row'><div style='display: table-cell;'>" + linkConsumption.airlineName
+ "</div><div style='display: table-cell;'>" + toLinkClassValueString(linkConsumption.price, "$")
+ "</div><div style='display: table-cell; text-align: right;'>" + toLinkClassValueString(linkConsumption.capacity)
+ "</div><div style='display: table-cell; text-align: right;'>" + linkConsumption.quality
+ "</div><div style='display: table-cell; text-align: right;'>" + linkConsumption.frequency + "</div></div>")
if (linkConsumption.airlineId == airlineId) {
$("#linkCompetitons .table-header").after(row) //self is always on top
} else {
$("#linkCompetitons").append(row)
}
})
if ($("#linkCompetitons .data-row").length == 0) {
$("#linkCompetitons").append("<div class='table-row data-row'><div style='display: table-cell;'>-</div><div style='display: table-cell;'>-</div><div style='display: table-cell;'>-</div><div style='display: table-cell;'>-</div><div style='display: table-cell;'>-</div></div>")
}
$("#linkCompetitons").show()
assignAirlineColors(linkConsumptions, "airlineId")
plotPie(linkConsumptions, null, $("#linkCompetitionsPie"), "airlineName", "soldSeats")
return linkConsumptions;
}
function _isFullPax(link, key) {
return link.passengers[key] === link.capacity[key];
}
function _getPricesFor(link) {
var linkPrices = {};
for (var key in link.price) {
if (key === 'total') continue;
linkPrices[key] = link.price[key] - 5;
// linkPrices[key] = link.price[key] - (_isFullPax(link, key) ? 0 : 5);
}
return linkPrices;
}
async function _doAutomaticPriceUpdateFor(link) {
var priceUpdate = {
fromAirportId: link.fromAirportId,
toAirportId: link.toAirportId,
assignedDelegates: 0,
airplanes: {},
airlineId: link.assignedAirplanes[0].airplane.ownerId,
price: _getPricesFor(link),
model: link.assignedAirplanes[0].airplane.modelId,
rawQuality: link.rawQuality
}
for (var p of link.assignedAirplanes) {
if (!p.frequency) continue;
priceUpdate.airplanes[p.airplane.id] = p.frequency;
}
const updateResult = await _request(`/airlines/${priceUpdate.airlineId}/links`, 'PUT', priceUpdate);
}
//load history
async function loadHistoryForLink(airlineId, linkId, cycleCount, link) {
const linkHistory = await _request(`airlines/${airlineId}/link-consumptions/${linkId}?cycleCount=${cycleCount}`);
$('#linkEventChart').data('linkConsumptions', linkHistory)
if (jQuery.isEmptyObject(linkHistory)) {
$("#linkHistoryPrice").text("-")
$("#linkHistoryCapacity").text("-")
$("#linkLoadFactor").text("-")
$("#linkProfit").text("-")
$("#linkRevenue").text("-")
$("#linkFuelCost").text("-")
$("#linkCrewCost").text("-")
$("#linkAirportFees").text("-")
$("#linkDepreciation").text("-")
$("#linkCompensation").text("-")
$("#linkLoungeCost").text("-")
$("#linkServiceSupplies").text("-")
$("#linkMaintenance").text("-")
$("#linkOtherCosts").text("-")
$("#linkDelays").text("-")
$("#linkCancellations").text("-")
disableButton($("#linkDetails .button.viewLinkHistory"), "Passenger Map is not yet available for this route - please wait for the simulation (time estimation on top left of the screen).")
disableButton($("#linkDetails .button.viewLinkComposition"), "Passenger Survey is not yet available for this route - please wait for the simulation (time estimation on top left of the screen).")
plotHistory(linkHistory);
return;
}
if (!$("#linkAverageLoadFactor").length) {
$("#linkLoadFactor").parent().after(`<div class="table-row" style="color:#999">
<div class="label" style="color:#999"><h5>Avg. Load Factor:</h5></div>
<div class="value" id="linkAverageLoadFactor"></div>
</div>`)
}
if (!$("#linkAverageProfit").length) {
$("#linkProfit").parent().after(`<div class="table-row" style="color:#999">
<div class="label" style="color:#999"><h5>Avg. Profit:</h5></div>
<div class="value" id="linkAverageProfit"></div>
</div>`)
}
//if (!$("#doAutomaticPriceUpdate").length) {
// $("#linkLoadFactor").parent().after(`<div class="table-row" style="color:#999">
// <div class="button" id="doAutomaticPriceUpdate">Auto Manage</div>
// </div>`)
//}
const averageLoadFactor = getLoadFactorsFor({
soldSeats: {
economy: averageFromSubKey(linkHistory, 'soldSeats', 'economy'),
business: averageFromSubKey(linkHistory, 'soldSeats', 'business'),
first: averageFromSubKey(linkHistory, 'soldSeats', 'first'),
},
capacity: {
economy: averageFromSubKey(linkHistory, 'capacity', 'economy'),
business: averageFromSubKey(linkHistory, 'capacity', 'business'),
first: averageFromSubKey(linkHistory, 'capacity', 'first'),
}
});
var latestLinkData = linkHistory[0]
$("#linkHistoryPrice").text(toLinkClassValueString(latestLinkData.price, "$"))
$("#linkHistoryCapacity").text(toLinkClassValueString(latestLinkData.capacity))
if (latestLinkData.totalLoadFactor !== 100) {
let originalLink = link;
//console.dir(originalLink);
$("#doAutomaticPriceUpdate").click(() => {
_doAutomaticPriceUpdateFor(originalLink);
});
$("#doAutomaticPriceUpdate").show();
} else {
$("#doAutomaticPriceUpdate").hide();
}
$("#linkLoadFactor").text(toLinkClassValueString(getLoadFactorsFor(latestLinkData), "", "%"))
$("#linkAverageLoadFactor").text(toLinkClassValueString(averageLoadFactor, "", "%"))
const dollarValuesByElementId = {
linkProfit: latestLinkData.profit,
linkAverageProfit: Math.round(averageFromSubKey(linkHistory, 'profit')),
linkRevenue: latestLinkData.revenue,
linkFuelCost: latestLinkData.fuelCost,
linkCrewCost: latestLinkData.crewCost,
linkAirportFees: latestLinkData.airportFees,
linkDepreciation: latestLinkData.depreciation,
linkCompensation: latestLinkData.delayCompensation,
linkLoungeCost: latestLinkData.loungeCost,
linkServiceSupplies: latestLinkData.inflightCost,
linkMaintenance: latestLinkData.maintenanceCost,
};
for (const elementId in dollarValuesByElementId) {
$('#'+elementId).text('$' + commaSeparateNumber(dollarValuesByElementId[elementId]));
}
if (latestLinkData.minorDelayCount == 0 && latestLinkData.majorDelayCount == 0) {
$("#linkDelays").removeClass("warning")
$("#linkDelays").text("-")
} else {
$("#linkDelays").addClass("warning")
$("#linkDelays").text(latestLinkData.minorDelayCount + " minor " + latestLinkData.majorDelayCount + " major")
}
if (latestLinkData.cancellationCount == 0) {
$("#linkCancellations").removeClass("warning")
$("#linkCancellations").text("-")
} else {
$("#linkCancellations").addClass("warning")
$("#linkCancellations").text(latestLinkData.cancellationCount)
}
enableButton($("#linkDetails .button.viewLinkHistory"))
enableButton($("#linkDetails .button.viewLinkComposition"))
plotHistory(linkHistory);
return linkHistory;
}
async function loadLinkSurvey(airlineId, link) {
if (!$("#paxOrigin").length) {
$("#linkProfit").parent().before(`<div class="table-row">
<div class="label">
<h5>Origin (H/T/D/T):
<div class="tooltip">
<img src="/assets/images/icons/information.png">
<span class="tooltiptext below" style="white-space: nowrap;">H: Pax from home airport<br>T: Transit pax going through home airport<br>D: Pax from destination airport<br>T: Transit pax going through destination airport
<br></span>
</div>
</h5>
</div>
<div class="value" id="paxOrigin"></div>
</div>`);
};
if (!$("#paxType").length) {
$("#paxOrigin").parent().after(`<div class="table-row">
<div class="label">
<h5>Type (B/S/L):
<div class="tooltip">
<img src="/assets/images/icons/information.png">
<span class="tooltiptext below" style="white-space: nowrap;">B: Budget (and Simple) pax (Cares about price)<br>S: Swift pax (Cares about frequency)<br>L: Compehensive + Brand Aware + Elite pax (Cares about quality & loyalty)<br>L pax are 3x better at generating loyalists compared to B and S pax<br>Check the survey button for more info on pax types
<br></span>
</div>
</h5>
</div>
<div class="value" id="paxType"></div>
</div>`);
};
if (!$("#newLoyalists").length) {
$("#paxType").parent().after(`<div class="table-row">
<div class="label">
<h5>New Loyalists (B/S/L):
</h5>
<div class="tooltip">
<img src="/assets/images/icons/information.png">
<span class="tooltiptext below" style="white-space: nowrap;">The approximate amount of new loyalists your airline gains from this route<br>Assumes all pax on your route don't take transits, conversion rate is reduced for transit pax<br>Budget and Swift pax can only convert loyalists at 30% of regular rate
<br></span>
</div>
</div>
<div class="value" id="newLoyalists"></div>
</div>`);
};
$("#paxOrigin").text(``);
$("#paxType").text(``);
$("#newLoyalists").text(``);
const survey = await _request(`airlines/${airlineId}/link-composition/${link.id}`);
const passengerMap = await _request(`airlines/${airlineId}/related-link-consumption/${link.id}?cycleDelta=0&economy=true&business=true&first=true`);
var homeAirportPax = 0;
var destinationAirportPax = 0;
var homeTransitPax = 0;
var destinationTransitPax = 0;
var cheapPax = 0;
var swiftPax = 0;
var loyalistPax = 0;
var comprehensivePax = 0;
var brandConsciousPax = 0;
var elitePax = 0;
var simplePax = 0;
var budgetPax = 0;
var cheapNewLoyalists = 0;
var swiftNewLoyalists = 0;
var loyalNewLoyalists = 0;
for (var i = 0; i < survey.homeAirports.length; i++) {
if (survey.homeAirports[i].airport === `${link.fromAirportCity}(${link.fromAirportCode})`) {
homeAirportPax = survey.homeAirports[i].passengerCount;
} else {
if (survey.homeAirports[i].airport === `${link.toAirportCity}(${link.toAirportCode})`) {
destinationAirportPax = survey.homeAirports[i].passengerCount;
}
}
}
for (i = 0; i < passengerMap.relatedLinks.length; i++) {
if (passengerMap.relatedLinks[i][0].linkId === link.id) {
try {
for (var j = 0; j < passengerMap.relatedLinks[i-1].length; j++) {
homeTransitPax += passengerMap.relatedLinks[i-1][j].passenger
}
} catch (TypeError) {
homeTransitPax = 0
}
}
}
for (i = 0; i < passengerMap.invertedRelatedLinks.length; i++) {
if (passengerMap.invertedRelatedLinks[i][0].linkId === link.id) {
try {
for (j = 0; j < passengerMap.invertedRelatedLinks[i-1].length; j++) {
destinationTransitPax += passengerMap.invertedRelatedLinks[i-1][j].passenger
}
} catch (TypeError) {
destinationTransitPax = 0
}
}
}
for (i = 0; i < survey.preferenceType.length; i++) {
if (survey.preferenceType[i].title === "Budget") {
budgetPax += survey.preferenceType[i].passengerCount;
cheapPax += survey.preferenceType[i].passengerCount;
cheapNewLoyalists += parseInt(survey.preferenceType[i].passengerCount * 0.3 * Math.max((survey.preferenceSatisfaction[i].satisfaction - 0.6) * 2.5, 0));
} else {
if (survey.preferenceType[i].title === "Swift") {
swiftPax += survey.preferenceType[i].passengerCount;
swiftNewLoyalists += parseInt(survey.preferenceType[i].passengerCount * 0.3 * Math.max((survey.preferenceSatisfaction[i].satisfaction - 0.6) * 2.5, 0));
} else {
if (survey.preferenceType[i].title === "Comprehensive") {
comprehensivePax += survey.preferenceType[i].passengerCount;
loyalistPax += survey.preferenceType[i].passengerCount;
loyalNewLoyalists += parseInt(survey.preferenceType[i].passengerCount * Math.max((survey.preferenceSatisfaction[i].satisfaction - 0.6) * 2.5, 0));
} else {
if (survey.preferenceType[i].title === "Brand Conscious") {
brandConsciousPax += survey.preferenceType[i].passengerCount;
loyalistPax += survey.preferenceType[i].passengerCount;
loyalNewLoyalists += parseInt(survey.preferenceType[i].passengerCount * Math.max((survey.preferenceSatisfaction[i].satisfaction - 0.6) * 2.5, 0));
} else {
if (survey.preferenceType[i].title === "Elite") {
elitePax += survey.preferenceType[i].passengerCount;
loyalistPax += survey.preferenceType[i].passengerCount;
loyalNewLoyalists += parseInt(survey.preferenceType[i].passengerCount * Math.max((survey.preferenceSatisfaction[i].satisfaction - 0.6) * 2.5, 0));
} else {
if (survey.preferenceType[i].title === "Simple") {
simplePax += survey.preferenceType[i].passengerCount;
cheapPax += survey.preferenceType[i].passengerCount;
cheapNewLoyalists += parseInt(survey.preferenceType[i].passengerCount * 0.3 * Math.max((survey.preferenceSatisfaction[i].satisfaction - 0.6) * 2.5, 0));
}
}
}
}
}
}
}
$("#paxOrigin").text(`${homeAirportPax}/${homeTransitPax}/${destinationAirportPax}/${destinationTransitPax}`);
$("#paxType").text(`${cheapPax}/${swiftPax}/${loyalistPax}`);
$("#newLoyalists").text(`${cheapNewLoyalists}/${swiftNewLoyalists}/${loyalNewLoyalists}`);
}
let lastPlotUnit;
window._getPlotUnit = function _getPlotUnit() {
let checkedElem = $('#linkDetails fieldset .switch input:checked')[0];
if (!checkedElem && lastPlotUnit) {
return lastPlotUnit;
}
return lastPlotUnit = window.plotUnitEnum[checkedElem ? $(checkedElem).val().toUpperCase() : 'MONTH']
}
window.loadLink = async function loadLink(airlineId, linkId) {
const link = await _request(`airlines/${airlineId}/links/${linkId}`)
$('#linkEventModal').data('link', link)
$("#linkFromAirport").attr("onclick", "showAirportDetails(" + link.fromAirportId + ")").html(getCountryFlagImg(link.fromCountryCode) + getAirportText(link.fromAirportCity, link.fromAirportCode))
//$("#linkFromAirportExpectedQuality").attr("onclick", "loadLinkExpectedQuality(" + link.fromAirportId + "," + link.toAirportId + "," + link.fromAirportId + ")")
$("#linkToAirport").attr("onclick", "showAirportDetails(" + link.toAirportId + ")").html(getCountryFlagImg(link.toCountryCode) + getAirportText(link.toAirportCity, link.toAirportCode))
//$("#linkToAirportExpectedQuality").attr("onclick", "loadLinkExpectedQuality(" + link.fromAirportId + "," + link.toAirportId + "," + link.toAirportId + ")")
$("#linkFlightCode").text(link.flightCode)
if (link.assignedAirplanes && link.assignedAirplanes.length > 0) {
$('#linkAirplaneModel').text(link.assignedAirplanes[0].airplane.name + "(" + link.assignedAirplanes.length + ")")
} else {
$('#linkAirplaneModel').text("-")
}
$("#linkCurrentPrice").text(toLinkClassValueString(link.price, "$"))
$("#linkDistance").text(link.distance + " km (" + link.flightType + ")")
$("#linkQuality").html(getGradeStarsImgs(Math.round(link.computedQuality / 10)) + link.computedQuality)
$("#linkCurrentCapacity").text(toLinkClassValueString(link.capacity))
if (link.future) {
$("#linkCurrentDetails .future .capacity").text(toLinkClassValueString(link.future.capacity))
$("#linkCurrentDetails .future").show()
} else {
$("#linkCurrentDetails .future").hide()
}
$("#linkCurrentDetails").show()
$("#linkToAirportId").val(link.toAirportId)
$("#linkFromAirportId").val(link.fromAirportId)
const plotUnit = _getPlotUnit();
// const plotUnit = $("#linkDetails #switchMonth").is(':checked')
// ? window.plotUnitEnum.MONTH
// : $("#linkDetails #switchQuarter").is(':checked')
// ? window.plotUnitEnum.QUARTER
// : window.plotUnitEnum.YEAR;
const cycleCount = plotUnit.maxWeek;
const [
linkCompetition,
linkHistory,
linkSurvey,
] = await Promise.all([
loadCompetitionForLink(airlineId, link),
loadHistoryForLink(airlineId, linkId, cycleCount, link),
loadLinkSurvey(airlineId, link),
])
//populate airplane model drop down
var explicitlySelectedModelId = $("#planLinkModelSelect").data('explicitId')
$("#viewLinkModelSelect").children('option').remove()
//find which model is assigned to the existing link (if exist)
const assignedModelId = link.modelId
var selectedModelId
if (explicitlySelectedModelId) { //if there was a explicitly selected model, for example from buying a new plane
selectedModelId = explicitlySelectedModelId;
} else {
selectedModelId = assignedModelId
}
loadAirplaneModels();
const fromAirport = airports.find(airport => airport.id === link.fromAirportId)
const toAirport = airports.find(airport => airport.id === link.toAirportId)
const minRunway = Math.min(fromAirport.runwayLength, toAirport.runwayLength)
link.fromAirport = fromAirport
link.toAirport = toAirport
$("#detailsPanel").data(link)
var arrayModels = Object.values(loadedModelsById)
$.each(arrayModels, function(key, modelPlanLinkInfo) {
if (modelPlanLinkInfo.id == selectedModelId) {
modelPlanLinkInfo.owned = true
} else {
modelPlanLinkInfo.owned = false
}
})
arrayModels = sortPreserveOrder(arrayModels, "owned", false)
$("#viewLinkModelSelect").children('option').remove()
$.each(arrayModels, function(id, model) {
var modelId = model.id
var modelname = model.name
if (model.range >= link.distance && model.runwayRequirement <= minRunway) {
let flightDuration = calcFlightTime(model, link.distance) ;
let maxFlightMinutes = 4 * 24 * 60;
let frequency = Math.floor(maxFlightMinutes / ((flightDuration + model.turnaroundTime) * 2));
var option = $("<option></option>").attr("value", modelId).text(modelname + " (" + frequency + ")")
option.appendTo($("#viewLinkModelSelect"))
if (selectedModelId == modelId) {
option.prop("selected", true)
option.addClass("highlight-text")
linkUpdateModelInfo(modelId)
}
}
});
$("#viewLinkModelSelect").show()
setActiveDiv($("#extendedPanel #airplaneModelDetails"))
return {
link,
linkCompetition,
linkHistory,
linkSurvey,
};
}
const _editLink = window.editLink
window.editLink = function editLink(linkId) {
$("#viewLinkModelSelect").hide()
_editLink(linkId)
}
let originalShowSearchCanvas = window.showSearchCanvas
window.showSearchCanvas = function showSearchCanvas(historyAirline) {
return originalShowSearchCanvas(historyAirline)
}
window.researchFlight = function researchFlight(fromAirportId, toAirportId) {
if (fromAirportId && toAirportId) {
var url = "research-link/" + fromAirportId + "/" + toAirportId
$.ajax({
type: 'GET',
url: url,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(result) {
$("#searchCanvas").data(result);
var fromAirport = result.fromAirport
var toAirport = result.toAirport
var fromAirportId = fromAirport.id
var toAirportId = toAirport.id
loadAirportImage(fromAirportId, $('#researchSearchResult img.fromAirport') )
loadAirportImage(toAirportId, $('#researchSearchResult img.toAirport'))
$("#researchSearchResult .fromAirportText").text(result.fromAirportText)
$("#researchSearchResult .fromAirportText")[0].setAttribute("onclick", `showAirportDetails(${fromAirportId})`)
$("#researchSearchResult .fromAirport .population").text(commaSeparateNumber(result.fromAirport.population))
$("#researchSearchResult .fromAirport .incomeLevel").text(result.fromAirport.incomeLevel)
$("#researchSearchResult .toAirportText").text(result.toAirportText)
$("#researchSearchResult .toAirportText")[0].setAttribute("onclick", `showAirportDetails(${toAirportId})`)
populateNavigation($("#researchSearchResult"))
$("#researchSearchResult .toAirport .population").text(commaSeparateNumber(result.toAirport.population))
$("#researchSearchResult .toAirport .incomeLevel").text(result.toAirport.incomeLevel)
$("#researchSearchResult .relationship").html(getCountryFlagImg(result.fromAirport.countryCode) + " vs " + getCountryFlagImg(result.toAirport.countryCode) + getCountryRelationshipDescription(result.mutualRelationship))
$("#researchSearchResult .distance").text(result.distance)
$("#researchSearchResult .flightType").text(result.flightType)
$("#researchSearchResult .demand").text(toLinkClassValueString(result.directDemand))
var $breakdown = $("#researchSearchResult .directDemandBreakdown")
$breakdown.find(".fromAirport .airportLabel").empty()
$breakdown.find(".fromAirport .airportLabel").append(getAirportSpan(fromAirport))
$breakdown.find(".fromAirport .businessDemand").text(toLinkClassValueString(result.fromAirportBusinessDemand))
$breakdown.find(".fromAirport .touristDemand").text(toLinkClassValueString(result.fromAirportTouristDemand))
$breakdown.find(".toAirport .airportLabel").empty()
$breakdown.find(".toAirport .airportLabel").append(getAirportSpan(toAirport))
$breakdown.find(".toAirport .businessDemand").text(toLinkClassValueString(result.toAirportBusinessDemand))
$breakdown.find(".toAirport .touristDemand").text(toLinkClassValueString(result.toAirportTouristDemand))
$("#researchSearchResult .table.links .table-row").remove()
const usedModels = []
$.each(result.links, function(index, link) {
var $row = $("<div class='table-row'><div class='cell'>" + link.airlineName
+ "</div><div class='cell'>" + link.modelName
+ "</div><div class='cell'>" + toLinkClassValueString(link.price, "$")
+ "</div><div class='cell'>" + toLinkClassValueString(link.capacity)
+ "</div><div class='cell'>" + link.computedQuality
+ "</div><div class='cell'>" + link.frequency + "</div></div>")
$('#researchSearchResult .table.links').append($row)
usedModels.push(link.modelId)
})
var selectedModel = null
if (result.links.length == 0) {
var $row = $("<div class='table-row'><div class='cell'>-"
+ "</div><div class='cell'>-"
+ "</div><div class='cell'>-"
+ "</div><div class='cell'>-"
+ "</div><div class='cell'>-</div></div>")
$('#researchSearchResult .table.links').append($row)
} else {
selectedModel = result.links[0].modelId
}
assignAirlineColors(result.consumptions, "airlineId")
plotPie(result.consumptions, null, $("#researchSearchResult .linksPie"), "airlineName", "soldSeats")
$('#researchSearchResult').show()
const minRunway = Math.min(fromAirport.runwayLength, toAirport.runwayLength)
const distance = result.distance
loadAirplaneModels();
var arrayModels = Object.values(loadedModelsById)
$.each(arrayModels, function(key, modelPlanLinkInfo) {
if (usedModels.includes(modelPlanLinkInfo.id)) {
modelPlanLinkInfo.used = true
} else {
modelPlanLinkInfo.used = false
}
})
arrayModels = sortPreserveOrder(arrayModels, "used", false)
$("#researchFlightModelSelect").children('option').remove()
$.each(arrayModels, function(id, model) {
var modelId = model.id
var modelname = model.name
if (model.range >= distance && model.runwayRequirement <= minRunway) {
if (selectedModel === null) {
selectedModel = modelId
}
let flightDuration = calcFlightTime(model, distance) ;
let maxFlightMinutes = 4 * 24 * 60;
let frequency = Math.floor(maxFlightMinutes / ((flightDuration + model.turnaroundTime) * 2));
var option = $("<option></option>").attr("value", modelId).text(modelname + " (" + frequency + ")")
option.appendTo($("#researchFlightModelSelect"))
if (selectedModel == modelId) {
option.prop("selected", true)
researchUpdateModelInfo(modelId)
}
if (usedModels.includes(modelId)) {
option.addClass("highlight-text")
}
}
});
//plot consumptions
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
},
complete:function() {
//Hide the loader over here
input.parent().find(".spinner").hide()
currentSearchAjax = undefined
},
beforeSend: function() {
$('body .loadingSpinner').show()
},
complete: function(){
$('body .loadingSpinner').hide()
}
});
}
}
window.researchUpdateModelInfo = function researchUpdateModelInfo(modelId) {
let routeInfo = $("#searchCanvas").data()
let model = loadedModelsById[modelId]
$('#researchAirplaneModelDetails .selectedModel').val(modelId)
$('#researchAirplaneModelDetails #modelName').text(model.name)
$('#researchAirplaneModelDetails .modelFamily').text(model.family)
$('#researchAirplaneModelDetails #capacity').text(model.capacity)
$('#researchAirplaneModelDetails #airplaneType').text(model.airplaneType)
$('#researchAirplaneModelDetails .turnaroundTime').text(model.turnaroundTime)
$('#researchAirplaneModelDetails .runwayRequirement').text(model.runwayRequirement)
$('#researchAirplaneModelDetails #fuelBurn').text(model.fuelBurn)
$('#researchAirplaneModelDetails #range').text(model.range + "km")
$('#researchAirplaneModelDetails #speed').text(model.speed + "km/h")
$('#researchAirplaneModelDetails #lifespan').text(model.lifespan / 52 + " years")
var $manufacturerSpan = $('<span>' + model.manufacturer + ' </span>')
$manufacturerSpan.append(getCountryFlagImg(model.countryCode))
$('#researchAirplaneModelDetails .manufacturer').empty()
$('#researchAirplaneModelDetails .manufacturer').append($manufacturerSpan)
$('#researchAirplaneModelDetails .price').text("$" + commaSeparateNumber(model.price))
if (model.constructionTime == 0) {
$('#researchAirplaneModelDetails .delivery').text("immediate")
$('#researchAirplaneModelDetails .delivery').removeClass('warning')
$('#researchAirplaneModelDetails .add').text('Purchase')
} else {
$('#researchAirplaneModelDetails .delivery').text(model.constructionTime + " weeks")
$('#researchAirplaneModelDetails .delivery').addClass('warning')
$('#researchAirplaneModelDetails .add').text('Place Order')
}
if (model.rejection) {
disableButton($('#researchAirplaneModelDetails .add'), model.rejection)
} else {
enableButton($('#researchAirplaneModelDetails .add'))
}
let serviceLevel = 40;
let frequency = 0;
let plane_category = _getPlaneCategoryFor(model);
let baseSlotFee = 0;
let distance = routeInfo.distance
let airportFrom = routeInfo.fromAirport
let airportTo = routeInfo.toAirport
switch (airportFrom.size){
case 1 :
case 2 : baseSlotFee=50;break;
case 3 : baseSlotFee=80;break;
case 4 : baseSlotFee=150;break;
case 5 : baseSlotFee=250;break;
case 6 : baseSlotFee=350;break;
default: baseSlotFee=500;break;
}
switch (airportTo.size){
case 1 :
case 2 : baseSlotFee+=50;break;
case 3 : baseSlotFee+=80;break;
case 4 : baseSlotFee+=150;break;
case 5 : baseSlotFee+=250;break;
case 6 : baseSlotFee+=350;break;
default: baseSlotFee+=500;break;
}
let serviceLevelCost = 1;
switch (serviceLevel) {
case 2:serviceLevelCost=4;break;
case 3:serviceLevelCost=8;break;
case 4:serviceLevelCost=13;break;
case 5:serviceLevelCost=20;break;
}
let basic = 0;
let multiplyFactor = 2;
if (airportFrom.countryCode == airportTo.countryCode) {
if (distance <= 1000) {
basic = 8;
} else if (distance <= 3000) {
basic = 10;
} else {
basic = 12;
}
} else if (airportFrom.zone == airportTo.zone){
if (distance <= 2000) {
basic = 10;
} else if (distance <= 4000) {
basic = 15;
} else {
basic = 20;
}
} else {
if (distance <= 2000) {
basic = 15;
multiplyFactor = 3;
} else if (distance <= 5000) {
basic = 25;
multiplyFactor = 3;
} else if (distance <= 12000) {
basic = 30;
multiplyFactor = 4;
} else {
basic = 30;
multiplyFactor = 4;
}
}
let staffPerFrequency = multiplyFactor * 0.4;
let staffPer1000Pax = multiplyFactor;
let duration = calcFlightTime(model, distance)
let durationInHour = duration / 60;
let price = model.price;
if( model.originalPrice){
price = model.originalPrice;
}
let baseDecayRate = 100 / model.lifespan;
let maintenance = 0;
let depreciationRate = 0;
let maxFlightMinutes = 4 * 24 * 60;
frequency = Math.floor(maxFlightMinutes / ((duration + model.turnaroundTime)*2));
let flightTime = frequency * 2 * (duration + model.turnaroundTime);
let availableFlightMinutes = maxFlightMinutes - flightTime;
let utilisation = flightTime / (maxFlightMinutes - availableFlightMinutes);
let planeUtilisation = (maxFlightMinutes - availableFlightMinutes) / maxFlightMinutes;
let decayRate = 100 / (model.lifespan * 3) * (1 + 2 * planeUtilisation);
depreciationRate += Math.floor(price * (decayRate / 100) * utilisation);
maintenance += model.capacity * 100 * utilisation;
let fuelCost = frequency;
if (duration <= 90){
fuelCost *= model.fuelBurn * duration * 5.5 * 0.08;
}else{
fuelCost *= model.fuelBurn * (duration + 495) * 0.08;
}
let crewCost = model.capacity * durationInHour * 12 * frequency;
let airportFees = (baseSlotFee * plane_category + (Math.min(3, airportTo.size) + Math.min(3, airportFrom.size)) * model.capacity) * frequency;
let servicesCost = (20 + serviceLevelCost * durationInHour) * model.capacity * 2 * frequency;
let cost = fuelCost + crewCost + airportFees + depreciationRate + servicesCost + maintenance;
let staffTotal = Math.floor(basic + staffPerFrequency * frequency + staffPer1000Pax * model.capacity * frequency / 1000);
$('#researchAirplaneModelDetails #FCPF').text("$" + commaSeparateNumber(Math.floor(fuelCost)));
$('#researchAirplaneModelDetails #CCPF').text("$" + commaSeparateNumber(Math.floor(crewCost)));
$('#researchAirplaneModelDetails #AFPF').text("$" + commaSeparateNumber(airportFees));
$('#researchAirplaneModelDetails #depreciation').text("$" + commaSeparateNumber(Math.floor(depreciationRate)));
$('#researchAirplaneModelDetails #SSPF').text("$" + commaSeparateNumber(Math.floor(servicesCost)));
$('#researchAirplaneModelDetails #maintenance').text("$" + commaSeparateNumber(Math.floor(maintenance)));
$('#researchAirplaneModelDetails #cpp').text("$" + commaSeparateNumber(Math.floor(cost / (model.capacity * frequency))) + " * " + (model.capacity * frequency));
$('#researchAirplaneModelDetails #cps').text("$" + commaSeparateNumber(Math.floor(cost / staffTotal)) + " * " + staffTotal);
}
window.linkUpdateModelInfo = function linkUpdateModelInfo(modelId) {
let routeInfo = $("#detailsPanel").data()
let model = loadedModelsById[modelId]
$('#airplaneModelDetails .selectedModel').val(modelId)
$('#airplaneModelDetails #modelName').text(model.name)
$('#airplaneModelDetails .modelFamily').text(model.family)
$('#airplaneModelDetails #capacity').text(model.capacity)
$('#airplaneModelDetails #airplaneType').text(model.airplaneType)
$('#airplaneModelDetails .turnaroundTime').text(model.turnaroundTime)
$('#airplaneModelDetails .runwayRequirement').text(model.runwayRequirement)
$('#airplaneModelDetails #fuelBurn').text(model.fuelBurn)
$('#airplaneModelDetails #range').text(model.range + "km")
$('#airplaneModelDetails #speed').text(model.speed + "km/h")
$('#airplaneModelDetails #lifespan').text(model.lifespan / 52 + " years")
var $manufacturerSpan = $('<span>' + model.manufacturer + ' </span>')
$manufacturerSpan.append(getCountryFlagImg(model.countryCode))
$('#airplaneModelDetails .manufacturer').empty()
$('#airplaneModelDetails .manufacturer').append($manufacturerSpan)
$('#airplaneModelDetails .price').text("$" + commaSeparateNumber(model.price))
if (model.constructionTime == 0) {
$('#airplaneModelDetails .delivery').text("immediate")
$('#airplaneModelDetails .delivery').removeClass('warning')
$('#airplaneModelDetails .add').text('Purchase')
} else {
$('#airplaneModelDetails .delivery').text(model.constructionTime + " weeks")
$('#airplaneModelDetails .delivery').addClass('warning')
$('#airplaneModelDetails .add').text('Place Order')
}
if (model.rejection) {
disableButton($('#airplaneModelDetails .add'), model.rejection)
} else {
enableButton($('#airplaneModelDetails .add'))