habitica/common/script/ops/buyQuest.js

45 lines
1.2 KiB
JavaScript
Raw Normal View History

2016-03-07 22:02:42 +00:00
import i18n from '../i18n';
import content from '../content/index';
import {
BadRequest,
NotAuthorized,
NotFound,
} from '../libs/errors';
import _ from 'lodash';
module.exports = function buyQuest (user, req = {}, analytics) {
let key = _.get(req, 'params.key');
if (!key) throw new BadRequest(i18n.t('missingKeyParam', req.language));
let item = content.quests[key];
2016-03-20 12:33:34 +00:00
if (!item) throw new NotFound(i18n.t('questNotFound', {key}, req.language));
2016-03-07 22:02:42 +00:00
if (!(item.category === 'gold' && item.goldValue)) {
throw new NotAuthorized(i18n.t('questNotGoldPurchasable', {key}, req.language));
2016-03-07 22:02:42 +00:00
}
if (user.stats.gp < item.goldValue) {
throw new NotAuthorized(i18n.t('messageNotEnoughGold', req.language));
2016-03-07 22:02:42 +00:00
}
user.items.quests[item.key] = user.items.quests[item.key] || 0;
user.items.quests[item.key]++;
2016-03-07 22:02:42 +00:00
user.stats.gp -= item.goldValue;
if (analytics) {
analytics.track('acquire item', {
uuid: user._id,
itemKey: item.key,
itemType: 'Market',
goldCost: item.goldValue,
acquireMethod: 'Gold',
category: 'behavior',
});
2016-03-07 22:02:42 +00:00
}
return {
data: user.items.quests,
message: i18n.t('messageBought', {
itemText: item.text(req.language),
}, req.language),
};
2016-03-07 22:02:42 +00:00
};