cardSearch.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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. // Use a more efficient query with limit and sort
  167. const selector = {
  168. type: 'cardType-card',
  169. dueAt: { $exists: true, $nin: [null, ''] }
  170. };
  171. const options = {
  172. sort: { dueAt: 1 }, // Sort by due date ascending (oldest first)
  173. limit: 100 // Limit to 100 cards for performance
  174. };
  175. const allCards = Cards.find(selector, options).fetch();
  176. if (process.env.DEBUG === 'true') {
  177. console.log('getResults - direct card search found:', allCards ? allCards.length : 0, 'cards');
  178. }
  179. if (allCards && allCards.length > 0) {
  180. allCards.forEach(card => {
  181. if (card && card._id) {
  182. cards.push(card);
  183. }
  184. });
  185. }
  186. this.queryErrors = [];
  187. }
  188. if (this.queryErrors.length) {
  189. // console.log('queryErrors:', this.queryErrorMessages());
  190. this.hasQueryErrors.set(true);
  191. // return null;
  192. }
  193. this.debug.set(new QueryDebug(this.sessionData ? this.sessionData.debug : null));
  194. if (process.env.DEBUG === 'true') {
  195. console.log('debug:', this.debug.get().get());
  196. console.log('debug.show():', this.debug.get().show());
  197. console.log('debug.showSelector():', this.debug.get().showSelector());
  198. }
  199. if (cards) {
  200. if (this.sessionData) {
  201. this.totalHits = this.sessionData.totalHits || 0;
  202. this.resultsCount = cards.length;
  203. this.resultsStart = this.sessionData.lastHit - this.resultsCount + 1;
  204. this.resultsEnd = this.sessionData.lastHit;
  205. this.resultsHeading.set(this.getResultsHeading());
  206. this.results.set(cards);
  207. this.hasNextPage.set(this.sessionData.lastHit < this.sessionData.totalHits);
  208. this.hasPreviousPage.set(
  209. this.sessionData.lastHit - this.sessionData.resultsCount > 0,
  210. );
  211. } else {
  212. this.totalHits = cards.length;
  213. this.resultsCount = cards.length;
  214. this.resultsStart = 1;
  215. this.resultsEnd = cards.length;
  216. this.resultsHeading.set(this.getResultsHeading());
  217. this.results.set(cards);
  218. this.hasNextPage.set(false);
  219. this.hasPreviousPage.set(false);
  220. }
  221. return cards;
  222. }
  223. this.resultsCount = 0;
  224. return null;
  225. }
  226. stopSubscription() {
  227. if (this.subscriptionHandle) {
  228. this.subscriptionHandle.stop();
  229. }
  230. }
  231. getSubscription(queryParams) {
  232. if (process.env.DEBUG === 'true') {
  233. console.log('Subscribing to globalSearch with:', {
  234. sessionId: this.sessionId,
  235. params: queryParams.params,
  236. text: queryParams.text
  237. });
  238. }
  239. // Subscribe to both globalSearch and sessionData
  240. const globalSearchHandle = Meteor.subscribe(
  241. 'globalSearch',
  242. this.sessionId,
  243. queryParams.params,
  244. queryParams.text,
  245. this.subscriptionCallbacks,
  246. );
  247. const sessionDataHandle = Meteor.subscribe('sessionData', this.sessionId);
  248. if (process.env.DEBUG === 'true') {
  249. console.log('Subscribed to sessionData with sessionId:', this.sessionId);
  250. }
  251. return globalSearchHandle;
  252. }
  253. runGlobalSearch(queryParams) {
  254. this.searching.set(true);
  255. this.debug.set(new QueryDebug());
  256. this.stopSubscription();
  257. this.subscriptionHandle = this.getSubscription(queryParams);
  258. }
  259. queryErrorMessages() {
  260. const messages = [];
  261. this.queryErrors.forEach(err => {
  262. let value = err.color ? TAPi18n.__(`color-${err.value}`) : err.value;
  263. if (!value) {
  264. value = err.value;
  265. }
  266. messages.push(TAPi18n.__(err.tag, value));
  267. });
  268. return messages;
  269. }
  270. nextPage() {
  271. this.searching.set(true);
  272. this.stopSubscription();
  273. this.subscriptionHandle = Meteor.subscribe(
  274. 'nextPage',
  275. this.sessionId,
  276. this.subscriptionCallbacks,
  277. );
  278. }
  279. previousPage() {
  280. this.searching.set(true);
  281. this.stopSubscription();
  282. this.subscriptionHandle = Meteor.subscribe(
  283. 'previousPage',
  284. this.sessionId,
  285. this.subscriptionCallbacks,
  286. );
  287. }
  288. getResultsHeading() {
  289. if (this.resultsCount === 0) {
  290. return TAPi18n.__('no-cards-found');
  291. } else if (this.resultsCount === 1) {
  292. return TAPi18n.__('one-card-found');
  293. } else if (this.resultsCount === this.totalHits) {
  294. return TAPi18n.__('n-cards-found', {sprintf: [this.resultsCount]});
  295. }
  296. return TAPi18n.__('n-n-of-n-cards-found', {
  297. start: this.resultsStart,
  298. end: this.resultsEnd,
  299. total: this.totalHits,
  300. });
  301. }
  302. getSearchHref() {
  303. const baseUrl = window.location.href.replace(/([?#].*$|\s*$)/, '');
  304. return `${baseUrl}?q=${encodeURIComponent(this.query.get())}`;
  305. }
  306. events() {
  307. return [
  308. {
  309. 'click .js-next-page'(evt) {
  310. evt.preventDefault();
  311. this.nextPage();
  312. },
  313. 'click .js-previous-page'(evt) {
  314. evt.preventDefault();
  315. this.previousPage();
  316. },
  317. },
  318. ];
  319. }
  320. }