CREATE_BET_API #9

Merged
emre.kartal merged 3 commits from CREATE_BET_API into master 1 year ago

@ -9,8 +9,6 @@ import SwiftUI
import DependencyInjection import DependencyInjection
import Model import Model
import ViewModel import ViewModel
import StubLib
import Api
@main @main
struct AllInApp: App { struct AllInApp: App {
@ -20,7 +18,6 @@ struct AllInApp: App {
init() { init() {
DI.addSingleton(IAuthService.self, AuthService()) DI.addSingleton(IAuthService.self, AuthService())
DI.addSingleton(ManagerVM.self, ManagerVM(withModel: Manager(withBetDataManager: BetStubManager(), withUserDataManager: UserApiManager())))
} }
var body: some Scene { var body: some Scene {

@ -7,6 +7,10 @@
import Foundation import Foundation
import Model import Model
import ViewModel
import DependencyInjection
import Api
import StubLib
class AuthService: IAuthService { class AuthService: IAuthService {
@ -35,6 +39,8 @@ class AuthService: IAuthService {
if status != 200 { if status != 200 {
completion(status) completion(status)
AppStateContainer.shared.authenticationRefresh = nil; AppStateContainer.shared.authenticationRefresh = nil;
} else {
self.initManagerVM(token: token)
} }
} }
} }
@ -52,7 +58,7 @@ class AuthService: IAuthService {
request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let json = [ let json = [
"email": email, "email": email.lowercased(),
"username": username.lowercased(), "username": username.lowercased(),
"password": password, "password": password,
"nbCoins": "0" "nbCoins": "0"
@ -71,6 +77,8 @@ class AuthService: IAuthService {
if status != 200 { if status != 200 {
completion(status) completion(status)
AppStateContainer.shared.authenticationRefresh = nil; AppStateContainer.shared.authenticationRefresh = nil;
} else {
self.initManagerVM(token: token)
} }
} }
} }
@ -87,8 +95,6 @@ class AuthService: IAuthService {
return return
} }
print(token)
let url = URL(string: Config.allInApi + "users/token")! let url = URL(string: Config.allInApi + "users/token")!
var request = URLRequest(url: url) var request = URLRequest(url: url)
request.httpMethod = "GET" request.httpMethod = "GET"
@ -103,6 +109,7 @@ class AuthService: IAuthService {
let user = User.mapUser(from: userJson) { let user = User.mapUser(from: userJson) {
AppStateContainer.shared.user = user AppStateContainer.shared.user = user
AppStateContainer.shared.loggedState.connectedUser = true AppStateContainer.shared.loggedState.connectedUser = true
self.initManagerVM(token: token)
} }
} else { } else {
AppStateContainer.shared.authenticationRefresh = nil AppStateContainer.shared.authenticationRefresh = nil
@ -136,5 +143,8 @@ class AuthService: IAuthService {
}.resume() }.resume()
} }
private func initManagerVM(token: String) {
DependencyInjection.shared.addSingleton(ManagerVM.self, ManagerVM(withModel: Manager(withBetDataManager: BetStubManager(), withUserDataManager: UserApiManager(withUserToken: token))))
}
} }

@ -18,6 +18,7 @@ class CreationBetViewModel: ObservableObject {
@Published var isPublic = true @Published var isPublic = true
@Published var endRegisterDate = Date() @Published var endRegisterDate = Date()
@Published var endBetDate = Date() @Published var endBetDate = Date()
@Published var betAdded = false
@Published var themeFieldError: String? @Published var themeFieldError: String?
@Published var descriptionFieldError: String? @Published var descriptionFieldError: String?
@ -35,6 +36,8 @@ class CreationBetViewModel: ObservableObject {
if let user = AppStateContainer.shared.user { if let user = AppStateContainer.shared.user {
manager.addBet(theme: theme, description: description, endRegister: endRegisterDate, endBet: endBetDate, isPublic: isPublic, creator: user) manager.addBet(theme: theme, description: description, endRegister: endRegisterDate, endBet: endBetDate, isPublic: isPublic, creator: user)
} }
betAdded = true
} }
func checkAndSetError(forTheme checkTheme: Bool, forDescription checkDescription: Bool, forEndRegisterDate checkEndRegisterDate: Bool, forEndBetDate checkEndBetDate: Bool) -> Bool { func checkAndSetError(forTheme checkTheme: Bool, forDescription checkDescription: Bool, forEndRegisterDate checkEndRegisterDate: Bool, forEndBetDate checkEndBetDate: Bool) -> Bool {

@ -71,6 +71,9 @@ struct CreationBetView: View {
var body: some View { var body: some View {
VStack(alignment: .center, spacing: 0) { VStack(alignment: .center, spacing: 0) {
NavigationLink(destination: MainView(page: "Bet").navigationBarBackButtonHidden(true), isActive: $viewModel.betAdded) {
EmptyView()
}
TopBar(showMenu: self.$showMenu) TopBar(showMenu: self.$showMenu)
TabView(selection: $selectedTab) { TabView(selection: $selectedTab) {
@ -113,7 +116,7 @@ struct CreationBetView: View {
.frame(height: 40) .frame(height: 40)
) )
.frame(width: 350, height: 40) .frame(width: 350, height: 40)
.foregroundColor(.black) .foregroundColor(AllInColors.primaryTextColor)
.overlay( .overlay(
RoundedRectangle(cornerRadius: 10, style: .continuous) RoundedRectangle(cornerRadius: 10, style: .continuous)
.stroke(AllInColors.delimiterGrey, lineWidth: 1) .stroke(AllInColors.delimiterGrey, lineWidth: 1)
@ -155,7 +158,7 @@ struct CreationBetView: View {
.frame(height: 110) .frame(height: 110)
) )
.frame(width: 350, height: 110) .frame(width: 350, height: 110)
.foregroundColor(.black) .foregroundColor(AllInColors.primaryTextColor)
.overlay( .overlay(
RoundedRectangle(cornerRadius: 10, style: .continuous) RoundedRectangle(cornerRadius: 10, style: .continuous)
.stroke(AllInColors.delimiterGrey, lineWidth: 1) .stroke(AllInColors.delimiterGrey, lineWidth: 1)

@ -5,6 +5,9 @@ import PackageDescription
let package = Package( let package = Package(
name: "Api", name: "Api",
platforms: [
.iOS(.v13)
],
products: [ products: [
// Products define the executables and libraries a package produces, and make them visible to other packages. // Products define the executables and libraries a package produces, and make them visible to other packages.
.library( .library(

@ -0,0 +1,65 @@
//
// FactoryApiBet.swift
//
//
// Created by Emre on 11/01/2024.
//
import Foundation
import Model
public class FactoryApiBet: FactoryBet {
public func toResponse(bet: Bet) -> [String: Any] {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let json: [String: Any] = [
"theme": bet.theme,
"sentenceBet": bet.phrase,
"endRegistration": dateFormatter.string(from: bet.endRegisterDate),
"endBet": dateFormatter.string(from: bet.endBetDate),
"isPrivate": String(bet.isPublic),
"response": [],
]
return json
}
public func toModel(from json: [String: Any]) -> Bet? {
guard let theme = json["theme"] as? String,
let phrase = json["sentenceBet"] as? String,
let endRegisterDateString = json["endRegistration"] as? String,
let endBetDateString = json["endBet"] as? String,
let isPublicString = json["isPrivate"] as? String,
let createdBy = json["createdBy"] as? User, // Assuming User object can be parsed from JSON
let type = json["type"] as? Int else {
return nil
}
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
guard let endRegisterDate = dateFormatter.date(from: endRegisterDateString),
let endBetDate = dateFormatter.date(from: endBetDateString) else {
return nil
}
let isPublic = (isPublicString.lowercased() == "true")
return toModel(theme: theme, description: phrase, endRegister: endRegisterDate, endBet: endBetDate, isPublic: isPublic, creator: createdBy, type: type)
}
public func toModel(theme: String, description: String, endRegister: Date, endBet: Date, isPublic: Bool, creator: User, type: Int) -> Bet {
switch type {
case 0:
return BinaryBet(theme: theme, phrase: description, endRegisterDate: endRegister, endBetDate: endBet, totalStakes: 0, isPublic: isPublic, invited: [], author: creator, registered: [])
case 1:
return MatchBet(theme: theme, phrase: description, endRegisterDate: endRegister, endBetDate: endBet, totalStakes: 0, isPublic: isPublic, invited: [], author: creator, registered: [], nameTeam1: "", nameTeam2: "")
case 2:
return CustomBet(theme: theme, phrase: description, endRegisterDate: endRegister, endBetDate: endBet, totalStakes: 0, isPublic: isPublic, invited: [], author: creator, registered: [])
default:
return BinaryBet(theme: theme, phrase: description, endRegisterDate: endRegister, endBetDate: endBet, totalStakes: 0, isPublic: isPublic, invited: [], author: creator, registered: [])
}
}
}

@ -12,7 +12,10 @@ let allInApi = "https://codefirst.iut.uca.fr/containers/AllDev-api"
public struct UserApiManager: UserDataManager { public struct UserApiManager: UserDataManager {
public init() { public let token: String
public init(withUserToken token: String) {
self.token = token
} }
public func getBets(withIndex index: Int, withCount count: Int) -> [Bet] { public func getBets(withIndex index: Int, withCount count: Int) -> [Bet] {
@ -21,27 +24,24 @@ public struct UserApiManager: UserDataManager {
public func addBet(bet: Bet) { public func addBet(bet: Bet) {
print(token)
let url = URL(string: allInApi + "bets/add")! let url = URL(string: allInApi + "bets/add")!
var request = URLRequest(url: url) var request = URLRequest(url: url)
request.httpMethod = "POST" request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let dateFormatter = DateFormatter() var json = FactoryApiBet().toResponse(bet: bet)
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" json["createdBy"] = token
let json = [
"theme": bet.theme,
"sentenceBet": bet.phrase,
"endRegistration": dateFormatter.string(from: bet.endRegisterDate),
"endBet": dateFormatter.string(from: bet.endBetDate),
"isPrivate": String(bet.isPublic),
"response": "",
"createdBy": ""
]
if let jsonData = try? JSONSerialization.data(withJSONObject: json, options: []){ if let jsonData = try? JSONSerialization.data(withJSONObject: json, options: []){
URLSession.shared.uploadTask(with: request, from: jsonData) { data, response, error in URLSession.shared.uploadTask(with: request, from: jsonData) { data, response, error in
print ("ALLIN : Add BET")
if let httpResponse = response as? HTTPURLResponse {
if httpResponse.statusCode == 201 {
}
print(httpResponse.statusCode)
}
}.resume() }.resume()
} }
} }

@ -5,6 +5,9 @@ import PackageDescription
let package = Package( let package = Package(
name: "Model", name: "Model",
platforms: [
.iOS(.v13)
],
products: [ products: [
// Products define the executables and libraries a package produces, and make them visible to other packages. // Products define the executables and libraries a package produces, and make them visible to other packages.
.library( .library(

@ -7,16 +7,56 @@
import Foundation import Foundation
public protocol Bet { /// A class representing a betting entity, including details about the bet theme, participants, and deadlines.
//public private(set) var id: String public class Bet: ObservableObject {
var theme: String { get set } /// The theme or topic of the bet.
var phrase: String { get set } public private(set) var theme: String
var endRegisterDate: Date { get set }
var endBetDate: Date { get set }
var totalStakes: Int { get set }
var isPublic: Bool { get set }
var invited: [User] { get set }
var author: User { get set }
var registered: [User] { get set }
/// The specific phrase or question related to the bet.
public private(set) var phrase: String
/// The deadline for users to register for the bet.
public private(set) var endRegisterDate: Date
/// The deadline for the actual betting to take place.
public private(set) var endBetDate: Date
/// The total stakes or amount involved in the bet.
public private(set) var totalStakes: Int
/// Indicates whether the bet is public or private.
public private(set) var isPublic: Bool
/// List of users who are invited to participate in the bet.
public private(set) var invited: [User]
/// The user who created the bet.
public private(set) var author: User
/// List of users who have registered for the bet.
public private(set) var registered: [User]
/// Custom Constructor
///
/// - Parameters:
/// - theme: The theme or topic of the bet.
/// - phrase: The specific phrase or question related to the bet.
/// - endRegisterDate: The deadline for users to register for the bet.
/// - endBetDate: The deadline for the actual betting to take place.
/// - totalStakes: The total stakes or amount involved in the bet.
/// - isPublic: Indicates whether the bet is public or private.
/// - invited: List of users who are invited to participate in the bet.
/// - author: The user who created the bet.
/// - registered: List of users who have registered for the bet.
public init(theme: String, phrase: String, endRegisterDate: Date, endBetDate: Date, totalStakes: Int, isPublic: Bool, invited: [User], author: User, registered: [User]) {
self.theme = theme
self.phrase = phrase
self.endRegisterDate = endRegisterDate
self.endBetDate = endBetDate
self.totalStakes = totalStakes
self.isPublic = isPublic
self.invited = invited
self.author = author
self.registered = registered
}
} }

@ -7,37 +7,22 @@
import Foundation import Foundation
public struct BinaryBet: Bet { /// A subclass of Bet that represents a binary bet, where participants make a choice between two possible outcomes.
public var theme: String public class BinaryBet: Bet {
public var phrase: String
public var endRegisterDate: Date
public var endBetDate: Date
public var totalStakes: Int
public var isPublic: Bool
public var invited: [User]
public var author: User
public var registered: [User]
public init( // Custom Constructor
theme: String, ///
phrase: String, /// - Parameters:
endRegisterDate: Date, /// - theme: The theme or topic of the binary bet.
endBetDate: Date, /// - phrase: The specific phrase or question related to the binary bet.
totalStakes: Int, /// - endRegisterDate: The deadline for users to register for the binary bet.
isPublic: Bool, /// - endBetDate: The deadline for the actual betting to take place for the binary bet.
invited: [User], /// - totalStakes: The total stakes or amount involved in the binary bet.
author: User, /// - isPublic: Indicates whether the binary bet is public or private.
registered: [User] /// - invited: List of users who are invited to participate in the binary bet.
) { /// - author: The user who created the binary bet.
self.theme = theme /// - registered: List of users who have registered for the binary bet.
self.phrase = phrase public override init(theme: String, phrase: String, endRegisterDate: Date, endBetDate: Date, totalStakes: Int, isPublic: Bool, invited: [User], author: User, registered: [User]) {
self.endRegisterDate = endRegisterDate super.init(theme: theme, phrase: phrase, endRegisterDate: endRegisterDate, endBetDate: endBetDate, totalStakes: totalStakes, isPublic: isPublic, invited: invited, author: author, registered: registered)
self.endBetDate = endBetDate
self.totalStakes = totalStakes
self.isPublic = isPublic
self.invited = invited
self.author = author
self.registered = registered
} }
} }

@ -7,16 +7,27 @@
import Foundation import Foundation
/// Enum to represent the possible answers for a binary participation.
public enum YesNo { public enum YesNo {
case yes case yes
case no case no
} }
public struct BinaryParticipation: Participation { /// A subclass of Participation that represents a binary participation (yes/no) in a bet.
public var coinAmount: Int public class BinaryParticipation: Participation {
public var date: Date /// The answer for the binary participation (yes or no).
public var user: User
public var bet: Bet
public var answer: YesNo public var answer: YesNo
/// Custom Constructor
///
/// - Parameters:
/// - coinAmount: The amount of coins involved in the binary participation.
/// - date: The date and time when the binary participation occurred.
/// - user: The user who participated in the binary bet.
/// - bet: The binary bet in which the user participated.
/// - answer: The answer for the binary participation (yes or no).
public init(coinAmount: Int, date: Date, user: User, bet: Bet, answer: YesNo) {
self.answer = answer
super.init(coinAmount: coinAmount, date: date, user: user, bet: bet)
}
} }

@ -7,16 +7,7 @@
import Foundation import Foundation
public struct CustomBet: Bet { /// A subclass of Bet that represents a custom bet, allowing users to define their own parameters and rules.
public var theme: String public class CustomBet: Bet {
public var phrase: String
public var endRegisterDate: Date
public var endBetDate: Date
public var totalStakes: Int
public var isPublic: Bool
public var invited: [User]
public var author: User
public var registered: [User]
public var possibleAnswers: [CustomBetResponse]
} }

@ -7,7 +7,15 @@
import Foundation import Foundation
public struct CustomBetResponse { /// A class representing a user's response to a custom bet.
public class CustomBetResponse {
/// The name or description of the custom bet response.
public var name: String public var name: String
/// Custom Constructor
///
/// - Parameter name: The name or description of the custom bet response.
public init(name: String) {
self.name = name
}
} }

@ -7,11 +7,21 @@
import Foundation import Foundation
public struct CustomParticipation: Participation { /// A subclass of Participation that represents a custom participation in a bet.
public var coinAmount: Int public class CustomParticipation: Participation {
public var date: Date /// The user's response to the custom bet.
public var user: User
public var bet: Bet
public var answer: CustomBetResponse public var answer: CustomBetResponse
/// Custom Constructor
///
/// - Parameters:
/// - coinAmount: The amount of coins involved in the custom participation.
/// - date: The date and time when the custom participation occurred.
/// - user: The user who participated in the custom bet.
/// - bet: The custom bet in which the user participated.
/// - answer: The user's response to the custom bet.
public init(coinAmount: Int, date: Date, user: User, bet: Bet, answer: CustomBetResponse) {
self.answer = answer
super.init(coinAmount: coinAmount, date: date, user: user, bet: bet)
}
} }

@ -8,7 +8,7 @@
import Foundation import Foundation
public protocol FactoryBet { public protocol FactoryBet {
func toResponse() func toResponse(bet: Bet) -> [String: Any]
func toModel() -> Bet func toModel(from json: [String: Any]) -> Bet?
func toModel(theme: String, description: String, endRegister: Date, endBet: Date, isPublic: Bool, creator: User, type: Int) -> Bet func toModel(theme: String, description: String, endRegister: Date, endBet: Date, isPublic: Bool, creator: User, type: Int) -> Bet
} }

@ -19,5 +19,4 @@ public struct Manager {
public func addBet(bet: Bet) { public func addBet(bet: Bet) {
userDataManager.addBet(bet: bet) userDataManager.addBet(bet: bet)
} }
} }

@ -7,17 +7,31 @@
import Foundation import Foundation
public struct MatchBet: Bet { /// A subclass of Bet that represents a bet on a match between two teams.
public var theme: String public class MatchBet: Bet {
public var phrase: String /// The name of the first team involved in the match.
public var endRegisterDate: Date
public var endBetDate: Date
public var totalStakes: Int
public var isPublic: Bool
public var invited: [User]
public var author: User
public var registered: [User]
public var nameTeam1: String public var nameTeam1: String
/// The name of the second team involved in the match.
public var nameTeam2: String public var nameTeam2: String
/// Custom Constructor
///
/// - Parameters:
/// - theme: The theme or topic of the match bet.
/// - phrase: The specific phrase or question related to the match bet.
/// - endRegisterDate: The deadline for users to register for the match bet.
/// - endBetDate: The deadline for the actual betting to take place for the match bet.
/// - totalStakes: The total stakes or amount involved in the match bet.
/// - isPublic: Indicates whether the match bet is public or private.
/// - invited: List of users who are invited to participate in the match bet.
/// - author: The user who created the match bet.
/// - registered: List of users who have registered for the match bet.
/// - nameTeam1: The name of the first team involved in the match.
/// - nameTeam2: The name of the second team involved in the match.
public init(theme: String, phrase: String, endRegisterDate: Date, endBetDate: Date, totalStakes: Int, isPublic: Bool, invited: [User], author: User, registered: [User], nameTeam1: String, nameTeam2: String) {
self.nameTeam1 = nameTeam1
self.nameTeam2 = nameTeam2
super.init(theme: theme, phrase: phrase, endRegisterDate: endRegisterDate, endBetDate: endBetDate, totalStakes: totalStakes, isPublic: isPublic, invited: invited, author: author, registered: registered)
}
} }

@ -7,12 +7,26 @@
import Foundation import Foundation
public struct MatchParticipation: Participation { /// A subclass of Participation that represents a user's participation in a match bet.
public var coinAmount: Int public class MatchParticipation: Participation {
public var date: Date /// The points earned by the user for the first team in the match.
public var user: User public var pointsTeam1: Int
public var bet: Bet
public var PointsTeam1: Int
public var PointsTeam2: Int
/// The points earned by the user for the second team in the match.
public var pointsTeam2: Int
/// Custom Constructor
///
/// - Parameters:
/// - coinAmount: The amount of coins involved in the match participation.
/// - date: The date and time when the match participation occurred.
/// - user: The user who participated in the match bet.
/// - bet: The match bet in which the user participated.
/// - pointsTeam1: The points earned by the user for the first team in the match.
/// - pointsTeam2: The points earned by the user for the second team in the match.
public init(coinAmount: Int, date: Date, user: User, bet: Bet, pointsTeam1: Int, pointsTeam2: Int) {
self.pointsTeam1 = pointsTeam1
self.pointsTeam2 = pointsTeam2
super.init(coinAmount: coinAmount, date: date, user: user, bet: bet)
}
} }

@ -7,10 +7,31 @@
import Foundation import Foundation
public protocol Participation { /// A class representing a user's participation in a bet, including the amount of coins, date, user, and the associated bet.
var coinAmount: Int { get set } public class Participation: ObservableObject {
var date: Date { get set } /// The amount of coins involved in the participation.
var user: User { get set } var coinAmount: Int
var bet: Bet { get set }
/// The date and time when the participation occurred.
var date: Date
/// The user who participated in the bet.
var user: User
/// The bet in which the user participated.
var bet: Bet
/// Custom Constructor
///
/// - Parameters:
/// - coinAmount: The amount of coins involved in the participation.
/// - date: The date and time when the participation occurred.
/// - user: The user who participated in the bet.
/// - bet: The bet in which the user participated.
init(coinAmount: Int, date: Date, user: User, bet: Bet) {
self.coinAmount = coinAmount
self.date = date
self.user = user
self.bet = bet
}
} }

@ -5,6 +5,9 @@ import PackageDescription
let package = Package( let package = Package(
name: "StubLib", name: "StubLib",
platforms: [
.iOS(.v13)
],
products: [ products: [
// Products define the executables and libraries a package produces, and make them visible to other packages. // Products define the executables and libraries a package produces, and make them visible to other packages.
.library( .library(

Loading…
Cancel
Save