habitica-self-host/website/common/script/ops/buy/buyQuestGem.js

63 lines
1.5 KiB
JavaScript
Raw Normal View History

2019-10-08 14:57:10 +00:00
import get from 'lodash/get';
import {
BadRequest,
NotAuthorized,
NotFound,
} from '../../libs/errors';
import content from '../../content/index';
import errorMessage from '../../libs/errorMessage';
2019-10-08 14:57:10 +00:00
import { AbstractGemItemOperation } from './abstractBuyOperation';
export class BuyQuestWithGemOperation extends AbstractGemItemOperation {
constructor (user, req, analytics) {
super(user, req, analytics);
}
multiplePurchaseAllowed () {
return true;
}
getItemKey () {
return this.key;
}
getItemValue (item) {
return item.value / 4;
}
getItemType () {
return 'quest';
}
extractAndValidateParams (user, req) {
2019-10-08 14:57:10 +00:00
const key = this.key = get(req, 'params.key');
if (!key) throw new BadRequest(errorMessage('missingKeyParam'));
2019-10-08 14:57:10 +00:00
const item = content.quests[key];
2019-10-08 14:57:10 +00:00
if (!item) throw new NotFound(errorMessage('questNotFound', { key }));
if (item.category === 'gold') {
2019-10-08 14:57:10 +00:00
throw new NotAuthorized(this.i18n('questNotGemPurchasable', { key }));
}
this.canUserPurchase(user, item);
}
executeChanges (user, item, req) {
if (!user.items.quests[item.key] || user.items.quests[item.key] < 0) user.items.quests[item.key] = 0;
user.items.quests[item.key] += this.quantity;
if (user.markModified) user.markModified('items.quests');
this.subtractCurrency(user, item, this.quantity);
return [
user.items.quests,
this.i18n('messageBought', {
itemText: item.text(req.language),
}),
];
}
}