Files
habitica/website/common/script/ops/buy/hourglassPurchase.js
Matteo Pagliazzi 0b8ce63c76 WIP: Improve User model performances (#10832)
* wip: define items as mixed objects

* add default owned gear

* mark modified

* more mark modified

* more mark modified

* more mark modified

* more mark modified

* fix common tests

* fix common tests

* update mongoose

* add itemsUtils

* use new util function in hall controller

* add tests for items utils

* update website/server to mark all items as modified

* start updating common code

* update login incentives

* update unlock

* remove changes to package-lock.json

* remove changes to package.json
2019-04-01 19:24:18 +02:00

63 lines
1.8 KiB
JavaScript

import content from '../../content/index';
import i18n from '../../i18n';
import get from 'lodash/get';
import includes from 'lodash/includes';
import keys from 'lodash/keys';
import {
BadRequest,
NotAuthorized,
} from '../../libs/errors';
import errorMessage from '../../libs/errorMessage';
module.exports = function purchaseHourglass (user, req = {}, analytics) {
let key = get(req, 'params.key');
if (!key) throw new BadRequest(errorMessage('missingKeyParam'));
let type = get(req, 'params.type');
if (!type) throw new BadRequest(errorMessage('missingTypeParam'));
if (!content.timeTravelStable[type]) {
throw new NotAuthorized(i18n.t('typeNotAllowedHourglass', {allowedTypes: keys(content.timeTravelStable).toString()}, req.language));
}
if (!includes(keys(content.timeTravelStable[type]), key)) {
throw new NotAuthorized(i18n.t('notAllowedHourglass', req.language));
}
if (user.items[type][key]) {
throw new NotAuthorized(i18n.t(`${type}AlreadyOwned`, req.language));
}
if (user.purchased.plan.consecutive.trinkets <= 0) {
throw new NotAuthorized(i18n.t('notEnoughHourglasses', req.language));
}
user.purchased.plan.consecutive.trinkets--;
if (type === 'pets') {
user.items.pets[key] = 5;
if (user.markModified) user.markModified('items.pets');
}
if (type === 'mounts') {
user.items.mounts[key] = true;
if (user.markModified) user.markModified('items.mounts');
}
if (analytics) {
analytics.track('acquire item', {
uuid: user._id,
itemKey: key,
itemType: type,
acquireMethod: 'Hourglass',
category: 'behavior',
headers: req.headers,
});
}
return [
{ items: user.items, purchasedPlanConsecutive: user.purchased.plan.consecutive },
i18n.t('hourglassPurchase', req.language),
];
};