Compare commits
24 Commits
31d74588fb
...
ea867812bc
Author | SHA1 | Date |
---|---|---|
Savanni D'Gerinel | ea867812bc | |
Savanni D'Gerinel | cb55d6aae0 | |
Savanni D'Gerinel | cfc7df5e2f | |
Savanni D'Gerinel | 9fc9d2b758 | |
Savanni D'Gerinel | 76f4b31466 | |
Savanni D'Gerinel | 73052a0694 | |
Savanni D'Gerinel | 2c42c35dfe | |
Savanni D'Gerinel | afe693fe10 | |
Savanni D'Gerinel | af1422d523 | |
Savanni D'Gerinel | 792e20d44b | |
Savanni D'Gerinel | 8016188b29 | |
Savanni D'Gerinel | 74df2880bb | |
Savanni D'Gerinel | 96c4201680 | |
Savanni D'Gerinel | ecdd38ebbc | |
Savanni D'Gerinel | 2fb8728856 | |
Savanni D'Gerinel | a7d43ef184 | |
Savanni D'Gerinel | 9727d35116 | |
Savanni D'Gerinel | 1d6155d9e5 | |
Savanni D'Gerinel | a8bf540517 | |
Savanni D'Gerinel | 3db870d790 | |
Savanni D'Gerinel | 24276d172b | |
Savanni D'Gerinel | 96317f5692 | |
Savanni D'Gerinel | c1e797f3ae | |
Savanni D'Gerinel | 304008c674 |
|
@ -133,6 +133,17 @@ dependencies = [
|
|||
"pin-project-lite",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "async-trait"
|
||||
version = "0.1.77"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c980ee35e870bd1a4d2c8294d4c04d0499e67bca1e4b5cefcc693c2fa00caea9"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.48",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "atoi"
|
||||
version = "2.0.0"
|
||||
|
@ -420,7 +431,7 @@ dependencies = [
|
|||
"heck",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.41",
|
||||
"syn 2.0.48",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
@ -736,7 +747,7 @@ checksum = "487585f4d0c6655fe74905e2504d8ad6908e4db67f744eb140876906c2f3175d"
|
|||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.41",
|
||||
"syn 2.0.48",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
@ -928,6 +939,7 @@ name = "fitnesstrax"
|
|||
version = "0.3.0"
|
||||
dependencies = [
|
||||
"async-channel",
|
||||
"async-trait",
|
||||
"chrono",
|
||||
"chrono-tz",
|
||||
"dimensioned 0.8.0",
|
||||
|
@ -1133,7 +1145,7 @@ checksum = "53b153fd91e4b0147f4aced87be237c98248656bb01050b96bf3ee89220a8ddb"
|
|||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.41",
|
||||
"syn 2.0.48",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
@ -1368,7 +1380,7 @@ dependencies = [
|
|||
"proc-macro-error",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.41",
|
||||
"syn 2.0.48",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
@ -2454,7 +2466,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c"
|
|||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.41",
|
||||
"syn 2.0.48",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
@ -2659,7 +2671,7 @@ checksum = "4359fd9c9171ec6e8c62926d6faaf553a8dc3f64e1507e76da7911b4f6a04405"
|
|||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.41",
|
||||
"syn 2.0.48",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
@ -2803,9 +2815,9 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.70"
|
||||
version = "1.0.78"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "39278fbbf5fb4f646ce651690877f89d1c5811a3d4acb27700c1cb3cdb78fd3b"
|
||||
checksum = "e2422ad645d89c99f8f3e6b88a9fdeca7fabeac836b1002371c4367c8f984aae"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
@ -2847,9 +2859,9 @@ checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0"
|
|||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.33"
|
||||
version = "1.0.35"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5267fca4496028628a95160fc423a33e8b2e6af8a5302579e322e4b520293cae"
|
||||
checksum = "291ec9ab5efd934aaf503a6466c5d5251535d108ee747472c3977cc5acc868ef"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
@ -3332,7 +3344,7 @@ checksum = "43576ca501357b9b071ac53cdc7da8ef0cbd9493d8df094cd821777ea6e894d3"
|
|||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.41",
|
||||
"syn 2.0.48",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
@ -3731,9 +3743,9 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "2.0.41"
|
||||
version = "2.0.48"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "44c8b28c477cc3bf0e7966561e3460130e1255f7a1cf71931075f1c5e7a7e269"
|
||||
checksum = "0f3531638e407dfc0814761abb7c00a5b54992b849452a0646b7f65c9f770f3f"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
|
@ -3829,7 +3841,7 @@ checksum = "01742297787513b79cf8e29d1056ede1313e2420b7b3b15d0a768b4921f549df"
|
|||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.41",
|
||||
"syn 2.0.48",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
@ -3953,7 +3965,7 @@ checksum = "5b8a1e28f2deaa14e508979454cb3a223b10b938b45af148bc0986de36f1923b"
|
|||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.41",
|
||||
"syn 2.0.48",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
@ -4074,7 +4086,7 @@ checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7"
|
|||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.41",
|
||||
"syn 2.0.48",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
@ -4444,7 +4456,7 @@ dependencies = [
|
|||
"once_cell",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.41",
|
||||
"syn 2.0.48",
|
||||
"wasm-bindgen-shared",
|
||||
]
|
||||
|
||||
|
@ -4478,7 +4490,7 @@ checksum = "f0eb82fcb7930ae6219a7ecfd55b217f5f0893484b7a13022ebb2b2bf20b5283"
|
|||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.41",
|
||||
"syn 2.0.48",
|
||||
"wasm-bindgen-backend",
|
||||
"wasm-bindgen-shared",
|
||||
]
|
||||
|
@ -4719,7 +4731,7 @@ checksum = "b3c129550b3e6de3fd0ba67ba5c81818f9805e58b8d7fee80a3a59d2c9fc601a"
|
|||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.41",
|
||||
"syn 2.0.48",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
|
70
Cargo.nix
70
Cargo.nix
|
@ -655,6 +655,32 @@ rec {
|
|||
};
|
||||
resolvedDefaultFeatures = [ "default" "std" ];
|
||||
};
|
||||
"async-trait" = rec {
|
||||
crateName = "async-trait";
|
||||
version = "0.1.77";
|
||||
edition = "2021";
|
||||
sha256 = "1adf1jh2yg39rkpmqjqyr9xyd6849p0d95425i6imgbhx0syx069";
|
||||
procMacro = true;
|
||||
authors = [
|
||||
"David Tolnay <dtolnay@gmail.com>"
|
||||
];
|
||||
dependencies = [
|
||||
{
|
||||
name = "proc-macro2";
|
||||
packageId = "proc-macro2";
|
||||
}
|
||||
{
|
||||
name = "quote";
|
||||
packageId = "quote";
|
||||
}
|
||||
{
|
||||
name = "syn";
|
||||
packageId = "syn 2.0.48";
|
||||
features = [ "full" "visit-mut" ];
|
||||
}
|
||||
];
|
||||
|
||||
};
|
||||
"atoi" = rec {
|
||||
crateName = "atoi";
|
||||
version = "2.0.0";
|
||||
|
@ -1487,7 +1513,7 @@ rec {
|
|||
}
|
||||
{
|
||||
name = "syn";
|
||||
packageId = "syn 2.0.41";
|
||||
packageId = "syn 2.0.48";
|
||||
features = [ "full" ];
|
||||
}
|
||||
];
|
||||
|
@ -2394,7 +2420,7 @@ rec {
|
|||
}
|
||||
{
|
||||
name = "syn";
|
||||
packageId = "syn 2.0.41";
|
||||
packageId = "syn 2.0.48";
|
||||
}
|
||||
];
|
||||
features = {
|
||||
|
@ -2972,6 +2998,10 @@ rec {
|
|||
name = "async-channel";
|
||||
packageId = "async-channel";
|
||||
}
|
||||
{
|
||||
name = "async-trait";
|
||||
packageId = "async-trait";
|
||||
}
|
||||
{
|
||||
name = "chrono";
|
||||
packageId = "chrono";
|
||||
|
@ -3576,7 +3606,7 @@ rec {
|
|||
}
|
||||
{
|
||||
name = "syn";
|
||||
packageId = "syn 2.0.41";
|
||||
packageId = "syn 2.0.48";
|
||||
features = [ "full" ];
|
||||
}
|
||||
];
|
||||
|
@ -4341,7 +4371,7 @@ rec {
|
|||
}
|
||||
{
|
||||
name = "syn";
|
||||
packageId = "syn 2.0.41";
|
||||
packageId = "syn 2.0.48";
|
||||
features = [ "full" ];
|
||||
}
|
||||
];
|
||||
|
@ -7690,7 +7720,7 @@ rec {
|
|||
}
|
||||
{
|
||||
name = "syn";
|
||||
packageId = "syn 2.0.41";
|
||||
packageId = "syn 2.0.48";
|
||||
features = [ "full" ];
|
||||
}
|
||||
];
|
||||
|
@ -8187,7 +8217,7 @@ rec {
|
|||
}
|
||||
{
|
||||
name = "syn";
|
||||
packageId = "syn 2.0.41";
|
||||
packageId = "syn 2.0.48";
|
||||
features = [ "full" "visit-mut" ];
|
||||
}
|
||||
];
|
||||
|
@ -8529,9 +8559,9 @@ rec {
|
|||
};
|
||||
"proc-macro2" = rec {
|
||||
crateName = "proc-macro2";
|
||||
version = "1.0.70";
|
||||
version = "1.0.78";
|
||||
edition = "2021";
|
||||
sha256 = "0fzxg3dkrjy101vv5b6llc8mh74xz1vhhsaiwrn68kzvynxqy9rr";
|
||||
sha256 = "1bjak27pqdn4f4ih1c9nr3manzyavsgqmf76ygw9k76q8pb2lhp2";
|
||||
authors = [
|
||||
"David Tolnay <dtolnay@gmail.com>"
|
||||
"Alex Crichton <alex@alexcrichton.com>"
|
||||
|
@ -8665,9 +8695,9 @@ rec {
|
|||
};
|
||||
"quote" = rec {
|
||||
crateName = "quote";
|
||||
version = "1.0.33";
|
||||
version = "1.0.35";
|
||||
edition = "2018";
|
||||
sha256 = "1biw54hbbr12wdwjac55z1m2x2rylciw83qnjn564a3096jgqrsj";
|
||||
sha256 = "1vv8r2ncaz4pqdr78x7f138ka595sp2ncr1sa2plm4zxbsmwj7i9";
|
||||
authors = [
|
||||
"David Tolnay <dtolnay@gmail.com>"
|
||||
];
|
||||
|
@ -10269,7 +10299,7 @@ rec {
|
|||
}
|
||||
{
|
||||
name = "syn";
|
||||
packageId = "syn 2.0.41";
|
||||
packageId = "syn 2.0.48";
|
||||
}
|
||||
];
|
||||
features = {
|
||||
|
@ -11748,11 +11778,11 @@ rec {
|
|||
};
|
||||
resolvedDefaultFeatures = [ "clone-impls" "default" "derive" "extra-traits" "full" "parsing" "printing" "proc-macro" "quote" ];
|
||||
};
|
||||
"syn 2.0.41" = rec {
|
||||
"syn 2.0.48" = rec {
|
||||
crateName = "syn";
|
||||
version = "2.0.41";
|
||||
version = "2.0.48";
|
||||
edition = "2021";
|
||||
sha256 = "0sg2lzkwbwbm229p3kx1yxai43hkc0s1wmk6g47bzhvw8y6b5j24";
|
||||
sha256 = "0gqgfygmrxmp8q32lia9p294kdd501ybn6kn2h4gqza0irik2d8g";
|
||||
authors = [
|
||||
"David Tolnay <dtolnay@gmail.com>"
|
||||
];
|
||||
|
@ -11990,7 +12020,7 @@ rec {
|
|||
}
|
||||
{
|
||||
name = "syn";
|
||||
packageId = "syn 2.0.41";
|
||||
packageId = "syn 2.0.48";
|
||||
}
|
||||
];
|
||||
|
||||
|
@ -12406,7 +12436,7 @@ rec {
|
|||
}
|
||||
{
|
||||
name = "syn";
|
||||
packageId = "syn 2.0.41";
|
||||
packageId = "syn 2.0.48";
|
||||
features = [ "full" ];
|
||||
}
|
||||
];
|
||||
|
@ -12820,7 +12850,7 @@ rec {
|
|||
}
|
||||
{
|
||||
name = "syn";
|
||||
packageId = "syn 2.0.41";
|
||||
packageId = "syn 2.0.48";
|
||||
usesDefaultFeatures = false;
|
||||
features = [ "full" "parsing" "printing" "visit-mut" "clone-impls" "extra-traits" "proc-macro" ];
|
||||
}
|
||||
|
@ -13814,7 +13844,7 @@ rec {
|
|||
}
|
||||
{
|
||||
name = "syn";
|
||||
packageId = "syn 2.0.41";
|
||||
packageId = "syn 2.0.48";
|
||||
features = [ "full" ];
|
||||
}
|
||||
{
|
||||
|
@ -13904,7 +13934,7 @@ rec {
|
|||
}
|
||||
{
|
||||
name = "syn";
|
||||
packageId = "syn 2.0.41";
|
||||
packageId = "syn 2.0.48";
|
||||
features = [ "visit" "full" ];
|
||||
}
|
||||
{
|
||||
|
@ -15388,7 +15418,7 @@ rec {
|
|||
}
|
||||
{
|
||||
name = "syn";
|
||||
packageId = "syn 2.0.41";
|
||||
packageId = "syn 2.0.48";
|
||||
}
|
||||
];
|
||||
|
||||
|
|
|
@ -124,13 +124,10 @@ where
|
|||
/// Put a new record into the database. A unique id will be assigned to the record and
|
||||
/// returned.
|
||||
pub fn put(&mut self, entry: T) -> Result<RecordId, EmseriesWriteError> {
|
||||
let uuid = RecordId::default();
|
||||
let record = Record {
|
||||
id: uuid,
|
||||
data: entry,
|
||||
};
|
||||
let id = RecordId::default();
|
||||
let record = Record { id, data: entry };
|
||||
self.update(record)?;
|
||||
Ok(uuid)
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
/// Update an existing record. The [RecordId] of the record passed into this function must match
|
||||
|
|
|
@ -166,6 +166,17 @@ impl<T: Clone + Recordable> Record<T> {
|
|||
pub fn timestamp(&self) -> Timestamp {
|
||||
self.data.timestamp()
|
||||
}
|
||||
|
||||
pub fn map<Map, U>(self, map: Map) -> Record<U>
|
||||
where
|
||||
Map: Fn(T) -> U,
|
||||
U: Clone + Recordable,
|
||||
{
|
||||
Record {
|
||||
id: self.id,
|
||||
data: map(self.data),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
|
|
@ -8,6 +8,7 @@ edition = "2021"
|
|||
[dependencies]
|
||||
adw = { version = "0.5", package = "libadwaita", features = [ "v1_4" ] }
|
||||
async-channel = { version = "2.1" }
|
||||
async-trait = { version = "0.1" }
|
||||
chrono = { version = "0.4" }
|
||||
chrono-tz = { version = "0.8" }
|
||||
dimensioned = { version = "0.8", features = [ "serde" ] }
|
||||
|
|
|
@ -14,6 +14,7 @@ General Public License for more details.
|
|||
You should have received a copy of the GNU General Public License along with FitnessTrax. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
use async_trait::async_trait;
|
||||
use chrono::NaiveDate;
|
||||
use emseries::{time_range, Record, RecordId, Series, Timestamp};
|
||||
use ft_core::TraxRecord;
|
||||
|
@ -34,6 +35,32 @@ pub enum AppError {
|
|||
Unhandled,
|
||||
}
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum ReadError {
|
||||
#[error("no database loaded")]
|
||||
NoDatabase,
|
||||
}
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum WriteError {
|
||||
#[error("no database loaded")]
|
||||
NoDatabase,
|
||||
#[error("unhandled error")]
|
||||
Unhandled,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait RecordProvider: Send + Sync {
|
||||
async fn records(
|
||||
&self,
|
||||
start: NaiveDate,
|
||||
end: NaiveDate,
|
||||
) -> Result<Vec<Record<TraxRecord>>, ReadError>;
|
||||
async fn put_record(&self, record: TraxRecord) -> Result<RecordId, WriteError>;
|
||||
async fn update_record(&self, record: Record<TraxRecord>) -> Result<(), WriteError>;
|
||||
async fn delete_record(&self, id: RecordId) -> Result<(), WriteError>;
|
||||
}
|
||||
|
||||
/// The real, headless application. This is where all of the logic will reside.
|
||||
#[derive(Clone)]
|
||||
pub struct App {
|
||||
|
@ -57,6 +84,18 @@ impl App {
|
|||
}
|
||||
}
|
||||
|
||||
pub async fn open_db(&self, path: PathBuf) -> Result<(), AppError> {
|
||||
let db_ref = self.database.clone();
|
||||
self.runtime
|
||||
.spawn_blocking(move || {
|
||||
let db = Series::open(path).map_err(|_| AppError::FailedToOpenDatabase)?;
|
||||
*db_ref.write().unwrap() = Some(db);
|
||||
Ok(())
|
||||
})
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
pub async fn get_record(&self, id: RecordId) -> Result<Option<Record<TraxRecord>>, AppError> {
|
||||
let db = self.database.clone();
|
||||
self.runtime
|
||||
|
@ -70,12 +109,15 @@ impl App {
|
|||
.await
|
||||
.unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn records(
|
||||
#[async_trait]
|
||||
impl RecordProvider for App {
|
||||
async fn records(
|
||||
&self,
|
||||
start: NaiveDate,
|
||||
end: NaiveDate,
|
||||
) -> Result<Vec<Record<TraxRecord>>, AppError> {
|
||||
) -> Result<Vec<Record<TraxRecord>>, ReadError> {
|
||||
let db = self.database.clone();
|
||||
self.runtime
|
||||
.spawn_blocking(move || {
|
||||
|
@ -91,14 +133,14 @@ impl App {
|
|||
.collect::<Vec<Record<TraxRecord>>>();
|
||||
Ok(records)
|
||||
} else {
|
||||
Err(AppError::NoDatabase)
|
||||
Err(ReadError::NoDatabase)
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
pub async fn put_record(&self, record: TraxRecord) -> Result<RecordId, AppError> {
|
||||
async fn put_record(&self, record: TraxRecord) -> Result<RecordId, WriteError> {
|
||||
let db = self.database.clone();
|
||||
self.runtime
|
||||
.spawn_blocking(move || {
|
||||
|
@ -111,10 +153,10 @@ impl App {
|
|||
})
|
||||
.await
|
||||
.unwrap()
|
||||
.map_err(|_| AppError::Unhandled)
|
||||
.map_err(|_| WriteError::Unhandled)
|
||||
}
|
||||
|
||||
pub async fn update_record(&self, record: Record<TraxRecord>) -> Result<(), AppError> {
|
||||
async fn update_record(&self, record: Record<TraxRecord>) -> Result<(), WriteError> {
|
||||
let db = self.database.clone();
|
||||
self.runtime
|
||||
.spawn_blocking(move || {
|
||||
|
@ -126,18 +168,10 @@ impl App {
|
|||
})
|
||||
.await
|
||||
.unwrap()
|
||||
.map_err(|_| AppError::Unhandled)
|
||||
.map_err(|_| WriteError::Unhandled)
|
||||
}
|
||||
|
||||
pub async fn open_db(&self, path: PathBuf) -> Result<(), AppError> {
|
||||
let db_ref = self.database.clone();
|
||||
self.runtime
|
||||
.spawn_blocking(move || {
|
||||
let db = Series::open(path).map_err(|_| AppError::FailedToOpenDatabase)?;
|
||||
*db_ref.write().unwrap() = Some(db);
|
||||
Ok(())
|
||||
})
|
||||
.await
|
||||
.unwrap()
|
||||
async fn delete_record(&self, _id: RecordId) -> Result<(), WriteError> {
|
||||
unimplemented!()
|
||||
}
|
||||
}
|
||||
|
|
|
@ -121,6 +121,7 @@ impl AppWindow {
|
|||
s
|
||||
}
|
||||
|
||||
#[allow(unused)]
|
||||
fn show_welcome_view(&self) {
|
||||
let view = View::Welcome(WelcomeView::new({
|
||||
let s = self.clone();
|
||||
|
@ -129,13 +130,13 @@ impl AppWindow {
|
|||
self.swap_main(view);
|
||||
}
|
||||
|
||||
fn show_historical_view(&self, start_date: chrono::NaiveDate, end_date: chrono::NaiveDate) {
|
||||
fn show_historical_view(&self, interval: DayInterval) {
|
||||
let on_select_day = {
|
||||
let s = self.clone();
|
||||
move |date, _records| {
|
||||
move |date| {
|
||||
let s = s.clone();
|
||||
glib::spawn_future_local(async move {
|
||||
let view_model = DayDetailViewModel::new(date, s.app.clone()).await;
|
||||
let view_model = DayDetailViewModel::new(date, s.app.clone()).await.unwrap();
|
||||
let layout = gtk::Box::new(gtk::Orientation::Vertical, 0);
|
||||
layout.append(&adw::HeaderBar::new());
|
||||
// layout.append(&DayDetailView::new(date, records, s.app.clone()));
|
||||
|
@ -151,10 +152,7 @@ impl AppWindow {
|
|||
|
||||
let view = View::Historical(HistoricalView::new(
|
||||
self.app.clone(),
|
||||
DayInterval {
|
||||
start: start_date,
|
||||
end: end_date,
|
||||
},
|
||||
interval,
|
||||
Rc::new(on_select_day),
|
||||
));
|
||||
self.swap_main(view);
|
||||
|
@ -166,10 +164,7 @@ impl AppWindow {
|
|||
async move {
|
||||
let end = Local::now().date_naive();
|
||||
let start = end - Duration::days(7);
|
||||
match s.app.records(start, end).await {
|
||||
Ok(_records) => s.show_historical_view(start, end),
|
||||
Err(_) => s.show_welcome_view(),
|
||||
}
|
||||
s.show_historical_view(DayInterval { start, end });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
@ -186,6 +181,7 @@ impl AppWindow {
|
|||
self.layout.append(¤t_widget.widget());
|
||||
}
|
||||
|
||||
#[allow(unused)]
|
||||
fn on_apply_config(&self, path: PathBuf) {
|
||||
glib::spawn_future_local({
|
||||
let s = self.clone();
|
||||
|
|
|
@ -20,10 +20,11 @@ use crate::{
|
|||
components::{
|
||||
steps_editor, time_distance_summary, weight_field, ActionGroup, Steps, WeightLabel,
|
||||
},
|
||||
types::{DistanceFormatter, DurationFormatter, WeightFormatter},
|
||||
view_models::DayDetailViewModel,
|
||||
};
|
||||
use emseries::{Record, RecordId};
|
||||
use ft_core::{RecordType, TraxRecord};
|
||||
use ft_core::{TimeDistanceActivity, TraxRecord};
|
||||
use glib::Object;
|
||||
use gtk::{prelude::*, subclass::prelude::*};
|
||||
use std::{cell::RefCell, rc::Rc};
|
||||
|
@ -104,8 +105,11 @@ impl DaySummary {
|
|||
row.append(&label);
|
||||
self.append(&row);
|
||||
|
||||
let biking_summary = view_model.biking_summary();
|
||||
if let Some(label) = time_distance_summary(biking_summary.0, biking_summary.1) {
|
||||
let biking_summary = view_model.time_distance_summary(TimeDistanceActivity::BikeRide);
|
||||
if let Some(label) = time_distance_summary(
|
||||
DistanceFormatter::from(biking_summary.0),
|
||||
DurationFormatter::from(biking_summary.1),
|
||||
) {
|
||||
self.append(&label);
|
||||
}
|
||||
}
|
||||
|
@ -147,7 +151,7 @@ impl DayDetail {
|
|||
let top_row = gtk::Box::builder()
|
||||
.orientation(gtk::Orientation::Horizontal)
|
||||
.build();
|
||||
let weight_view = WeightLabel::new(view_model.weight());
|
||||
let weight_view = WeightLabel::new(view_model.weight().map(WeightFormatter::from));
|
||||
top_row.append(&weight_view.widget());
|
||||
|
||||
let steps_view = Steps::new(view_model.steps());
|
||||
|
@ -155,18 +159,9 @@ impl DayDetail {
|
|||
|
||||
s.append(&top_row);
|
||||
|
||||
let records = view_model.records();
|
||||
let records = view_model.time_distance_records();
|
||||
for emseries::Record { data, .. } in records {
|
||||
match data {
|
||||
TraxRecord::BikeRide(ride) => {
|
||||
s.append(&time_distance_detail(RecordType::BikeRide, ride))
|
||||
}
|
||||
TraxRecord::Row(row) => s.append(&time_distance_detail(RecordType::Row, row)),
|
||||
TraxRecord::Run(run) => s.append(&time_distance_detail(RecordType::Run, run)),
|
||||
TraxRecord::Swim(walk) => s.append(&time_distance_detail(RecordType::Swim, walk)),
|
||||
TraxRecord::Walk(walk) => s.append(&time_distance_detail(RecordType::Walk, walk)),
|
||||
_ => {}
|
||||
}
|
||||
s.append(&time_distance_detail(data));
|
||||
}
|
||||
|
||||
s
|
||||
|
@ -175,6 +170,7 @@ impl DayDetail {
|
|||
|
||||
pub struct DayEditPrivate {
|
||||
on_finished: RefCell<Box<dyn Fn()>>,
|
||||
#[allow(unused)]
|
||||
workout_rows: RefCell<gtk::Box>,
|
||||
view_model: RefCell<Option<DayDetailViewModel>>,
|
||||
}
|
||||
|
@ -230,24 +226,15 @@ impl DayEdit {
|
|||
.into_iter()
|
||||
.filter_map({
|
||||
let s = s.clone();
|
||||
move |record| {
|
||||
let workout_type = record.data.workout_type();
|
||||
match record.data {
|
||||
TraxRecord::BikeRide(workout)
|
||||
| TraxRecord::Row(workout)
|
||||
| TraxRecord::Run(workout)
|
||||
| TraxRecord::Swim(workout)
|
||||
| TraxRecord::Walk(workout) => {
|
||||
Some(TimeDistanceEdit::new(workout_type, workout, {
|
||||
move |record| match record.data {
|
||||
TraxRecord::TimeDistance(workout) => Some(TimeDistanceEdit::new(workout, {
|
||||
let s = s.clone();
|
||||
move |type_, data| {
|
||||
s.update_workout(record.id, type_, data);
|
||||
}
|
||||
}))
|
||||
move |data| {
|
||||
s.update_workout(record.id, data);
|
||||
}
|
||||
})),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
})
|
||||
.for_each(|row| s.imp().workout_rows.borrow().append(&row));
|
||||
|
||||
|
@ -266,10 +253,11 @@ impl DayEdit {
|
|||
let view_model = {
|
||||
let view_model = s.imp().view_model.borrow();
|
||||
view_model
|
||||
.clone()
|
||||
.as_ref()
|
||||
.expect("DayEdit has not been initialized with the view model")
|
||||
.clone()
|
||||
};
|
||||
let _ = view_model.save().await;
|
||||
let _ = view_model.async_save().await;
|
||||
(s.imp().on_finished.borrow())()
|
||||
}
|
||||
});
|
||||
|
@ -278,55 +266,47 @@ impl DayEdit {
|
|||
fn add_row(&self, workout: Record<TraxRecord>) {
|
||||
let workout_rows = self.imp().workout_rows.borrow();
|
||||
|
||||
let workout_id = workout.id;
|
||||
let workout_type = workout.data.workout_type();
|
||||
|
||||
#[allow(clippy::single_match)]
|
||||
match workout.data {
|
||||
TraxRecord::BikeRide(ref w)
|
||||
| TraxRecord::Row(ref w)
|
||||
| TraxRecord::Swim(ref w)
|
||||
| TraxRecord::Run(ref w)
|
||||
| TraxRecord::Walk(ref w) => {
|
||||
workout_rows.append(&TimeDistanceEdit::new(workout_type, w.clone(), {
|
||||
TraxRecord::TimeDistance(r) => workout_rows.append(&TimeDistanceEdit::new(r, {
|
||||
let s = self.clone();
|
||||
move |type_, data| s.update_workout(workout_id, type_, data)
|
||||
}));
|
||||
move |data| {
|
||||
println!("update workout callback on workout: {:?}", workout.id);
|
||||
s.update_workout(workout.id, data)
|
||||
}
|
||||
})),
|
||||
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn update_workout(&self, id: RecordId, type_: RecordType, data: ft_core::TimeDistance) {
|
||||
let data = match type_ {
|
||||
RecordType::BikeRide => TraxRecord::BikeRide(data),
|
||||
RecordType::Row => TraxRecord::Row(data),
|
||||
RecordType::Swim => TraxRecord::Swim(data),
|
||||
RecordType::Run => TraxRecord::Run(data),
|
||||
RecordType::Walk => TraxRecord::Walk(data),
|
||||
_ => panic!("Record type {:?} is not a Time/Distance record", type_),
|
||||
fn update_workout(&self, id: RecordId, data: ft_core::TimeDistance) {
|
||||
if let Some(ref view_model) = *self.imp().view_model.borrow() {
|
||||
let record = Record {
|
||||
id,
|
||||
data: TraxRecord::TimeDistance(data),
|
||||
};
|
||||
let record = Record { id, data };
|
||||
let view_model = self.imp().view_model.borrow();
|
||||
let view_model = view_model
|
||||
.as_ref()
|
||||
.expect("DayEdit has not been initialized with a view model");
|
||||
view_model.update_record(record);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn control_buttons(s: &DayEdit, view_model: &DayDetailViewModel) -> ActionGroup {
|
||||
ActionGroup::builder()
|
||||
.primary_action("Save", {
|
||||
let s = s.clone();
|
||||
let _view_model = view_model.clone();
|
||||
move || s.finish()
|
||||
})
|
||||
.secondary_action("Cancel", {
|
||||
let s = s.clone();
|
||||
let view_model = view_model.clone();
|
||||
move || {
|
||||
view_model.revert();
|
||||
let s = s.clone();
|
||||
let view_model = view_model.clone();
|
||||
glib::spawn_future_local(async move {
|
||||
view_model.revert().await;
|
||||
s.finish();
|
||||
});
|
||||
}
|
||||
})
|
||||
.build()
|
||||
|
@ -337,10 +317,10 @@ fn weight_and_steps_row(view_model: &DayDetailViewModel) -> gtk::Box {
|
|||
.orientation(gtk::Orientation::Horizontal)
|
||||
.build();
|
||||
row.append(
|
||||
&weight_field(view_model.weight(), {
|
||||
&weight_field(view_model.weight().map(WeightFormatter::from), {
|
||||
let view_model = view_model.clone();
|
||||
move |w| match w {
|
||||
Some(w) => view_model.set_weight(w),
|
||||
Some(w) => view_model.set_weight(*w),
|
||||
None => eprintln!("have not implemented record delete"),
|
||||
}
|
||||
})
|
||||
|
@ -376,8 +356,8 @@ where
|
|||
let view_model = view_model.clone();
|
||||
let add_row = add_row.clone();
|
||||
move |_| {
|
||||
let workout = view_model.new_record(RecordType::Walk);
|
||||
&add_row(workout);
|
||||
let workout = view_model.new_time_distance(TimeDistanceActivity::Walking);
|
||||
add_row(workout.map(TraxRecord::TimeDistance));
|
||||
}
|
||||
});
|
||||
|
||||
|
@ -389,8 +369,8 @@ where
|
|||
running_button.connect_clicked({
|
||||
let view_model = view_model.clone();
|
||||
move |_| {
|
||||
let workout = view_model.new_record(RecordType::Walk);
|
||||
add_row(workout);
|
||||
let workout = view_model.new_time_distance(TimeDistanceActivity::Running);
|
||||
add_row(workout.map(TraxRecord::TimeDistance));
|
||||
}
|
||||
});
|
||||
*/
|
||||
|
@ -403,8 +383,8 @@ where
|
|||
biking_button.connect_clicked({
|
||||
let view_model = view_model.clone();
|
||||
move |_| {
|
||||
let workout = view_model.new_record(RecordType::BikeRide);
|
||||
add_row(workout);
|
||||
let workout = view_model.new_time_distance(TimeDistanceActivity::BikeRide);
|
||||
add_row(workout.map(TraxRecord::TimeDistance));
|
||||
}
|
||||
});
|
||||
|
||||
|
|
|
@ -106,6 +106,7 @@ impl<T: Clone + std::fmt::Debug + 'static> TextEntry<T> {
|
|||
}
|
||||
}
|
||||
|
||||
#[allow(unused)]
|
||||
pub fn time_field<OnUpdate>(
|
||||
value: Option<TimeFormatter>,
|
||||
on_update: OnUpdate,
|
||||
|
@ -122,6 +123,7 @@ where
|
|||
)
|
||||
}
|
||||
|
||||
#[allow(unused)]
|
||||
pub fn distance_field<OnUpdate>(
|
||||
value: Option<DistanceFormatter>,
|
||||
on_update: OnUpdate,
|
||||
|
@ -138,6 +140,7 @@ where
|
|||
)
|
||||
}
|
||||
|
||||
#[allow(unused)]
|
||||
pub fn duration_field<OnUpdate>(
|
||||
value: Option<DurationFormatter>,
|
||||
on_update: OnUpdate,
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
/*
|
||||
Copyright 2023, Savanni D'Gerinel <savanni@luminescent-dreams.com>
|
||||
Copyright 2023-2024, Savanni D'Gerinel <savanni@luminescent-dreams.com>
|
||||
|
||||
This file is part of FitnessTrax.
|
||||
|
||||
|
@ -22,10 +22,10 @@ use crate::{
|
|||
types::{DistanceFormatter, DurationFormatter, FormatOption, TimeFormatter},
|
||||
};
|
||||
use dimensioned::si;
|
||||
use ft_core::{RecordType, TimeDistance};
|
||||
use ft_core::{TimeDistance, TimeDistanceActivity};
|
||||
use glib::Object;
|
||||
use gtk::{prelude::*, subclass::prelude::*};
|
||||
use std::cell::RefCell;
|
||||
use std::{rc::Rc, cell::RefCell};
|
||||
|
||||
pub fn time_distance_summary(
|
||||
distance: DistanceFormatter,
|
||||
|
@ -45,7 +45,7 @@ pub fn time_distance_summary(
|
|||
text.map(|text| gtk::Label::new(Some(&text)))
|
||||
}
|
||||
|
||||
pub fn time_distance_detail(type_: ft_core::RecordType, record: ft_core::TimeDistance) -> gtk::Box {
|
||||
pub fn time_distance_detail(record: ft_core::TimeDistance) -> gtk::Box {
|
||||
let layout = gtk::Box::builder()
|
||||
.orientation(gtk::Orientation::Vertical)
|
||||
.hexpand(true)
|
||||
|
@ -62,7 +62,7 @@ pub fn time_distance_detail(type_: ft_core::RecordType, record: ft_core::TimeDis
|
|||
first_row.append(
|
||||
>k::Label::builder()
|
||||
.halign(gtk::Align::Start)
|
||||
.label(format!("{:?}", type_))
|
||||
.label(format!("{:?}", record.activity))
|
||||
.build(),
|
||||
);
|
||||
|
||||
|
@ -109,18 +109,25 @@ pub fn time_distance_detail(type_: ft_core::RecordType, record: ft_core::TimeDis
|
|||
layout
|
||||
}
|
||||
|
||||
type OnUpdate = Rc<RefCell<Box<dyn Fn(TimeDistance)>>>;
|
||||
|
||||
pub struct TimeDistanceEditPrivate {
|
||||
type_: RefCell<RecordType>,
|
||||
workout: RefCell<TimeDistance>,
|
||||
on_update: RefCell<Box<dyn Fn(RecordType, TimeDistance)>>,
|
||||
#[allow(unused)]
|
||||
workout: RefCell<ft_core::TimeDistance>,
|
||||
on_update: OnUpdate,
|
||||
}
|
||||
|
||||
impl Default for TimeDistanceEditPrivate {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
type_: RefCell::new(RecordType::BikeRide),
|
||||
workout: RefCell::new(TimeDistance::new(chrono::Utc::now().into())),
|
||||
on_update: RefCell::new(Box::new(|_, _| {})),
|
||||
workout: RefCell::new(TimeDistance {
|
||||
datetime: chrono::Utc::now().into(),
|
||||
activity: TimeDistanceActivity::BikeRide,
|
||||
duration: None,
|
||||
distance: None,
|
||||
comments: None,
|
||||
}),
|
||||
on_update: Rc::new(RefCell::new(Box::new(|_| {}))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -152,13 +159,12 @@ impl Default for TimeDistanceEdit {
|
|||
}
|
||||
|
||||
impl TimeDistanceEdit {
|
||||
pub fn new<OnUpdate>(type_: RecordType, workout: TimeDistance, on_update: OnUpdate) -> Self
|
||||
pub fn new<OnUpdate>(workout: TimeDistance, on_update: OnUpdate) -> Self
|
||||
where
|
||||
OnUpdate: Fn(ft_core::RecordType, ft_core::TimeDistance) + 'static,
|
||||
OnUpdate: Fn(TimeDistance) + 'static,
|
||||
{
|
||||
let s = Self::default();
|
||||
|
||||
*s.imp().type_.borrow_mut() = type_;
|
||||
*s.imp().workout.borrow_mut() = workout.clone();
|
||||
*s.imp().on_update.borrow_mut() = Box::new(on_update);
|
||||
|
||||
|
@ -196,19 +202,19 @@ impl TimeDistanceEdit {
|
|||
s
|
||||
}
|
||||
|
||||
fn update_time(&self, time: Option<TimeFormatter>) {
|
||||
fn update_time(&self, _time: Option<TimeFormatter>) {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
fn update_distance(&self, distance: Option<DistanceFormatter>) {
|
||||
let mut workout = self.imp().workout.borrow_mut();
|
||||
workout.distance = distance.map(|d| *d);
|
||||
(self.imp().on_update.borrow())(self.imp().type_.borrow().clone(), workout.clone());
|
||||
(self.imp().on_update.borrow())(workout.clone());
|
||||
}
|
||||
|
||||
fn update_duration(&self, duration: Option<DurationFormatter>) {
|
||||
let mut workout = self.imp().workout.borrow_mut();
|
||||
workout.duration = duration.map(|d| *d);
|
||||
(self.imp().on_update.borrow())(self.imp().type_.borrow().clone(), workout.clone());
|
||||
(self.imp().on_update.borrow())(workout.clone());
|
||||
}
|
||||
}
|
||||
|
|
|
@ -14,11 +14,7 @@ General Public License for more details.
|
|||
You should have received a copy of the GNU General Public License along with FitnessTrax. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
use crate::{
|
||||
components::TextEntry,
|
||||
types::{FormatOption, WeightFormatter},
|
||||
};
|
||||
use dimensioned::si;
|
||||
use crate::types::{FormatOption, WeightFormatter};
|
||||
use gtk::prelude::*;
|
||||
|
||||
pub struct WeightLabel {
|
||||
|
|
|
@ -53,6 +53,7 @@ impl Iterator for DayIterator {
|
|||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum FormatOption {
|
||||
Abbreviated,
|
||||
#[allow(unused)]
|
||||
Full,
|
||||
}
|
||||
|
||||
|
@ -60,6 +61,7 @@ pub enum FormatOption {
|
|||
pub struct TimeFormatter(chrono::NaiveTime);
|
||||
|
||||
impl TimeFormatter {
|
||||
#[allow(unused)]
|
||||
pub fn format(&self, option: FormatOption) -> String {
|
||||
match option {
|
||||
FormatOption::Abbreviated => self.0.format("%H:%M"),
|
||||
|
@ -68,6 +70,7 @@ impl TimeFormatter {
|
|||
.to_string()
|
||||
}
|
||||
|
||||
#[allow(unused)]
|
||||
pub fn parse(s: &str) -> Result<TimeFormatter, ParseError> {
|
||||
let parts = s
|
||||
.split(':')
|
||||
|
@ -104,6 +107,7 @@ impl From<chrono::NaiveTime> for TimeFormatter {
|
|||
pub struct WeightFormatter(si::Kilogram<f64>);
|
||||
|
||||
impl WeightFormatter {
|
||||
#[allow(unused)]
|
||||
pub fn format(&self, option: FormatOption) -> String {
|
||||
match option {
|
||||
FormatOption::Abbreviated => format!("{} kg", self.0.value_unsafe),
|
||||
|
@ -111,6 +115,7 @@ impl WeightFormatter {
|
|||
}
|
||||
}
|
||||
|
||||
#[allow(unused)]
|
||||
pub fn parse(s: &str) -> Result<WeightFormatter, ParseError> {
|
||||
s.parse::<f64>()
|
||||
.map(|w| WeightFormatter(w * si::KG))
|
||||
|
@ -149,6 +154,7 @@ impl From<si::Kilogram<f64>> for WeightFormatter {
|
|||
pub struct DistanceFormatter(si::Meter<f64>);
|
||||
|
||||
impl DistanceFormatter {
|
||||
#[allow(unused)]
|
||||
pub fn format(&self, option: FormatOption) -> String {
|
||||
match option {
|
||||
FormatOption::Abbreviated => format!("{} km", self.0.value_unsafe / 1000.),
|
||||
|
@ -156,6 +162,7 @@ impl DistanceFormatter {
|
|||
}
|
||||
}
|
||||
|
||||
#[allow(unused)]
|
||||
pub fn parse(s: &str) -> Result<DistanceFormatter, ParseError> {
|
||||
let value = s.parse::<f64>().map_err(|_| ParseError)?;
|
||||
Ok(DistanceFormatter(value * 1000. * si::M))
|
||||
|
@ -193,6 +200,7 @@ impl From<si::Meter<f64>> for DistanceFormatter {
|
|||
pub struct DurationFormatter(si::Second<f64>);
|
||||
|
||||
impl DurationFormatter {
|
||||
#[allow(unused)]
|
||||
pub fn format(&self, option: FormatOption) -> String {
|
||||
let (hours, minutes) = self.hours_and_minutes();
|
||||
let (h, m) = match option {
|
||||
|
@ -206,11 +214,13 @@ impl DurationFormatter {
|
|||
}
|
||||
}
|
||||
|
||||
#[allow(unused)]
|
||||
pub fn parse(s: &str) -> Result<DurationFormatter, ParseError> {
|
||||
let value = s.parse::<f64>().map_err(|_| ParseError)?;
|
||||
Ok(DurationFormatter(value * 60. * si::S))
|
||||
}
|
||||
|
||||
#[allow(unused)]
|
||||
fn hours_and_minutes(&self) -> (i64, i64) {
|
||||
let minutes: i64 = (self.0.value_unsafe / 60.).round() as i64;
|
||||
let hours: i64 = minutes / 60;
|
||||
|
|
|
@ -14,42 +14,45 @@ General Public License for more details.
|
|||
You should have received a copy of the GNU General Public License along with FitnessTrax. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
use crate::{
|
||||
app::App,
|
||||
types::{DistanceFormatter, DurationFormatter, WeightFormatter},
|
||||
};
|
||||
use crate::app::{ReadError, RecordProvider};
|
||||
use dimensioned::si;
|
||||
use emseries::{Record, RecordId, Recordable};
|
||||
use ft_core::{RecordType, TimeDistance, TraxRecord};
|
||||
use ft_core::{TimeDistance, TimeDistanceActivity, TraxRecord};
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
ops::Deref,
|
||||
sync::{Arc, RwLock},
|
||||
};
|
||||
|
||||
// These are actually a used imports. Clippy isn't detecting their use, probably because of complexity around the async trait macros.
|
||||
#[allow(unused_imports)]
|
||||
use crate::app::WriteError;
|
||||
#[allow(unused_imports)]
|
||||
use chrono::NaiveDate;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
enum RecordState<T: Clone + Recordable> {
|
||||
Original(Record<T>),
|
||||
New(Record<T>),
|
||||
Updated(Record<T>),
|
||||
#[allow(unused)]
|
||||
Deleted(Record<T>),
|
||||
}
|
||||
|
||||
impl<T: Clone + emseries::Recordable> RecordState<T> {
|
||||
#[allow(unused)]
|
||||
fn id(&self) -> Option<&RecordId> {
|
||||
fn exists(&self) -> bool {
|
||||
match self {
|
||||
RecordState::Original(ref r) => Some(&r.id),
|
||||
RecordState::New(ref r) => None,
|
||||
RecordState::Updated(ref r) => Some(&r.id),
|
||||
RecordState::Deleted(ref r) => Some(&r.id),
|
||||
RecordState::Original(_) => true,
|
||||
RecordState::New(_) => true,
|
||||
RecordState::Updated(_) => true,
|
||||
RecordState::Deleted(_) => false,
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(unused)]
|
||||
fn data(&self) -> Option<&Record<T>> {
|
||||
match self {
|
||||
RecordState::Original(ref r) => Some(r),
|
||||
RecordState::New(ref _r) => None,
|
||||
RecordState::New(ref r) => None,
|
||||
RecordState::Updated(ref r) => Some(r),
|
||||
RecordState::Deleted(ref r) => Some(r),
|
||||
}
|
||||
|
@ -92,9 +95,20 @@ impl<T: Clone + emseries::Recordable> Deref for RecordState<T> {
|
|||
}
|
||||
}
|
||||
|
||||
impl<T: Clone + emseries::Recordable> std::ops::DerefMut for RecordState<T> {
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
match self {
|
||||
RecordState::Original(ref mut r) => &mut r.data,
|
||||
RecordState::New(ref mut r) => &mut r.data,
|
||||
RecordState::Updated(ref mut r) => &mut r.data,
|
||||
RecordState::Deleted(ref mut r) => &mut r.data,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct DayDetailViewModel {
|
||||
app: App,
|
||||
provider: Arc<dyn RecordProvider>,
|
||||
pub date: chrono::NaiveDate,
|
||||
weight: Arc<RwLock<Option<RecordState<ft_core::Weight>>>>,
|
||||
steps: Arc<RwLock<Option<RecordState<ft_core::Steps>>>>,
|
||||
|
@ -102,37 +116,37 @@ pub struct DayDetailViewModel {
|
|||
}
|
||||
|
||||
impl DayDetailViewModel {
|
||||
pub async fn new(date: chrono::NaiveDate, app: App) -> Self {
|
||||
pub async fn new(
|
||||
date: chrono::NaiveDate,
|
||||
provider: impl RecordProvider + 'static,
|
||||
) -> Result<Self, ReadError> {
|
||||
let s = Self {
|
||||
app,
|
||||
provider: Arc::new(provider),
|
||||
date,
|
||||
|
||||
weight: Arc::new(RwLock::new(None)),
|
||||
steps: Arc::new(RwLock::new(None)),
|
||||
records: Arc::new(RwLock::new(HashMap::new())),
|
||||
};
|
||||
s.populate_records().await;
|
||||
s
|
||||
Ok(s)
|
||||
}
|
||||
|
||||
pub fn weight(&self) -> Option<WeightFormatter> {
|
||||
(*self.weight.read().unwrap())
|
||||
.as_ref()
|
||||
.map(|w| WeightFormatter::from(w.weight))
|
||||
pub fn weight(&self) -> Option<si::Kilogram<f64>> {
|
||||
(*self.weight.read().unwrap()).as_ref().map(|w| w.weight)
|
||||
}
|
||||
|
||||
pub fn set_weight(&self, new_weight: WeightFormatter) {
|
||||
pub fn set_weight(&self, new_weight: si::Kilogram<f64>) {
|
||||
let mut record = self.weight.write().unwrap();
|
||||
let new_record = match *record {
|
||||
Some(ref rstate) => rstate.clone().with_value(ft_core::Weight {
|
||||
date: self.date,
|
||||
weight: *new_weight,
|
||||
weight: new_weight,
|
||||
}),
|
||||
None => RecordState::New(Record {
|
||||
id: RecordId::default(),
|
||||
data: ft_core::Weight {
|
||||
date: self.date,
|
||||
weight: *new_weight,
|
||||
weight: new_weight,
|
||||
},
|
||||
}),
|
||||
};
|
||||
|
@ -161,40 +175,58 @@ impl DayDetailViewModel {
|
|||
*record = Some(new_record);
|
||||
}
|
||||
|
||||
pub fn biking_summary(&self) -> (DistanceFormatter, DurationFormatter) {
|
||||
self.records.read().unwrap().iter().fold(
|
||||
(DistanceFormatter::default(), DurationFormatter::default()),
|
||||
|(acc_distance, acc_duration), (_, record)| match record.data() {
|
||||
Some(Record {
|
||||
data:
|
||||
TraxRecord::BikeRide(TimeDistance {
|
||||
distance, duration, ..
|
||||
}),
|
||||
..
|
||||
}) => (
|
||||
distance
|
||||
.map(|distance| acc_distance + DistanceFormatter::from(distance))
|
||||
.unwrap_or(acc_distance),
|
||||
duration
|
||||
.map(|duration| acc_duration + DurationFormatter::from(duration))
|
||||
.unwrap_or(acc_duration),
|
||||
),
|
||||
|
||||
_ => (acc_distance, acc_duration),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
pub fn new_record(&self, type_: RecordType) -> Record<TraxRecord> {
|
||||
let new_record = Record {
|
||||
id: RecordId::default(),
|
||||
data: ft_core::TraxRecord::new(type_, chrono::Local::now().into()),
|
||||
pub fn new_time_distance(&self, activity: TimeDistanceActivity) -> Record<TimeDistance> {
|
||||
let id = RecordId::default();
|
||||
let workout = TimeDistance {
|
||||
datetime: chrono::Local::now().into(),
|
||||
activity,
|
||||
distance: None,
|
||||
duration: None,
|
||||
comments: None,
|
||||
};
|
||||
let tr = TraxRecord::from(workout.clone());
|
||||
self.records
|
||||
.write()
|
||||
.unwrap()
|
||||
.insert(new_record.id, RecordState::New(new_record.clone()));
|
||||
new_record
|
||||
.insert(id, RecordState::New(Record { id, data: tr }));
|
||||
Record { id, data: workout }
|
||||
}
|
||||
|
||||
pub fn time_distance_records(&self) -> Vec<Record<TimeDistance>> {
|
||||
self.records
|
||||
.read()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter(|(_, record)| record.exists())
|
||||
.filter_map(|(id, record_state)| match **record_state {
|
||||
TraxRecord::TimeDistance(ref workout) => Some(Record {
|
||||
id: *id,
|
||||
data: workout.clone(),
|
||||
}),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn time_distance_summary(
|
||||
&self,
|
||||
activity: TimeDistanceActivity,
|
||||
) -> (si::Meter<f64>, si::Second<f64>) {
|
||||
self.time_distance_records()
|
||||
.into_iter()
|
||||
.filter(|rec| rec.data.activity == activity)
|
||||
.fold(
|
||||
(0. * si::M, 0. * si::S),
|
||||
|(distance, duration), workout| match (workout.data.distance, workout.data.duration)
|
||||
{
|
||||
(Some(distance_), Some(duration_)) => {
|
||||
(distance + distance_, duration + duration_)
|
||||
}
|
||||
(Some(distance_), None) => (distance + distance_, duration),
|
||||
(None, Some(duration_)) => (distance, duration + duration_),
|
||||
(None, None) => (distance, duration),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
pub fn update_record(&self, update: Record<TraxRecord>) {
|
||||
|
@ -213,19 +245,47 @@ impl DayDetailViewModel {
|
|||
.collect::<Vec<Record<TraxRecord>>>()
|
||||
}
|
||||
|
||||
pub fn save(&self) -> glib::JoinHandle<()> {
|
||||
glib::spawn_future({
|
||||
#[allow(unused)]
|
||||
fn get_record(&self, id: &RecordId) -> Option<Record<TraxRecord>> {
|
||||
let record_set = self.records.read().unwrap();
|
||||
record_set.get(id).map(|record| Record {
|
||||
id: *id,
|
||||
data: (**record).clone(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn remove_record(&self, id: RecordId) {
|
||||
let mut record_set = self.records.write().unwrap();
|
||||
let updated_record = match record_set.remove(&id) {
|
||||
Some(RecordState::Original(r)) => Some(RecordState::Deleted(r)),
|
||||
Some(RecordState::New(_)) => None,
|
||||
Some(RecordState::Updated(r)) => Some(RecordState::Deleted(r)),
|
||||
Some(RecordState::Deleted(r)) => Some(RecordState::Deleted(r)),
|
||||
None => None,
|
||||
};
|
||||
if let Some(updated_record) = updated_record {
|
||||
record_set.insert(id, updated_record);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn save(&self) {
|
||||
let s = self.clone();
|
||||
async move {
|
||||
let weight_record = s.weight.read().unwrap().clone();
|
||||
glib::spawn_future(async move { s.async_save().await });
|
||||
}
|
||||
|
||||
pub async fn async_save(&self) {
|
||||
let weight_record = self.weight.read().unwrap().clone();
|
||||
match weight_record {
|
||||
Some(RecordState::New(Record { data, .. })) => {
|
||||
let _ = s.app.put_record(TraxRecord::Weight(data)).await;
|
||||
Some(RecordState::New(data)) => {
|
||||
let _ = self
|
||||
.provider
|
||||
.put_record(TraxRecord::Weight(data.data))
|
||||
.await;
|
||||
}
|
||||
Some(RecordState::Original(_)) => {}
|
||||
Some(RecordState::Updated(weight)) => {
|
||||
let _ = s
|
||||
.app
|
||||
let _ = self
|
||||
.provider
|
||||
.update_record(Record {
|
||||
id: weight.id,
|
||||
data: TraxRecord::Weight(weight.data),
|
||||
|
@ -236,15 +296,15 @@ impl DayDetailViewModel {
|
|||
None => {}
|
||||
}
|
||||
|
||||
let steps_record = s.steps.read().unwrap().clone();
|
||||
let steps_record = self.steps.read().unwrap().clone();
|
||||
match steps_record {
|
||||
Some(RecordState::New(Record { data, .. })) => {
|
||||
let _ = s.app.put_record(TraxRecord::Steps(data)).await;
|
||||
Some(RecordState::New(data)) => {
|
||||
let _ = self.provider.put_record(TraxRecord::Steps(data.data)).await;
|
||||
}
|
||||
Some(RecordState::Original(_)) => {}
|
||||
Some(RecordState::Updated(steps)) => {
|
||||
let _ = s
|
||||
.app
|
||||
let _ = self
|
||||
.provider
|
||||
.update_record(Record {
|
||||
id: steps.id,
|
||||
data: TraxRecord::Steps(steps.data),
|
||||
|
@ -255,7 +315,7 @@ impl DayDetailViewModel {
|
|||
None => {}
|
||||
}
|
||||
|
||||
let records = s
|
||||
let records = self
|
||||
.records
|
||||
.write()
|
||||
.unwrap()
|
||||
|
@ -264,34 +324,29 @@ impl DayDetailViewModel {
|
|||
.collect::<Vec<RecordState<TraxRecord>>>();
|
||||
|
||||
for record in records {
|
||||
println!("saving record: {:?}", record);
|
||||
match record {
|
||||
RecordState::New(Record { data, .. }) => {
|
||||
let _ = s.app.put_record(data).await;
|
||||
RecordState::New(data) => {
|
||||
let _ = self.provider.put_record(data.data).await;
|
||||
}
|
||||
RecordState::Original(_) => {}
|
||||
RecordState::Updated(r) => {
|
||||
let _ = s.app.update_record(r.clone()).await;
|
||||
let _ = self.provider.update_record(r.clone()).await;
|
||||
}
|
||||
RecordState::Deleted(_) => unimplemented!(),
|
||||
RecordState::Deleted(r) => {
|
||||
let _ = self.provider.delete_record(r.id).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
self.populate_records().await;
|
||||
}
|
||||
|
||||
s.populate_records().await;
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub fn revert(&self) {
|
||||
glib::spawn_future({
|
||||
let s = self.clone();
|
||||
async move {
|
||||
s.populate_records().await;
|
||||
}
|
||||
});
|
||||
pub async fn revert(&self) {
|
||||
self.populate_records().await;
|
||||
}
|
||||
|
||||
async fn populate_records(&self) {
|
||||
let records = self.app.records(self.date, self.date).await.unwrap();
|
||||
let records = self.provider.records(self.date, self.date).await.unwrap();
|
||||
|
||||
let (weight_records, records): (Vec<Record<TraxRecord>>, Vec<Record<TraxRecord>>) =
|
||||
records.into_iter().partition(|r| r.data.is_weight());
|
||||
|
@ -321,30 +376,270 @@ impl DayDetailViewModel {
|
|||
}
|
||||
}
|
||||
|
||||
/*
|
||||
struct SavedRecordIterator<'a> {
|
||||
read_lock: RwLockReadGuard<'a, HashMap<RecordId, RecordState<TraxRecord>>>,
|
||||
iter: Box<dyn Iterator<Item = &'a Record<TraxRecord>> + 'a>,
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
use async_trait::async_trait;
|
||||
use chrono::{DateTime, FixedOffset};
|
||||
use dimensioned::si;
|
||||
use emseries::Record;
|
||||
|
||||
impl<'a> SavedRecordIterator<'a> {
|
||||
fn new(records: Arc<RwLock<HashMap<RecordId, RecordState<TraxRecord>>>>) -> Self {
|
||||
let read_lock = records.read().unwrap();
|
||||
let iter = read_lock
|
||||
.iter()
|
||||
.map(|(_, record_state)| record_state.data())
|
||||
.filter_map(|r| r);
|
||||
#[derive(Clone, Debug)]
|
||||
struct MockProvider {
|
||||
records: Arc<RwLock<HashMap<RecordId, Record<TraxRecord>>>>,
|
||||
|
||||
put_records: Arc<RwLock<Vec<Record<TraxRecord>>>>,
|
||||
updated_records: Arc<RwLock<Vec<Record<TraxRecord>>>>,
|
||||
deleted_records: Arc<RwLock<Vec<RecordId>>>,
|
||||
}
|
||||
|
||||
impl MockProvider {
|
||||
fn new(records: Vec<Record<TraxRecord>>) -> Self {
|
||||
let record_map = records
|
||||
.into_iter()
|
||||
.map(|r| (r.id, r))
|
||||
.collect::<HashMap<RecordId, Record<TraxRecord>>>();
|
||||
Self {
|
||||
read_lock,
|
||||
iter: Box::new(iter),
|
||||
records: Arc::new(RwLock::new(record_map)),
|
||||
put_records: Arc::new(RwLock::new(vec![])),
|
||||
updated_records: Arc::new(RwLock::new(vec![])),
|
||||
deleted_records: Arc::new(RwLock::new(vec![])),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Iterator for SavedRecordIterator<'a> {
|
||||
type Item = &'a Record<TraxRecord>;
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
None
|
||||
#[async_trait]
|
||||
impl RecordProvider for MockProvider {
|
||||
async fn records(
|
||||
&self,
|
||||
start: NaiveDate,
|
||||
end: NaiveDate,
|
||||
) -> Result<Vec<Record<TraxRecord>>, ReadError> {
|
||||
let start = emseries::Timestamp::Date(start);
|
||||
let end = emseries::Timestamp::Date(end);
|
||||
Ok(self
|
||||
.records
|
||||
.read()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|(_, r)| r)
|
||||
.filter(|r| r.timestamp() >= start && r.timestamp() <= end)
|
||||
.cloned()
|
||||
.collect::<Vec<Record<TraxRecord>>>())
|
||||
}
|
||||
|
||||
async fn put_record(&self, record: TraxRecord) -> Result<RecordId, WriteError> {
|
||||
let id = RecordId::default();
|
||||
let record = Record {
|
||||
id: id,
|
||||
data: record,
|
||||
};
|
||||
self.put_records.write().unwrap().push(record.clone());
|
||||
self.records.write().unwrap().insert(id, record);
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
async fn update_record(&self, record: Record<TraxRecord>) -> Result<(), WriteError> {
|
||||
println!("updated record: {:?}", record);
|
||||
self.updated_records.write().unwrap().push(record.clone());
|
||||
self.records.write().unwrap().insert(record.id, record);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn delete_record(&self, id: RecordId) -> Result<(), WriteError> {
|
||||
self.deleted_records.write().unwrap().push(id);
|
||||
let _ = self.records.write().unwrap().remove(&id);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
async fn create_empty_view_model() -> (DayDetailViewModel, MockProvider) {
|
||||
let provider = MockProvider::new(vec![]);
|
||||
|
||||
let oct_13 = chrono::NaiveDate::from_ymd_opt(2023, 10, 13).unwrap();
|
||||
let model = DayDetailViewModel::new(oct_13, provider.clone())
|
||||
.await
|
||||
.unwrap();
|
||||
(model, provider)
|
||||
}
|
||||
|
||||
async fn create_view_model() -> (DayDetailViewModel, MockProvider) {
|
||||
let oct_12 = chrono::NaiveDate::from_ymd_opt(2023, 10, 12).unwrap();
|
||||
let oct_13 = chrono::NaiveDate::from_ymd_opt(2023, 10, 13).unwrap();
|
||||
let oct_13_am: DateTime<FixedOffset> = oct_13
|
||||
.clone()
|
||||
.and_hms_opt(3, 28, 0)
|
||||
.unwrap()
|
||||
.and_utc()
|
||||
.with_timezone(&FixedOffset::east_opt(5 * 3600).unwrap());
|
||||
let provider = MockProvider::new(vec![
|
||||
Record {
|
||||
id: RecordId::default(),
|
||||
data: TraxRecord::Weight(ft_core::Weight {
|
||||
date: oct_12,
|
||||
weight: 93. * si::KG,
|
||||
}),
|
||||
},
|
||||
Record {
|
||||
id: RecordId::default(),
|
||||
data: TraxRecord::Weight(ft_core::Weight {
|
||||
date: oct_13,
|
||||
weight: 95. * si::KG,
|
||||
}),
|
||||
},
|
||||
Record {
|
||||
id: RecordId::default(),
|
||||
data: TraxRecord::Steps(ft_core::Steps {
|
||||
date: oct_13,
|
||||
count: 2500,
|
||||
}),
|
||||
},
|
||||
Record {
|
||||
id: RecordId::default(),
|
||||
data: TraxRecord::TimeDistance(ft_core::TimeDistance {
|
||||
datetime: oct_13_am.clone(),
|
||||
activity: TimeDistanceActivity::BikeRide,
|
||||
distance: Some(15000. * si::M),
|
||||
duration: Some(3600. * si::S),
|
||||
comments: Some("somecomments present".to_owned()),
|
||||
}),
|
||||
},
|
||||
]);
|
||||
let model = DayDetailViewModel::new(oct_13, provider.clone())
|
||||
.await
|
||||
.unwrap();
|
||||
(model, provider)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn it_honors_only_the_first_weight_and_step_record() {
|
||||
let (view_model, _provider) = create_view_model().await;
|
||||
assert_eq!(view_model.weight(), Some(95. * si::KG));
|
||||
assert_eq!(view_model.steps(), Some(2500));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn it_can_create_a_weight_and_stepcount() {
|
||||
let (view_model, provider) = create_empty_view_model().await;
|
||||
assert_eq!(view_model.weight(), None);
|
||||
assert_eq!(view_model.steps(), None);
|
||||
|
||||
view_model.set_weight(95. * si::KG);
|
||||
view_model.set_steps(250);
|
||||
|
||||
assert_eq!(view_model.weight(), Some(95. * si::KG));
|
||||
assert_eq!(view_model.steps(), Some(250));
|
||||
|
||||
view_model.set_weight(93. * si::KG);
|
||||
view_model.set_steps(255);
|
||||
|
||||
assert_eq!(view_model.weight(), Some(93. * si::KG));
|
||||
assert_eq!(view_model.steps(), Some(255));
|
||||
|
||||
view_model.async_save().await;
|
||||
|
||||
println!("provider: {:?}", provider);
|
||||
assert_eq!(provider.put_records.read().unwrap().len(), 2);
|
||||
assert_eq!(provider.updated_records.read().unwrap().len(), 0);
|
||||
assert_eq!(provider.deleted_records.read().unwrap().len(), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn it_can_construct_new_records() {
|
||||
let (view_model, provider) = create_empty_view_model().await;
|
||||
assert_eq!(
|
||||
view_model.time_distance_summary(TimeDistanceActivity::BikeRide),
|
||||
(0. * si::M, 0. * si::S)
|
||||
);
|
||||
|
||||
let mut record = view_model.new_time_distance(TimeDistanceActivity::BikeRide);
|
||||
record.data.duration = Some(60. * si::S);
|
||||
view_model.async_save().await;
|
||||
|
||||
assert_eq!(provider.put_records.read().unwrap().len(), 1);
|
||||
assert_eq!(provider.updated_records.read().unwrap().len(), 0);
|
||||
assert_eq!(provider.deleted_records.read().unwrap().len(), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn it_can_update_a_new_record_before_saving() {
|
||||
let (view_model, provider) = create_empty_view_model().await;
|
||||
assert_eq!(
|
||||
view_model.time_distance_summary(TimeDistanceActivity::BikeRide),
|
||||
(0. * si::M, 0. * si::S)
|
||||
);
|
||||
|
||||
let mut record = view_model.new_time_distance(TimeDistanceActivity::BikeRide);
|
||||
record.data.duration = Some(60. * si::S);
|
||||
let record = record.map(TraxRecord::TimeDistance);
|
||||
view_model.update_record(record.clone());
|
||||
assert_eq!(view_model.get_record(&record.id), Some(record));
|
||||
assert_eq!(
|
||||
view_model.time_distance_summary(TimeDistanceActivity::BikeRide),
|
||||
(0. * si::M, 60. * si::S)
|
||||
);
|
||||
assert_eq!(
|
||||
view_model.time_distance_summary(TimeDistanceActivity::Running),
|
||||
(0. * si::M, 0. * si::S)
|
||||
);
|
||||
view_model.async_save().await;
|
||||
|
||||
assert_eq!(provider.put_records.read().unwrap().len(), 1);
|
||||
assert_eq!(provider.updated_records.read().unwrap().len(), 0);
|
||||
assert_eq!(provider.deleted_records.read().unwrap().len(), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn it_can_update_an_existing_record() {
|
||||
let (view_model, provider) = create_view_model().await;
|
||||
let mut workout = view_model.time_distance_records().first().cloned().unwrap();
|
||||
|
||||
workout.data.duration = Some(1800. * si::S);
|
||||
view_model.update_record(workout.map(TraxRecord::TimeDistance));
|
||||
|
||||
assert_eq!(
|
||||
view_model.time_distance_summary(TimeDistanceActivity::BikeRide),
|
||||
(15000. * si::M, 1800. * si::S)
|
||||
);
|
||||
|
||||
view_model.async_save().await;
|
||||
|
||||
assert_eq!(provider.put_records.read().unwrap().len(), 0);
|
||||
assert_eq!(provider.updated_records.read().unwrap().len(), 1);
|
||||
assert_eq!(provider.deleted_records.read().unwrap().len(), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn it_can_remove_a_new_record() {
|
||||
let (view_model, provider) = create_empty_view_model().await;
|
||||
assert_eq!(
|
||||
view_model.time_distance_summary(TimeDistanceActivity::BikeRide),
|
||||
(0. * si::M, 0. * si::S)
|
||||
);
|
||||
|
||||
let record = view_model.new_time_distance(TimeDistanceActivity::BikeRide);
|
||||
view_model.remove_record(record.id);
|
||||
view_model.save();
|
||||
|
||||
assert_eq!(provider.put_records.read().unwrap().len(), 0);
|
||||
assert_eq!(provider.updated_records.read().unwrap().len(), 0);
|
||||
assert_eq!(provider.deleted_records.read().unwrap().len(), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn it_can_delete_an_existing_record() {
|
||||
let (view_model, provider) = create_view_model().await;
|
||||
let workout = view_model.time_distance_records().first().cloned().unwrap();
|
||||
|
||||
view_model.remove_record(workout.id);
|
||||
assert_eq!(
|
||||
view_model.time_distance_summary(TimeDistanceActivity::BikeRide),
|
||||
(0. * si::M, 0. * si::S)
|
||||
);
|
||||
view_model.async_save().await;
|
||||
|
||||
assert_eq!(provider.put_records.read().unwrap().len(), 0);
|
||||
assert_eq!(provider.updated_records.read().unwrap().len(), 0);
|
||||
assert_eq!(provider.deleted_records.read().unwrap().len(), 1);
|
||||
}
|
||||
}
|
||||
*/
|
||||
|
|
|
@ -18,8 +18,6 @@ use crate::{
|
|||
app::App, components::DaySummary, types::DayInterval, view_models::DayDetailViewModel,
|
||||
};
|
||||
|
||||
use emseries::Record;
|
||||
use ft_core::TraxRecord;
|
||||
use glib::Object;
|
||||
use gtk::{prelude::*, subclass::prelude::*};
|
||||
use std::{cell::RefCell, rc::Rc};
|
||||
|
@ -76,7 +74,9 @@ impl ObjectSubclass for HistoricalViewPrivate {
|
|||
|
||||
if let Some(app) = app.borrow().clone() {
|
||||
glib::spawn_future_local(async move {
|
||||
let view_model = DayDetailViewModel::new(date.date(), app.clone()).await;
|
||||
let view_model = DayDetailViewModel::new(date.date(), app.clone())
|
||||
.await
|
||||
.unwrap();
|
||||
summary.set_data(view_model);
|
||||
});
|
||||
}
|
||||
|
@ -98,7 +98,7 @@ glib::wrapper! {
|
|||
impl HistoricalView {
|
||||
pub fn new<SelectFn>(app: App, interval: DayInterval, on_select_day: Rc<SelectFn>) -> Self
|
||||
where
|
||||
SelectFn: Fn(chrono::NaiveDate, Vec<Record<TraxRecord>>) + 'static,
|
||||
SelectFn: Fn(chrono::NaiveDate) + 'static,
|
||||
{
|
||||
let s: Self = Object::builder().build();
|
||||
s.set_orientation(gtk::Orientation::Vertical);
|
||||
|
@ -118,7 +118,7 @@ impl HistoricalView {
|
|||
// This gets triggered whenever the user clicks on an item on the list.
|
||||
let item = s.model().unwrap().item(idx).unwrap();
|
||||
let date = item.downcast_ref::<Date>().unwrap();
|
||||
on_select_day(date.date(), vec![]);
|
||||
on_select_day(date.date());
|
||||
}
|
||||
});
|
||||
|
||||
|
@ -127,6 +127,14 @@ impl HistoricalView {
|
|||
s
|
||||
}
|
||||
|
||||
pub fn set_interval(&self, interval: DayInterval) {
|
||||
let mut model = gio::ListStore::new::<Date>();
|
||||
model.extend(interval.days().map(Date::new));
|
||||
self.imp()
|
||||
.list_view
|
||||
.set_model(Some(>k::NoSelection::new(Some(model))));
|
||||
}
|
||||
|
||||
pub fn time_window(&self) -> DayInterval {
|
||||
self.imp().time_window.borrow().clone()
|
||||
}
|
||||
|
|
|
@ -30,6 +30,7 @@ pub use welcome_view::WelcomeView;
|
|||
|
||||
pub enum View {
|
||||
Placeholder(PlaceholderView),
|
||||
#[allow(unused)]
|
||||
Welcome(WelcomeView),
|
||||
Historical(HistoricalView),
|
||||
}
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
mod legacy;
|
||||
|
||||
mod types;
|
||||
pub use types::{RecordType, Steps, TimeDistance, TraxRecord, Weight};
|
||||
pub use types::{Steps, TimeDistance, TimeDistanceActivity, TraxRecord, Weight};
|
||||
|
|
|
@ -33,6 +33,15 @@ impl Recordable for Steps {
|
|||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub enum TimeDistanceActivity {
|
||||
BikeRide,
|
||||
Running,
|
||||
Rowing,
|
||||
Swimming,
|
||||
Walking,
|
||||
}
|
||||
|
||||
/// TimeDistance represents workouts characterized by a duration and a distance travelled. These
|
||||
/// sorts of workouts can occur many times a day, depending on how one records things. I might
|
||||
/// record a single 30-km workout if I go on a long-distanec ride. Or I might record multiple 5km
|
||||
|
@ -48,6 +57,8 @@ pub struct TimeDistance {
|
|||
/// in the database, but we can still get a Naive Date from the DateTime, which will still read
|
||||
/// as the original day.
|
||||
pub datetime: DateTime<FixedOffset>,
|
||||
/// The activity
|
||||
pub activity: TimeDistanceActivity,
|
||||
/// The distance travelled. This is optional because such a workout makes sense even without
|
||||
/// the distance.
|
||||
pub distance: Option<si::Meter<f64>>,
|
||||
|
@ -57,14 +68,13 @@ pub struct TimeDistance {
|
|||
pub comments: Option<String>,
|
||||
}
|
||||
|
||||
impl TimeDistance {
|
||||
pub fn new(time: DateTime<FixedOffset>) -> Self {
|
||||
Self {
|
||||
datetime: time,
|
||||
distance: None,
|
||||
duration: None,
|
||||
comments: None,
|
||||
impl Recordable for TimeDistance {
|
||||
fn timestamp(&self) -> Timestamp {
|
||||
Timestamp::DateTime(self.datetime)
|
||||
}
|
||||
|
||||
fn tags(&self) -> Vec<String> {
|
||||
vec![]
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -86,54 +96,15 @@ impl Recordable for Weight {
|
|||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum RecordType {
|
||||
BikeRide,
|
||||
Row,
|
||||
Run,
|
||||
Steps,
|
||||
Swim,
|
||||
Walk,
|
||||
Weight,
|
||||
}
|
||||
|
||||
/// The unified data structure for all records that are part of the app.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub enum TraxRecord {
|
||||
BikeRide(TimeDistance),
|
||||
Row(TimeDistance),
|
||||
Run(TimeDistance),
|
||||
TimeDistance(TimeDistance),
|
||||
Steps(Steps),
|
||||
Swim(TimeDistance),
|
||||
Walk(TimeDistance),
|
||||
Weight(Weight),
|
||||
}
|
||||
|
||||
impl TraxRecord {
|
||||
pub fn new(type_: RecordType, time: DateTime<FixedOffset>) -> TraxRecord {
|
||||
match type_ {
|
||||
RecordType::BikeRide => TraxRecord::BikeRide(TimeDistance::new(time)),
|
||||
RecordType::Row => TraxRecord::Row(TimeDistance::new(time)),
|
||||
RecordType::Run => TraxRecord::Run(TimeDistance::new(time)),
|
||||
RecordType::Steps => unimplemented!(),
|
||||
RecordType::Swim => unimplemented!(),
|
||||
RecordType::Walk => TraxRecord::Walk(TimeDistance::new(time)),
|
||||
RecordType::Weight => unimplemented!(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn workout_type(&self) -> RecordType {
|
||||
match self {
|
||||
TraxRecord::BikeRide(_) => RecordType::BikeRide,
|
||||
TraxRecord::Row(_) => RecordType::Row,
|
||||
TraxRecord::Run(_) => RecordType::Run,
|
||||
TraxRecord::Steps(_) => RecordType::Steps,
|
||||
TraxRecord::Swim(_) => RecordType::Swim,
|
||||
TraxRecord::Walk(_) => RecordType::Walk,
|
||||
TraxRecord::Weight(_) => RecordType::Weight,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_weight(&self) -> bool {
|
||||
matches!(self, TraxRecord::Weight(_))
|
||||
}
|
||||
|
@ -142,24 +113,34 @@ impl TraxRecord {
|
|||
matches!(self, TraxRecord::Steps(_))
|
||||
}
|
||||
|
||||
pub fn is_bike_ride(&self) -> bool {
|
||||
matches!(self, TraxRecord::BikeRide(_))
|
||||
}
|
||||
|
||||
pub fn is_run(&self) -> bool {
|
||||
matches!(self, TraxRecord::Run(_))
|
||||
pub fn is_time_distance(&self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
TraxRecord::TimeDistance(TimeDistance {
|
||||
activity: TimeDistanceActivity::BikeRide,
|
||||
..
|
||||
}) | TraxRecord::TimeDistance(TimeDistance {
|
||||
activity: TimeDistanceActivity::Running,
|
||||
..
|
||||
}) | TraxRecord::TimeDistance(TimeDistance {
|
||||
activity: TimeDistanceActivity::Rowing,
|
||||
..
|
||||
}) | TraxRecord::TimeDistance(TimeDistance {
|
||||
activity: TimeDistanceActivity::Swimming,
|
||||
..
|
||||
}) | TraxRecord::TimeDistance(TimeDistance {
|
||||
activity: TimeDistanceActivity::Walking,
|
||||
..
|
||||
})
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl Recordable for TraxRecord {
|
||||
fn timestamp(&self) -> Timestamp {
|
||||
match self {
|
||||
TraxRecord::BikeRide(rec) => Timestamp::DateTime(rec.datetime),
|
||||
TraxRecord::Row(rec) => Timestamp::DateTime(rec.datetime),
|
||||
TraxRecord::Run(rec) => Timestamp::DateTime(rec.datetime),
|
||||
TraxRecord::TimeDistance(rec) => Timestamp::DateTime(rec.datetime),
|
||||
TraxRecord::Steps(rec) => rec.timestamp(),
|
||||
TraxRecord::Swim(rec) => Timestamp::DateTime(rec.datetime),
|
||||
TraxRecord::Walk(rec) => Timestamp::DateTime(rec.datetime),
|
||||
TraxRecord::Weight(rec) => rec.timestamp(),
|
||||
}
|
||||
}
|
||||
|
@ -169,6 +150,12 @@ impl Recordable for TraxRecord {
|
|||
}
|
||||
}
|
||||
|
||||
impl From<TimeDistance> for TraxRecord {
|
||||
fn from(td: TimeDistance) -> Self {
|
||||
Self::TimeDistance(td)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
|
|
Loading…
Reference in New Issue