summaryrefslogtreecommitdiff
path: root/tests/FundLab.Api.Tests/SipPlanStatusTests.fs
blob: 780d85f9fa320d9f83d39f0b167e0ca875af8614 (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
namespace FundLab.Api.Tests

open System
open Xunit
open FundLab.Api
open FundLab.Domain

[<Collection("postgres")>]
type SipPlanStatusTests(fixture: PostgresFixture) =
    let sharedRepository =
        lazy
            let value = FundRepository(fixture.ConnectionString)
            value.EnsureSchema()
            value

    let repository () = sharedRepository.Value

    let seedInstrument () =
        let code = Random.Shared.Next(0, 1000000).ToString("D6")

        let payload =
            {
                Source = "akshare"
                SourceRevision = "akshare-test/eastmoney"
                CollectedAt = DateTimeOffset(2026, 9, 21, 8, 0, 0, TimeSpan.Zero)
                Instruments = [ { Code = code; Name = "定投状态测试基金"; FundType = None } ]
            }

        repository().UpsertInstruments(payload, "sip-status-test-hash")
        code

    let createFund (initialCash: decimal) =
        let command =
            {
                Name = "定投状态测试 FOF"
                InitialCash = initialCash
                InitialUnitNav = 1.00000000m
                IsSynthetic = true
            }

        let key = fixture.Key(sprintf "sip-status-fund-%s" (Guid.NewGuid().ToString("N")))

        match repository().CreateFund(key, command) with
        | FundWriteResult.Created fund -> fund.Id
        | other -> failwithf "unexpected fund creation result: %A" other

    let app () = App.createApplication (repository ())

    let truncateMicroseconds (moment: DateTimeOffset) =
        let utc = moment.ToUniversalTime()
        DateTimeOffset(utc.Ticks - (utc.Ticks % 10L), TimeSpan.Zero)

    let insertQuoteOnDate (code: string) (nav: decimal) (navDate: DateOnly) =
        let revision = sprintf "akshare-test/%O" (Guid.NewGuid())

        let payload: MarketDataNavPayload =
            {
                Source = "akshare"
                SourceRevision = revision
                CollectedAt = truncateMicroseconds (DateTimeOffset.Now.AddSeconds(-10.0))
                Code = code
                Observations =
                    [
                        {
                            NavDate = navDate
                            PublishedAt = None
                            Nav = nav
                            AccumulatedNav = Some nav
                            DailyReturn = Some 0.0m
                        }
                    ]
            }

        repository().UpsertNavObservations(payload, sprintf "sip-status-hash/%s" revision)

    let createPlanWithAnchor (fundId: Guid) (code: string) (amount: decimal) (frequency: SipFrequency) =
        let key = fixture.Key(sprintf "sip-status-plan-%s" (Guid.NewGuid().ToString("N")))

        match
            repository().CreateSipPlan(
                key,
                fundId,
                { InstrumentCode = code; Amount = amount; Frequency = frequency },
                DateOnly(2026, 9, 7)
            )
        with
        | SipPlanWriteResult.SipPlanCreated plan -> plan.Id
        | other -> failwithf "unexpected sip plan result: %A" other

    let postStatus (fundId: Guid) (planId: Guid) (action: string) =
        PersistenceTestHelpers.invoke
            (app ())
            "POST"
            (sprintf "/api/funds/%O/sip/plans/%O/%s" fundId planId action)
            [ "Authorization", "Bearer test-token" ]
            ""

    let advance (fundId: Guid) (body: string) =
        PersistenceTestHelpers.invoke
            (app ())
            "POST"
            (sprintf "/api/funds/%O/sip/advance" fundId)
            [ "Authorization", "Bearer test-token" ]
            body

    let listPlans (fundId: Guid) =
        PersistenceTestHelpers.invoke
            (app ())
            "GET"
            (sprintf "/api/funds/%O/sip/plans" fundId)
            [ "Authorization", "Bearer test-token" ]
            ""

    [<Fact>]
    member _.``pause skips advance, resume lets the next due period execute again``() =
        let fundId = createFund 10000.00m
        let code = seedInstrument ()
        let planId = createPlanWithAnchor fundId code 100.00m Weekly

        insertQuoteOnDate code 2.5m (DateOnly(2026, 9, 14))
        insertQuoteOnDate code 2.5m (DateOnly(2026, 9, 21))

        let pauseStatus, pauseBody = postStatus fundId planId "pause"
        Assert.Equal(200, pauseStatus)
        Assert.Contains("\"status\":\"paused\"", pauseBody)

        let advanceStatus, advanceBody = advance fundId "{\"endDate\":\"2026-09-21\"}"
        Assert.Equal(200, advanceStatus)
        Assert.DoesNotContain("\"status\":\"succeeded\"", advanceBody)
        Assert.DoesNotContain("\"status\":\"pending_nav\"", advanceBody)

        let resumeStatus, resumeBody = postStatus fundId planId "resume"
        Assert.Equal(200, resumeStatus)
        Assert.Contains("\"status\":\"active\"", resumeBody)

        let _, resumedBody = advance fundId "{\"endDate\":\"2026-09-21\"}"
        Assert.Contains("\"status\":\"succeeded\"", resumedBody)
        Assert.Contains("\"tradeDate\":\"2026-09-14\"", resumedBody)

    [<Fact>]
    member _.``pausing an already paused plan is idempotent``() =
        let fundId = createFund 1000.00m
        let code = seedInstrument ()
        let planId = createPlanWithAnchor fundId code 100.00m Weekly

        let firstStatus, firstBody = postStatus fundId planId "pause"
        Assert.Equal(200, firstStatus)
        Assert.Contains("\"status\":\"paused\"", firstBody)

        let secondStatus, secondBody = postStatus fundId planId "pause"
        Assert.Equal(200, secondStatus)
        Assert.Contains("\"status\":\"paused\"", secondBody)

    [<Fact>]
    member _.``paused plan status is reflected in the sip plan list``() =
        let fundId = createFund 1000.00m
        let code = seedInstrument ()
        let planId = createPlanWithAnchor fundId code 100.00m Weekly

        let _, _ = postStatus fundId planId "pause"
        let _, listBody = listPlans fundId
        Assert.Contains("\"status\":\"paused\"", listBody)

        let _, _ = postStatus fundId planId "resume"
        let _, resumedListBody = listPlans fundId
        Assert.Contains("\"status\":\"active\"", resumedListBody)

    [<Fact>]
    member _.``pausing a plan that belongs to another fund answers 404``() =
        let fundId = createFund 1000.00m
        let otherFundId = createFund 1000.00m
        let code = seedInstrument ()
        let planId = createPlanWithAnchor fundId code 100.00m Weekly

        let status, body = postStatus otherFundId planId "pause"
        Assert.Equal(404, status)
        Assert.Contains("PLAN_NOT_FOUND", body)