Mike Gerwitz

Activist for User Freedom

aboutsummaryrefslogtreecommitdiffstats
blob: 3bc72c0309fdfd66a64f83316c8bceb91a8c79df (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
/**
 * Tests RatingService
 *
 *  Copyright (C) 2010-2019 R-T Specialty, LLC.
 *
 *  This file is part of the Liza Data Collection Framework.
 *
 *  liza is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import {
    RatingService as Sut,
    RateRequestResult
} from "../../../src/server/service/RatingService";

import { ClientActions } from "../../../src/client/action/ClientAction";
import { PriorityLog } from "../../../src/server/log/PriorityLog";
import { ProcessManager } from "../../../src/server/rater/ProcessManager";
import { Program } from "../../../src/program/Program";
import { QuoteId } from "../../../src/quote/Quote";
import { Rater, RateResult } from "../../../src/server/rater/Rater";
import { Server } from "../../../src/server/Server";
import { ServerSideQuote } from "../../../src/server/quote/ServerSideQuote";
import { UserRequest } from "../../../src/server/request/UserRequest";
import { UserResponse } from "../../../src/server/request/UserResponse";
import { UserSession } from "../../../src/server/request/UserSession";
import { QuoteDataBucket } from "../../../src/bucket/QuoteDataBucket";

import {
    ServerDao,
    Callback as ServerDaoCallback
} from "../../../src/server/db/ServerDao";

import { expect, use as chai_use } from 'chai';
chai_use( require( 'chai-as-promised' ) );


describe( 'RatingService', () =>
{
    it( "returns rating results", () =>
    {
        const {
            logger,
            server,
            raters,
            dao,
            request,
            response,
            quote,
            stub_rate_data,
        } = getStubs();

        const sut = new Sut( logger, dao, server, raters );

        const expected = {
            data:             stub_rate_data,
            initialRatedDate: quote.getRatedDate(),
            lastRatedDate:    quote.getLastPremiumDate(),
        };

        return expect( sut.request( request, response, quote, "" ) )
            .to.eventually.deep.equal( expected );
    } );


    it( "updates rating dates before serving to client", () =>
    {
        const {
            logger,
            server,
            raters,
            dao,
            request,
            response,
            quote,
            stub_rate_data,
        } = getStubs();

        const sut = new Sut( logger, dao, server, raters );

        let last_prem_called  = false;
        let rated_date_called = false;

        let stub_last_prem_ts  = <UnixTimestamp>12345;
        let stub_rated_date_ts = <UnixTimestamp>23456;

        let sent = false;

        quote.setLastPremiumDate = () =>
        {
            last_prem_called = true;
            return quote;
        };

        quote.setRatedDate = () =>
        {
            rated_date_called = true;
            return quote;
        };

        quote.getLastPremiumDate = () => stub_last_prem_ts;
        quote.getRatedDate       = () => stub_rated_date_ts;

        server.sendResponse = (
            _request: any,
            _quote:   any,
            resp:     RateRequestResult,
            _actions: ClientActions
        ) =>
        {
            expect( resp.initialRatedDate ).to.equal( stub_rated_date_ts );
            expect( resp.lastRatedDate ).to.equal( stub_last_prem_ts );

            expect( last_prem_called ).to.be.true;
            expect( rated_date_called ).to.be.true;

            sent = true;

            return server;
        };

        const expected = {
            data:             stub_rate_data,
            initialRatedDate: stub_rated_date_ts,
            lastRatedDate:    stub_last_prem_ts,
        };

        return expect( sut.request( request, response, quote, "" ) )
            .to.eventually.deep.equal( expected )
            .then( () => expect( sent ).to.be.true );
    } );

    it( "saves rate data to it's own field", () =>
    {
        const {
            logger,
            server,
            raters,
            dao,
            request,
            response,
            quote,
            stub_rate_data,
        } = getStubs();

        let saved_rates = false;

        dao.saveQuote = (
            quote:     ServerSideQuote,
            success:   ServerDaoCallback,
            _failure:  ServerDaoCallback,
            save_data: Record<string, any>,
        ) =>
        {
            expect( save_data ).to.deep.equal( {
                ratedata: stub_rate_data,
            } );

            saved_rates = true;
            success( quote );

            return dao;
        };

        const sut = new Sut( logger, dao, server, raters );

        return sut.request( request, response, quote, "" )
            .then( () =>
            {
                expect( saved_rates ).to.be.true;
            } );
    } );


    it( "rejects and responds with error", () =>
    {
        const {
            dao,
            logger,
            program,
            quote,
            rater,
            raters,
            request,
            response,
            server,
        } = getStubs();

        const expected_error = new Error( "expected error" );

        rater.rate = () => { throw expected_error; };

        const sut = new Sut( logger, dao, server, raters );

        let logged = false;

        logger.log = function(
            priority:   number,
            _format:    string,
            qid:        QuoteId,
            program_id: string,
            message:    string,
        )
        {
            if ( typeof message === 'string' )
            {
                expect( priority ).to.equal( logger.PRIORITY_ERROR );
                expect( qid ).to.equal( quote.getId() );
                expect( program_id ).to.equal( program.getId() );
                expect( message ).to.contain( expected_error.message );

                logged = true;
            }

            return logger;
        };

        return expect( sut.request( request, response, quote, "" ) )
            .to.eventually.rejectedWith( expected_error )
            .then( () => expect( logged ).to.be.true );
    } );


    it( "returns error message from rater", () =>
    {
        const {
            dao,
            logger,
            quote,
            rater,
            raters,
            request,
            response,
            server,
        } = getStubs();

        const expected_message = 'expected foo';

        const sut = new Sut( logger, dao, server, raters );

        rater.rate = (
            _quote:   ServerSideQuote,
            _session: UserSession,
            _indv:    string,
            _success: ( data: RateResult, actions: ClientActions ) => void,
            failure:  ( message: string ) => void,
        ) =>
        {
            failure( expected_message );
            return rater;
        };

        return expect( sut.request( request, response, quote, "" ) )
            .to.eventually.rejectedWith( Error, expected_message );
    } );


    // this means of deferred rating is deprecated and is being superceded
    // in the near future by a better system; it will hopefully be removed
    // at some point
    it( "sends indvRate action for old-style deferred suppliers", () =>
    {
        const {
            dao,
            logger,
            quote,
            raters,
            request,
            response,
            server,
            stub_rate_data,
        } = getStubs();

        let sent = false;

        stub_rate_data._cmpdata = {
            deferred: [ 'supp1', 'supp2' ],
        };

        server.sendResponse = (
            _request: any,
            _quote: any,
            _resp: any,
            actions: ClientActions
        ) =>
        {
            expect( actions ).to.deep.equal( [
                { action: 'indvRate', id: 'supp1' },
                { action: 'indvRate', id: 'supp2' },
            ] );

            sent = true;

            return server;
        };

        const sut = new Sut( logger, dao, server, raters );

        return sut.request( request, response, quote, "" )
            .then( () => expect( sent ).to.be.true );
    } );


    describe( "protected API", () =>
    {
        it( "calls #postProcessRaterData after rating before save", done =>
        {
            let processed = false;

            const {
                logger,
                server,
                raters,
                dao,
                request,
                response,
                quote,
            } = getStubs();

            dao.mergeBucket = () =>
            {
                expect( processed ).to.equal( true );
                done();

                return dao;
            };

            const sut = new class extends Sut
            {
                postProcessRaterData()
                {
                    processed = true;
                }
            }( logger, dao, server, raters );

            sut.request( request, response, quote, 'something' );
        } );

        it( "calls getLastPremiumDate during #_performRating", done =>
        {
            let getLastPremiumDateCallCount = 0;

            const last_date    = <UnixTimestamp>1234;
            const initial_date = <UnixTimestamp>2345;

            const {
                logger,
                server,
                raters,
                dao,
                request,
                response,
                quote,
            } = getStubs();

            quote.getLastPremiumDate = () =>
            {
                getLastPremiumDateCallCount++;
                return last_date
            };

            quote.getRatedDate = () => initial_date;

            const sut = new Sut( logger, dao, server, raters );

            server.sendResponse = ( _request: any, _quote: any, resp: any, _actions: any ) =>
            {
                expect( getLastPremiumDateCallCount ).to.equal( 2 );
                expect( resp.initialRatedDate ).to.equal( initial_date );
                expect( resp.lastRatedDate ).to.equal( last_date );

                done();

                return server;
            };

            sut.request( request, response, quote, "" );
        } );
    } );
} );


function getStubs()
{
    const program_id = 'foo';

    const program = <Program>{
        getId:               () => program_id,
        ineligibleLockCount: 0,
    };

    // rate reply
    const stub_rate_data: RateResult = {
        _unavailable_all: '0',
    };

    const rater = new class implements Rater
    {
        rate(
            _quote:   ServerSideQuote,
            _session: UserSession,
            _indv:    string,
            success:  ( data: RateResult, actions: ClientActions ) => void,
            _failure: ( message: string ) => void,
        )
        {
            // force to be async so that the tests resemble how the code
            // actually runs
            process.nextTick( () => success( stub_rate_data, [] ) );

            return this;
        }
    };

    const raters = <ProcessManager>{
        byId: () => rater,
    };

    const logger = new class implements PriorityLog
    {
        readonly PRIORITY_ERROR: number     = 0;
        readonly PRIORITY_IMPORTANT: number = 1;
        readonly PRIORITY_DB: number        = 2;
        readonly PRIORITY_INFO: number      = 3;
        readonly PRIORITY_SOCKET: number    = 4;

        log( _priority: number, ..._args: Array<string|number> ): this
        {
            return this;
        }
    };

    const server = <Server>{
        sendResponse: () => server,
        sendError:    () => server,
    };

    const dao = new class implements ServerDao
    {
        saveQuote(
            quote:      ServerSideQuote,
            success:    ServerDaoCallback,
            _failure:   ServerDaoCallback,
            _save_data: Record<string, any>,
        ): this
        {
            success( quote );
            return this;
        }

        mergeBucket(): this
        {
            return this;
        }

        saveQuoteClasses(): this
        {
            return this;
        }

        setWorksheets(): this
        {
            return this;
        }

        saveQuoteState(): this
        {
            throw new Error( "Unused method" );
        }

        saveQuoteLockState(): this
        {
            throw new Error( "Unused method" );
        }

        getWorksheet(): this
        {
            throw new Error( "Unused method" );
        }
    };

    const session = <UserSession>{
        isInternal: () => false,
    };

    const request = <UserRequest>{
        getSession:       () => session,
        getSessionIdName: () => {},
    };

    const response = <UserResponse>{};

    const quote = <ServerSideQuote>{
        getProgramId:       () => program_id,
        getProgram:         () => program,
        getId:              () => <QuoteId>0,
        setLastPremiumDate: () => quote,
        setRatedDate:       () => quote,
        getRatedDate:       () => <UnixTimestamp>0,
        getLastPremiumDate: () => <UnixTimestamp>0,
        getCurrentStepId:   () => 0,
        setExplicitLock:    () => quote,
        setRateBucket:      () => quote,
        setRatingData:      () => quote,
        getRatingData:      () => stub_rate_data,
        getBucket:          () => new QuoteDataBucket(),
    };

    return {
        program:        program,
        stub_rate_data: stub_rate_data,
        rater:          rater,
        raters:         raters,
        logger:         logger,
        server:         server,
        dao:            dao,
        session:        session,
        request:        request,
        response:       response,
        quote:          quote,
    };
};