use std::fmt;
use crate::types::path;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Method {
Get,
Post,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Endpoint {
CreatePayment,
QueryOrder,
QueryOrders,
Refund,
QueryMerchant,
QuerySettlements,
}
impl Endpoint {
pub fn path(self) -> &'static str {
match self {
Self::CreatePayment => path::MAPI,
_ => path::API,
}
}
pub fn act(self) -> Option<&'static str> {
match self {
Self::CreatePayment => None,
Self::QueryOrder => Some("order"),
Self::QueryOrders => Some("orders"),
Self::Refund => Some("refund"),
Self::QueryMerchant => Some("query"),
Self::QuerySettlements => Some("settle"),
}
}
pub fn is_success_code(self, code: i32) -> bool {
match self {
Self::Refund => matches!(code, 0 | 1),
_ => code == 1,
}
}
pub fn label(self) -> &'static str {
match self {
Self::CreatePayment => "mapi.php",
Self::QueryOrder => "api.php?act=order",
Self::QueryOrders => "api.php?act=orders",
Self::Refund => "api.php?act=refund",
Self::QueryMerchant => "api.php?act=query",
Self::QuerySettlements => "api.php?act=settle",
}
}
pub(crate) fn method(self) -> Method {
match self {
Self::CreatePayment | Self::Refund => Method::Post,
_ => Method::Get,
}
}
}
impl fmt::Display for Endpoint {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.label())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn refund_accepts_official_zero_and_fork_one() {
assert!(Endpoint::Refund.is_success_code(0));
assert!(Endpoint::Refund.is_success_code(1));
assert!(!Endpoint::Refund.is_success_code(-1));
assert!(!Endpoint::QueryOrder.is_success_code(0));
assert!(Endpoint::QueryOrder.is_success_code(1));
}
#[test]
fn paths_methods_and_acts() {
assert_eq!(Endpoint::CreatePayment.path(), "/mapi.php");
assert_eq!(Endpoint::CreatePayment.act(), None);
assert_eq!(Endpoint::CreatePayment.method(), Method::Post);
assert_eq!(Endpoint::Refund.method(), Method::Post);
assert_eq!(Endpoint::QueryOrders.method(), Method::Get);
assert_eq!(Endpoint::QuerySettlements.act(), Some("settle"));
assert_eq!(Endpoint::QueryMerchant.to_string(), "api.php?act=query");
}
}