-
Notifications
You must be signed in to change notification settings - Fork 6
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
一開始不做太複雜的功能,隨著開發及使用上的需求再慢慢增加就好。 首先,先做交易記錄的部份,所以先定義出交易紀錄的格式。 透過 `sdm` 套件從 `sqlite` 裡存取交易記錄,也會轉成 json 格式在前後端之 間傳遞。
- Loading branch information
Showing
1 changed file
with
56 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
package main | ||
|
||
import ( | ||
"database/sql" | ||
"log" | ||
|
||
"git.ronmi.tw/ronmi/sdm" | ||
) | ||
|
||
// Order 代表用戶的外幣資產的變動。 | ||
// | ||
// 由於 Order 是站在外幣資產的角度,所以買進外幣時 Foreign 會是正的,賣出則會是負的。 | ||
// 同理,買進外幣時的 Local 會是負的,賣出則會是正的。 | ||
type Order struct { | ||
Time int64 `sdm:"order_when" json:"when"` // 交易的 timestamp | ||
Foreign float64 `sdm:"foreign_currency" json:"foreign"` | ||
Local float64 `sdm:"local_currency" json:"local"` | ||
Code string `sdm:"currency_code" json:"code"` // 外幣代碼 (三碼英文) | ||
} | ||
|
||
// This will be called at very begining of the program, just fail fast. | ||
func initTable(db *sql.DB) { | ||
qstr := `CREATE TABLE IF NOT EXIST orders ( | ||
order_when TIMESTAMP, | ||
foreign_currency DOUBLE, | ||
local_currency DOUBLE, | ||
currency_code VARCHAR(3), | ||
CONSTRAINT order_pk (order_when,currency_code) | ||
)` | ||
|
||
if _, err := db.Exec(qstr); err != nil { | ||
log.Fatalf("Some error occured when creating order table in database: %s", err) | ||
} | ||
} | ||
|
||
func computeOrder(rows *sdm.Rows) (foreign, local, rate float64, err error) { | ||
for rows.Next() { | ||
var data Order | ||
rows.Scan(&data) | ||
foreign += data.Foreign | ||
local += data.Local | ||
} | ||
|
||
if foreign > 0 { | ||
rate = local / foreign | ||
} | ||
err = rows.Err() | ||
return | ||
} | ||
|
||
// Count 結算某外幣的所有交易 | ||
func Count(code string, m *sdm.Manager) (foreign, local, rate float64, err error) { | ||
qstr := `SELECT * FROM orders WHERE currency_code=?` | ||
|
||
return computeOrder(m.Query(Order{}, qstr, code)) | ||
} |