ticket.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. 'use strict';
  2. const { CrudService } = require('naf-framework-mongoose/lib/service');
  3. const { BusinessError, ErrorCode } = require('naf-core').Error;
  4. const _ = require('lodash');
  5. const assert = require('assert');
  6. const { ObjectId } = require('mongoose').Types;
  7. // 超市
  8. class TicketService extends CrudService {
  9. constructor(ctx) {
  10. super(ctx, 'ticket');
  11. this.model = this.ctx.model.Ticket;
  12. this.record = this.ctx.model.TicketRecord;
  13. }
  14. async query({ skip = 0, limit = 0, ...query } = {}) {
  15. const nquery = _.omit(query, [ 'name' ]);
  16. if (nquery.user_id) nquery.user_id = ObjectId(nquery.user_id);
  17. if (nquery.mechanism_id) nquery.mechanism_id = ObjectId(nquery.mechanism_id);
  18. const arr = [
  19. { $match: nquery },
  20. {
  21. $lookup: {
  22. from: 'organization',
  23. localField: 'user_id',
  24. foreignField: '_id',
  25. as: 'company',
  26. },
  27. },
  28. { $unwind: '$company' },
  29. { $addFields: { name: '$company.name' } },
  30. { $project: { _id: 1, name: 1, meta: 1, status: 1 } },
  31. ];
  32. if (_.get(query, 'name')) {
  33. arr.push({ $match: { name: new RegExp(_.get(query, 'name')) } });
  34. }
  35. let res = await this.model.aggregate(arr);
  36. const total = res.length;
  37. if (limit && limit !== '0') {
  38. res = _.slice(res, parseInt(skip), parseInt(limit));
  39. }
  40. return { data: res, total };
  41. }
  42. async fetch({ id }) {
  43. let res = await this.model.findById(id);
  44. if (!res) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到指定数据');
  45. res = JSON.parse(JSON.stringify(res));
  46. const { user_id } = res;
  47. if (user_id) {
  48. const company = await this.ctx.model.Organization.findById(user_id);
  49. if (company) res.name = company.name;
  50. }
  51. return res;
  52. }
  53. async status({ id }, body) {
  54. const { status } = body;
  55. await this.model.updateOne({ _id: id }, { status });
  56. // TODO,添加记录
  57. body.ticket_id = id;
  58. await this.record.create(body);
  59. }
  60. }
  61. module.exports = TicketService;