Skip to content

Commit

Permalink
Add files via upload
Browse files Browse the repository at this point in the history
  • Loading branch information
YU-SHAO-XU authored May 21, 2024
1 parent 4294f92 commit 29dbf4d
Show file tree
Hide file tree
Showing 15 changed files with 320 additions and 321 deletions.
22 changes: 12 additions & 10 deletions AuthService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,30 +8,32 @@
import Foundation
import Firebase



class AuthService{
class AuthService: ObservableObject {

@Published var userSession: FirebaseAuth.User?

static let shared = AuthService()
init(){

private init() {
self.userSession = Auth.auth().currentUser
}

@MainActor
func login(withEmail email: String, password: String) async throws{
func login(withEmail email: String, password: String) async throws {
do {
let result = try await Auth.auth().signIn(withEmail: email, password: password)
self.userSession = result.user
} catch {
print("DEBUG: Failed to login user with error \(error.localizedDescription)")
}

}


func signout(){
try? Auth.auth().signOut()
self.userSession = nil
func signout() {
do {
try Auth.auth().signOut()
self.userSession = nil
} catch {
print("DEBUG: Failed to sign out with error \(error.localizedDescription)")
}
}
}
3 changes: 2 additions & 1 deletion ContentView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ struct ContentView: View {
@StateObject var viewModel = ContentViewModel()

var body: some View {
Group{
Group {
if viewModel.userSession == nil {
Login()
} else {
Expand All @@ -21,6 +21,7 @@ struct ContentView: View {
}
}

// Preview for SwiftUI canvas
#Preview {
ContentView()
}
28 changes: 28 additions & 0 deletions ContentViewModel.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
//
// ContentView.swift
// Industrial_APP
//
// Created by User on 2023/12/29.
//

import Foundation
import Firebase
import Combine

@MainActor
class ContentViewModel: ObservableObject{

private let service = AuthService.shared
private var cancellables = Set<AnyCancellable>()

@Published var userSession : FirebaseAuth.User?
init(){
setupSubscribers()
}
func setupSubscribers(){
service.$userSession.sink{[weak self] userSession in
self?.userSession = userSession
}
.store(in: &cancellables)
}
}
7 changes: 7 additions & 0 deletions Cost.swift
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
//
// ContentView.swift
// Industrial_APP
//
// Created by User on 2023/5/17.
//

import SwiftUI

struct Cost: View {
Expand Down
238 changes: 89 additions & 149 deletions IE.swift
Original file line number Diff line number Diff line change
@@ -1,201 +1,141 @@
//
// ContentView.swift
// Industrial_APP
//
// Created by User on 2023/2/21.
//

import SwiftUI
import FirebaseFirestore

struct Process: Identifiable, Codable {
var id: UUID // 使用 UUID 作為唯一 ID
var productName: String
struct ProcessData: Identifiable, Codable {
var id: String
var name: String
var quantity: String
var machine: String
var progress: String
}

struct IE: View {
@State private var searchText = ""
@State private var productionOrder: [Process] = []
@State private var isSheetPresented = false
@State private var processes: [ProcessData] = []
@State private var showAlert = false
@State private var deleteIndexSet: IndexSet?

var filteredProductionOrder: [Process] {
if searchText.isEmpty {
return productionOrder
} else {
return productionOrder.filter { process in
process.productName.lowercased().contains(searchText.lowercased()) ||
process.quantity.lowercased().contains(searchText.lowercased()) ||
process.machine.lowercased().contains(searchText.lowercased()) ||
process.progress.lowercased().contains(searchText.lowercased())
}
}
}
@State private var deleteProcess: ProcessData?
private let collectionReference = Firestore.firestore().collection("processes")

var body: some View {
NavigationView {
VStack {
List {
ForEach(filteredProductionOrder) { process in
VStack() {
/* Text("ID: \(process.id)")
.frame(maxWidth: .infinity, alignment: .leading)
.font(.title2)*/
Text("Producto: \(process.productName)")
.frame(maxWidth: .infinity, alignment: .leading)
.font(.title2)
Text("Cantidad: \(process.quantity)")
.frame(maxWidth: .infinity, alignment: .leading)
.font(.title2)
Text("Máquina: \(process.machine)")
.frame(maxWidth: .infinity, alignment: .leading)
.font(.title2)
Text("Progreso: \(process.progress)")
.frame(maxWidth: .infinity, alignment: .leading)
.font(.title2)
HeaderRow()

ForEach($processes) { $process in
HStack {
TextField("Producto", text: $process.name, onCommit: {
saveProcess(process)
})
TextField("Cantidad", text: $process.quantity, onCommit: {
saveProcess(process)
})
TextField("Máquina", text: $process.machine, onCommit: {
saveProcess(process)
})
TextField("Progreso", text: $process.progress, onCommit: {
saveProcess(process)
})

Button(action: {
deleteProcess = process
showAlert = true
}) {
Image(systemName: "trash")
.foregroundColor(.red)
}
}
}
.onDelete(perform: { indexSet in
deleteIndexSet = indexSet
showAlert.toggle()
}) // Enable row deletion

}
.searchable(text: $searchText, prompt: "Buscar...")

Spacer()
}
.navigationBarTitle("Proceso", displayMode: .inline)
.navigationBarItems(trailing: Button(action: {
isSheetPresented.toggle()
addProcess()
}) {
Image(systemName: "plus")
}
.sheet(isPresented: $isSheetPresented) {
AddProcessView(productionOrder: $productionOrder, isSheetPresented: $isSheetPresented)
})
.onAppear {
fetchProcesses()
}
.alert(isPresented: $showAlert) {
Alert(
title: Text("¡Advertencia!"),
message: Text("¿Estás seguro de eliminar este proceso?"),
primaryButton: .destructive(Text("Eliminar")) {
// Perform deletion action here
if let indexSet = deleteIndexSet {
deleteRow(at: indexSet)
title: Text("Confirm Delete"),
message: Text("Are you sure you want to delete this row?"),
primaryButton: .destructive(Text("Delete")) {
if let processToDelete = deleteProcess {
deleteProcess(processToDelete)
}
},
secondaryButton: .cancel(Text("Cancelar"))
secondaryButton: .cancel()
)
}
}
.onAppear {
fetchFromFirestore()
}
}

// Function to delete a row
private func deleteRow(at indexSet: IndexSet) {
// 获取要删除的文档的 ID
let idsToDelete = indexSet.compactMap { productionOrder[$0].id.uuidString }
productionOrder.remove(atOffsets: indexSet)

// 删除对应的 Firebase 文档
let db = Firestore.firestore()
let ordersCollection = db.collection("process")

idsToDelete.forEach { id in
ordersCollection.whereField("id", isEqualTo: id).getDocuments { snapshot, error in
if let error = error {
print("Error fetching documents: \(error)")
return
}
guard let documents = snapshot?.documents else {
print("No documents found")
return
}
for document in documents {
document.reference.delete { error in
if let error = error {
print("Error removing document: \(error)")
} else {
print("Document successfully removed from Firestore")
}
}
}
}
private func HeaderRow() -> some View {
HStack {
Text("Producto").font(.footnote).frame(maxWidth: .infinity, alignment: .center)
Text("Cantidad").font(.footnote).frame(maxWidth: .infinity, alignment: .center)
Text("Máquina").font(.footnote).frame(maxWidth: .infinity, alignment: .center)
Text("Progreso").font(.footnote).frame(maxWidth: .infinity, alignment: .center)
}
}
// Function to fetch data from Firestore
private func fetchFromFirestore() {
let db = Firestore.firestore()
let collectionRef = db.collection("process")

collectionRef.getDocuments { snapshot, error in

private func fetchProcesses() {
collectionReference.getDocuments { snapshot, error in
if let error = error {
print("Error getting documents: \(error)")
return
}

guard let documents = snapshot?.documents else {
print("No documents")
print("Error fetching documents: \(error)")
return
}

productionOrder = documents.compactMap { document in
var process = try? document.data(as: Process.self)
process?.id = UUID(uuidString: document.documentID) ?? UUID() // 將 Firestore 文檔 ID 賦值給 process 的 id 屬性
return process
guard let documents = snapshot?.documents else { return }
processes = documents.compactMap { document in
do {
let processData = try document.data(as: ProcessData.self)
return processData
} catch {
print("Error decoding document: \(error)")
return nil
}
}
}
}
}

struct AddProcessView: View {
@Binding var productionOrder: [Process]
@State private var newProcess = Process(id: UUID(), productName: "", quantity: "", machine: "", progress: "")
@Binding var isSheetPresented: Bool
@Environment(\.presentationMode) var presentationMode
private func saveProcess(_ process: ProcessData) {
do {
try collectionReference.document(process.id).setData(from: process)
} catch {
print("Error saving document: \(error)")
}
}

var body: some View {
NavigationView {
VStack {
Form {
Section {
TextField("Nombre del producto", text: $newProcess.productName)
TextField("Cantidad", text: $newProcess.quantity)
TextField("Máquina", text: $newProcess.machine)
TextField("Progreso", text: $newProcess.progress)
}
private func deleteProcess(_ process: ProcessData) {
collectionReference.document(process.id).delete { error in
if let error = error {
print("Error deleting document: \(error)")
} else {
if let index = processes.firstIndex(where: { $0.id == process.id }) {
processes.remove(at: index)
}
.navigationBarTitle("Agregar proceso")
.navigationBarItems(
leading: Button("Cancelar") {
presentationMode.wrappedValue.dismiss()
}.foregroundColor(.red),
trailing: Button("Ahorrar", action: saveOrder)
)
}
}
}


private func saveOrder() {
let db = Firestore.firestore()
let ordersCollection = db.collection("process")

do {
let documentReference = try ordersCollection.addDocument(from: newProcess)
let documentID = documentReference.documentID
print("Document added with ID: \(documentReference.documentID)")

// After successful save, add the new order to local data
productionOrder.append(newProcess)
isSheetPresented = false
} catch {
print("Error adding document: \(error)")
}
private func addProcess() {
let newProcess = ProcessData(id: UUID().uuidString, name: "", quantity: "", machine: "", progress: "")
processes.insert(newProcess, at: 0)
saveProcess(newProcess)
}
}

struct IE_Previews: PreviewProvider {
static var previews: some View {
IE()
}
}
struct IE_Previews: PreviewProvider {
static var previews: some View {
IE()
}
}
Binary file modified Industrial_APP.xcodeproj.zip
Binary file not shown.
Loading

0 comments on commit 29dbf4d

Please sign in to comment.