cardSearch.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. import { ReactiveCache } from '/imports/reactiveCache';
  2. import { TAPi18n } from '/imports/i18n';
  3. import Cards from '../../models/cards';
  4. import SessionData from '../../models/usersessiondata';
  5. import {QueryDebug} from "../../config/query-classes";
  6. import {OPERATOR_DEBUG} from "../../config/search-const";
  7. export class CardSearchPagedComponent extends BlazeComponent {
  8. onCreated() {
  9. this.searching = new ReactiveVar(false);
  10. this.hasResults = new ReactiveVar(false);
  11. this.hasQueryErrors = new ReactiveVar(false);
  12. this.query = new ReactiveVar('');
  13. this.resultsHeading = new ReactiveVar('');
  14. this.searchLink = new ReactiveVar(null);
  15. this.results = new ReactiveVar([]);
  16. this.hasNextPage = new ReactiveVar(false);
  17. this.hasPreviousPage = new ReactiveVar(false);
  18. this.resultsCount = 0;
  19. this.totalHits = 0;
  20. this.queryErrors = null;
  21. this.resultsPerPage = 25;
  22. this.sessionId = SessionData.getSessionId();
  23. this.subscriptionHandle = null;
  24. this.serverError = new ReactiveVar(false);
  25. this.sessionData = null;
  26. this.debug = new ReactiveVar(new QueryDebug());
  27. const that = this;
  28. this.subscriptionCallbacks = {
  29. onReady() {
  30. if (process.env.DEBUG === 'true') {
  31. console.log('Subscription ready, getting results...');
  32. console.log('Subscription ready - sessionId:', that.sessionId);
  33. }
  34. // Wait for session data to be available (with timeout)
  35. let waitCount = 0;
  36. const maxWaitCount = 50; // 10 seconds max wait
  37. const waitForSessionData = () => {
  38. waitCount++;
  39. const sessionData = that.getSessionData();
  40. if (process.env.DEBUG === 'true') {
  41. console.log('waitForSessionData - attempt', waitCount, 'session data:', sessionData);
  42. }
  43. if (sessionData) {
  44. const results = that.getResults();
  45. if (process.env.DEBUG === 'true') {
  46. console.log('Search results count:', results ? results.length : 0);
  47. }
  48. // If no results and this is a due cards search, try to retry
  49. if ((!results || results.length === 0) && that.searchRetryCount !== undefined && that.searchRetryCount < that.maxRetries) {
  50. if (process.env.DEBUG === 'true') {
  51. console.log('No results found, retrying search...');
  52. }
  53. that.searchRetryCount++;
  54. Meteor.setTimeout(() => {
  55. if (that.performSearch) {
  56. that.performSearch();
  57. }
  58. }, 500);
  59. return;
  60. }
  61. that.searching.set(false);
  62. that.hasResults.set(true);
  63. that.serverError.set(false);
  64. } else if (waitCount < maxWaitCount) {
  65. // Session data not available yet, wait a bit more
  66. if (process.env.DEBUG === 'true') {
  67. console.log('Session data not available yet, waiting... (attempt', waitCount, 'of', maxWaitCount, ')');
  68. }
  69. Meteor.setTimeout(waitForSessionData, 200);
  70. } else {
  71. // Timeout reached, try fallback search
  72. if (process.env.DEBUG === 'true') {
  73. console.log('Timeout reached waiting for session data, trying fallback search');
  74. }
  75. const results = that.getResults();
  76. if (process.env.DEBUG === 'true') {
  77. console.log('Fallback search results count:', results ? results.length : 0);
  78. }
  79. if (results && results.length > 0) {
  80. that.searching.set(false);
  81. that.hasResults.set(true);
  82. that.serverError.set(false);
  83. } else {
  84. that.searching.set(false);
  85. that.hasResults.set(false);
  86. that.serverError.set(true);
  87. }
  88. }
  89. };
  90. // Start waiting for session data
  91. Meteor.setTimeout(waitForSessionData, 100);
  92. },
  93. onError(error) {
  94. if (process.env.DEBUG === 'true') {
  95. console.log('Subscription error:', error);
  96. console.log('Error.reason:', error.reason);
  97. console.log('Error.message:', error.message);
  98. console.log('Error.stack:', error.stack);
  99. }
  100. that.searching.set(false);
  101. that.hasResults.set(false);
  102. that.serverError.set(true);
  103. },
  104. };
  105. }
  106. resetSearch() {
  107. this.searching.set(false);
  108. this.results.set([]);
  109. this.hasResults.set(false);
  110. this.hasQueryErrors.set(false);
  111. this.resultsHeading.set('');
  112. this.serverError.set(false);
  113. this.resultsCount = 0;
  114. this.totalHits = 0;
  115. this.queryErrors = null;
  116. this.debug.set(new QueryDebug());
  117. }
  118. getSessionData(sessionId) {
  119. const sessionIdToUse = sessionId || SessionData.getSessionId();
  120. if (process.env.DEBUG === 'true') {
  121. console.log('getSessionData - looking for sessionId:', sessionIdToUse);
  122. }
  123. // Try using the raw SessionData collection instead of ReactiveCache
  124. const sessionData = SessionData.findOne({
  125. sessionId: sessionIdToUse,
  126. });
  127. if (process.env.DEBUG === 'true') {
  128. console.log('getSessionData - found session data (raw):', sessionData);
  129. }
  130. // Also try ReactiveCache for comparison
  131. const reactiveSessionData = ReactiveCache.getSessionData({
  132. sessionId: sessionIdToUse,
  133. });
  134. if (process.env.DEBUG === 'true') {
  135. console.log('getSessionData - found session data (reactive):', reactiveSessionData);
  136. }
  137. return sessionData || reactiveSessionData;
  138. }
  139. getResults() {
  140. // eslint-disable-next-line no-console
  141. // console.log('getting results');
  142. this.sessionData = this.getSessionData();
  143. // eslint-disable-next-line no-console
  144. if (process.env.DEBUG === 'true') {
  145. console.log('getResults - sessionId:', this.sessionId);
  146. console.log('getResults - session data:', this.sessionData);
  147. }
  148. const cards = [];
  149. if (this.sessionData && this.sessionData.cards) {
  150. if (process.env.DEBUG === 'true') {
  151. console.log('getResults - cards array length:', this.sessionData.cards.length);
  152. }
  153. this.sessionData.cards.forEach(cardId => {
  154. const card = ReactiveCache.getCard(cardId);
  155. if (process.env.DEBUG === 'true') {
  156. console.log('getResults - card:', cardId, card);
  157. }
  158. cards.push(card);
  159. });
  160. this.queryErrors = this.sessionData.errors || [];
  161. } else {
  162. if (process.env.DEBUG === 'true') {
  163. console.log('getResults - no sessionData or no cards array, trying direct card search');
  164. }
  165. // Fallback: try to get cards directly from the client-side collection
  166. const selector = {
  167. type: 'cardType-card',
  168. dueAt: { $exists: true, $nin: [null, ''] }
  169. };
  170. const allCards = Cards.find(selector).fetch();
  171. if (process.env.DEBUG === 'true') {
  172. console.log('getResults - direct card search found:', allCards ? allCards.length : 0, 'cards');
  173. }
  174. if (allCards && allCards.length > 0) {
  175. allCards.forEach(card => {
  176. if (card && card._id) {
  177. if (process.env.DEBUG === 'true') {
  178. console.log('getResults - direct card:', card._id, card.title);
  179. }
  180. cards.push(card);
  181. }
  182. });
  183. }
  184. this.queryErrors = [];
  185. }
  186. if (this.queryErrors.length) {
  187. // console.log('queryErrors:', this.queryErrorMessages());
  188. this.hasQueryErrors.set(true);
  189. // return null;
  190. }
  191. this.debug.set(new QueryDebug(this.sessionData ? this.sessionData.debug : null));
  192. if (process.env.DEBUG === 'true') {
  193. console.log('debug:', this.debug.get().get());
  194. console.log('debug.show():', this.debug.get().show());
  195. console.log('debug.showSelector():', this.debug.get().showSelector());
  196. }
  197. if (cards) {
  198. if (this.sessionData) {
  199. this.totalHits = this.sessionData.totalHits || 0;
  200. this.resultsCount = cards.length;
  201. this.resultsStart = this.sessionData.lastHit - this.resultsCount + 1;
  202. this.resultsEnd = this.sessionData.lastHit;
  203. this.resultsHeading.set(this.getResultsHeading());
  204. this.results.set(cards);
  205. this.hasNextPage.set(this.sessionData.lastHit < this.sessionData.totalHits);
  206. this.hasPreviousPage.set(
  207. this.sessionData.lastHit - this.sessionData.resultsCount > 0,
  208. );
  209. } else {
  210. this.totalHits = cards.length;
  211. this.resultsCount = cards.length;
  212. this.resultsStart = 1;
  213. this.resultsEnd = cards.length;
  214. this.resultsHeading.set(this.getResultsHeading());
  215. this.results.set(cards);
  216. this.hasNextPage.set(false);
  217. this.hasPreviousPage.set(false);
  218. }
  219. return cards;
  220. }
  221. this.resultsCount = 0;
  222. return null;
  223. }
  224. stopSubscription() {
  225. if (this.subscriptionHandle) {
  226. this.subscriptionHandle.stop();
  227. }
  228. }
  229. getSubscription(queryParams) {
  230. if (process.env.DEBUG === 'true') {
  231. console.log('Subscribing to globalSearch with:', {
  232. sessionId: this.sessionId,
  233. params: queryParams.params,
  234. text: queryParams.text
  235. });
  236. }
  237. // Subscribe to both globalSearch and sessionData
  238. const globalSearchHandle = Meteor.subscribe(
  239. 'globalSearch',
  240. this.sessionId,
  241. queryParams.params,
  242. queryParams.text,
  243. this.subscriptionCallbacks,
  244. );
  245. const sessionDataHandle = Meteor.subscribe('sessionData', this.sessionId);
  246. if (process.env.DEBUG === 'true') {
  247. console.log('Subscribed to sessionData with sessionId:', this.sessionId);
  248. }
  249. return globalSearchHandle;
  250. }
  251. runGlobalSearch(queryParams) {
  252. this.searching.set(true);
  253. this.debug.set(new QueryDebug());
  254. this.stopSubscription();
  255. this.subscriptionHandle = this.getSubscription(queryParams);
  256. }
  257. queryErrorMessages() {
  258. const messages = [];
  259. this.queryErrors.forEach(err => {
  260. let value = err.color ? TAPi18n.__(`color-${err.value}`) : err.value;
  261. if (!value) {
  262. value = err.value;
  263. }
  264. messages.push(TAPi18n.__(err.tag, value));
  265. });
  266. return messages;
  267. }
  268. nextPage() {
  269. this.searching.set(true);
  270. this.stopSubscription();
  271. this.subscriptionHandle = Meteor.subscribe(
  272. 'nextPage',
  273. this.sessionId,
  274. this.subscriptionCallbacks,
  275. );
  276. }
  277. previousPage() {
  278. this.searching.set(true);
  279. this.stopSubscription();
  280. this.subscriptionHandle = Meteor.subscribe(
  281. 'previousPage',
  282. this.sessionId,
  283. this.subscriptionCallbacks,
  284. );
  285. }
  286. getResultsHeading() {
  287. if (this.resultsCount === 0) {
  288. return TAPi18n.__('no-cards-found');
  289. } else if (this.resultsCount === 1) {
  290. return TAPi18n.__('one-card-found');
  291. } else if (this.resultsCount === this.totalHits) {
  292. return TAPi18n.__('n-cards-found', {sprintf: [this.resultsCount]});
  293. }
  294. return TAPi18n.__('n-n-of-n-cards-found', {
  295. start: this.resultsStart,
  296. end: this.resultsEnd,
  297. total: this.totalHits,
  298. });
  299. }
  300. getSearchHref() {
  301. const baseUrl = window.location.href.replace(/([?#].*$|\s*$)/, '');
  302. return `${baseUrl}?q=${encodeURIComponent(this.query.get())}`;
  303. }
  304. events() {
  305. return [
  306. {
  307. 'click .js-next-page'(evt) {
  308. evt.preventDefault();
  309. this.nextPage();
  310. },
  311. 'click .js-previous-page'(evt) {
  312. evt.preventDefault();
  313. this.previousPage();
  314. },
  315. },
  316. ];
  317. }
  318. }