Skip to content

Commit

Permalink
feat: Implement Firebase integration with Eyedrops and Database repos…
Browse files Browse the repository at this point in the history
…itories; add EXAME_STATUS enum; enhance Exame model with status management; update MainPage for data synchronization
  • Loading branch information
werepa committed Dec 24, 2024
1 parent 5eed277 commit fe255e6
Show file tree
Hide file tree
Showing 19 changed files with 2,262 additions and 242 deletions.
6 changes: 4 additions & 2 deletions angular.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@
"assets": [
{
"glob": "**/*",
"input": "public"
"input": "public",
"src/assets"
}
],
"styles": ["src/global.scss", "src/theme/variables.scss"],
Expand Down Expand Up @@ -80,7 +81,8 @@
"assets": [
{
"glob": "**/*",
"input": "public"
"input": "public",
"src/assets"
}
],
"styles": ["src/global.scss", "src/theme/variables.scss"],
Expand Down
2,132 changes: 1,924 additions & 208 deletions package-lock.json

Large diffs are not rendered by default.

4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"@angular/common": "^18.1.0",
"@angular/compiler": "^18.1.0",
"@angular/core": "^18.1.0",
"@angular/fire": "^18.0.1",
"@angular/forms": "^18.1.0",
"@angular/platform-browser": "^18.1.0",
"@angular/platform-browser-dynamic": "^18.1.0",
Expand All @@ -34,6 +35,7 @@
"@ionic/pwa-elements": "^3.3.0",
"@ngrx/signals": "^18.1.1",
"@types/uuid": "^10.0.0",
"firebase": "^11.1.0",
"ionicons": "^7.4.0",
"rxjs": "~7.8.1",
"tslib": "^2.6.3",
Expand Down Expand Up @@ -69,4 +71,4 @@
"typescript": "~5.5.3"
},
"description": "An Ionic project"
}
}
34 changes: 34 additions & 0 deletions src/app/Repository/DatabaseRepository/DatabaseProvider.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { ExameService } from "src/app/services/exame.service"
import { DatabaseRepository } from "./DatabaseRepository"
import firebase from "firebase/compat/app"
import "firebase/firestore"

const firebaseConfig = {
apiKey: "AIzaSyDpMfldg10XJfdkap0lsQkfaFTzbVTv3Lo",
authDomain: "grade-anp-testes.firebaseapp.com",
projectId: "grade-anp-testes",
storageBucket: "grade-anp-testes.firebasestorage.app",
messagingSenderId: "486118580910",
appId: "1:486118580910:web:de3c6d36d5b1672d86c33f",
}

export const DatabaseProvider = [
// provider for ExameService
{
provide: ExameService,
useFactory: (repository: any) => {
return new ExameService(repository)
},
inject: [DatabaseRepository],
},
// provider for DatabaseRepository
{
provide: "EYEDROPS_REPOSITORY",
useClass: DatabaseRepository,
},
// provider for firebase
{
provide: firebase.initializeApp(firebaseConfig),
useValue: firebase.initializeApp(firebaseConfig),
},
]
Empty file.
79 changes: 79 additions & 0 deletions src/app/Repository/DatabaseRepository/DatabaseRepository.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import { Injectable } from "@angular/core"
import { AngularFirestore, CollectionReference } from "@angular/fire/compat/firestore"
import { EyedropsRepository } from "../EyedropsRepository"
import { Exame } from "src/app/models"
import "firebase/compat/firestore"

@Injectable({
providedIn: "root",
})
export class DatabaseRepository implements EyedropsRepository {
eyedropsCollection: CollectionReference

constructor(private firestore: AngularFirestore) {
this.eyedropsCollection = this.firestore.collection("eyedrops").ref
this.getByCodigo("0123/2024 GO")
.then((exame) => {
console.log("exame", exame)
})
.catch((error) => {
console.error("Error getting document: ", error)
})
}
async getByCodigo(codigo: string): Promise<any> {
try {
const eyedropsRef = this.eyedropsCollection.where("codigo", "==", codigo)
const eyedropsQuery = await eyedropsRef.limit(1).get()
if (eyedropsQuery.empty) return null
const exame: Exame = await eyedropsQuery.docs.map(async (doc: any) => {
const data: any = {
...doc.data(),
id: doc.id,
exame: doc.data(),
}
return data
})[0]
return exame
} catch (error) {
console.error(`Erro ao buscar documento codigo:${codigo}`, error)
throw error
}
}
getByUF(codigo: string): Promise<any[]> {
throw new Error("Method not implemented.")
}

async save(exame: Exame): Promise<void> {
try {
const query = await this.eyedropsCollection.where("codigo", "==", exame.material.codigo).get()
if (query.empty) {
console.log("save - create", query.empty)
await this.eyedropsCollection.doc().set({ codigo: exame.material.codigo, exame: JSON.stringify(exame) })
} else {
console.log("save - update", query.docs[0].id)
await this.eyedropsCollection
.doc(query.docs[0].id)
.set({ codigo: exame.material.codigo, exame: JSON.stringify(exame) })
}
} catch (error) {
console.error("Erro ao criar o documento:", error)
throw new Error(error.message)
}
}

// async remove(gradeId: string): Promise<void> {
// try {
// const gradeRef = this.#gradeCollection.doc(gradeId)
// if (!gradeRef) throw Error(`Grade ID: ${gradeId} não existe no repositório!`)
// await gradeRef.delete()
// return null
// } catch (error) {
// console.error(`Erro ao buscar documento ID:${gradeId}`, error)
// throw error
// }
// }

async truncate() {
return Promise.resolve()
}
}
8 changes: 8 additions & 0 deletions src/app/Repository/EyedropsRepository.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { Exame } from "../models"

export interface EyedropsRepository {
save(exame: Exame): Promise<void>
getByCodigo(codigo: string): Promise<any>
getByUF(codigo: string): Promise<any[]>
truncate(): Promise<void>
}
12 changes: 12 additions & 0 deletions src/app/Repository/InMemoryRepository/InMemoryProvider.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { ExameService } from "src/app/services/exame.service"
import { InMemoryRepository } from "./InMemoryRepository"

export const InMemoryProvider = [
{
provide: ExameService,
useFactory: (repository: any) => {
return new ExameService(repository)
},
inject: [InMemoryRepository],
},
]
34 changes: 34 additions & 0 deletions src/app/Repository/InMemoryRepository/InMemoryRepository.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { Exame } from "src/app/models"
import { EyedropsRepository } from "../EyedropsRepository"

export class InMemoryRepository implements EyedropsRepository {
getByCodigo(codigo: string): Promise<any> {
return Promise.resolve(
this.exames.find((exame) => `${exame.material.numero} ${exame.material.uf.toUpperCase()}` === codigo.toUpperCase())
)
}
exames: Exame[] = []

async getByUF(uf: string): Promise<any[]> {
return Promise.resolve(this.exames.filter((exame) => exame.material.uf === uf))
}

async save(exame: Exame): Promise<void> {
const index = this.exames.findIndex(
(e) =>
`${e.material.numero} ${e.material.uf.toUpperCase()}` ===
`${exame.material.numero} ${exame.material.uf.toUpperCase()}`
)
if (index < 0) {
this.exames.push(exame)
} else {
this.exames[index] = exame
}
return
}

truncate() {
this.exames = []
return Promise.resolve()
}
}
5 changes: 5 additions & 0 deletions src/app/Repository/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
// @index(['./**/*.ts',/spec/g], f => `export * from '${f.path}'`)
export * from "./DatabaseRepository/DatabaseRepository"
export * from "./EyedropsRepository"
export * from "./InMemoryRepository/InMemoryRepository"
// @endindex
38 changes: 38 additions & 0 deletions src/app/firebase/firebase.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import firebase from "firebase/compat/app"
import "firebase/compat/firestore"
import { DatabaseRepository } from "../Repository"

const firebaseProvider = {
provide: "FIREBASE_APP",
useFactory: () => {
const firebaseConfig = {
apiKey: "AIzaSyCychbq3p2CtKdv1-Q5ABJB7gA_r_En_x0",
authDomain: "grade-anp.firebaseapp.com",
projectId: "grade-anp",
storageBucket: "grade-anp.firebasestorage.app",
messagingSenderId: "761229602912",
appId: "1:761229602912:web:67aa3a36a10111fb965305",
}

if (!firebase.apps.length) {
firebase.initializeApp(firebaseConfig)
}

return firebase.firestore()
},
}

@Module({
providers: [
firebaseProvider,
{
provide: DatabaseRepository,
useFactory: (db: any) => {
return new DatabaseRepository(db)
},
inject: ["FIREBASE_APP"],
},
],
exports: [DatabaseRepository],
})
export class FirebaseModule {}
3 changes: 3 additions & 0 deletions src/app/main/main.page.html
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@
<span class="small-text"> {{ state().exameAtual.material.uf }} </span>
</ion-title>
<ion-buttons slot="end" *ngIf="state().exameAtual">
<ion-button (click)="syncWithFirebase()">
<ion-icon name="sync-outline"></ion-icon>
</ion-button>
<ion-button (click)="addExame()">
<ion-icon slot="icon-only" name="add-outline"></ion-icon>
</ion-button>
Expand Down
9 changes: 7 additions & 2 deletions src/app/main/main.page.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import { AlertController, IonicModule } from "@ionic/angular"
import { CommonModule } from "@angular/common"
import { BreakpointObserver, Breakpoints } from "@angular/cdk/layout"
import { addIcons } from "ionicons"
import { addOutline, camera, cameraOutline, checkmarkOutline, printOutline, trashOutline } from "ionicons/icons"
import { addOutline, camera, cameraOutline, checkmarkOutline, printOutline, syncOutline, trashOutline } from "ionicons/icons"
import { BATERIA_STATUS, STEP, TAREFAS, TELA_STATUS } from "../models/listas"
import { AuthService } from "../services/auth.service"
import { GaleriaFotosComponent } from "../galeria-fotos/galeria-fotos.component"
Expand Down Expand Up @@ -73,7 +73,7 @@ export class MainPage implements OnInit {

constructor(private exameService: ExameService, private fb: FormBuilder, private breakpointObserver: BreakpointObserver) {
this.state = this.exameService.state
addIcons({ camera, cameraOutline, checkmarkOutline, trashOutline, addOutline, printOutline })
addIcons({ camera, cameraOutline, checkmarkOutline, trashOutline, addOutline, printOutline, syncOutline })
}

ngOnInit() {
Expand Down Expand Up @@ -102,6 +102,11 @@ export class MainPage implements OnInit {
this.mostrarBateria = false
}

//sincroniza dados com Firebase
syncWithFirebase() {
this.exameService.syncWithFirebase()
}

isExameAtual(material: Material): boolean {
if (!this.state().exameAtual) return false
const materialAtual = this.state().exameAtual.material
Expand Down
35 changes: 29 additions & 6 deletions src/app/models/Exame.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,42 @@
import { Material, Usuario } from "."
import { STEP, Tarefa, TAREFAS } from "./listas"
import { EXAME_STATUS, STEP, Tarefa, TAREFAS } from "./listas"

export class Exame {
private _embalagem: string = ""
private _tarefas: Tarefa[] = []
private _currentStep: STEP = STEP.RECEBER_MATERIAL
private _material: Material
private _status: {
codigo: EXAME_STATUS
data: Date
usuario: Usuario
} = {
codigo: EXAME_STATUS.BLOQUEADO,
data: new Date(),
usuario: null,
}

constructor(private _material: Material) {
constructor(material: Material) {
this.material = material
this.reset()
}

get status(): any {
return this._status
}

set status(status: any) {
this._status = status
}

get material(): Material {
return this._material
}

set material(material: Material) {
this._material = material
}

/*
// RECEBER_MATERIAL = 0,
// VERIFICAR_MATERIAL_LACRADO = 1,
Expand Down Expand Up @@ -245,10 +272,6 @@ export class Exame {
this._embalagem = uuid
}

get material(): Material {
return this._material
}

get tarefas(): Tarefa[] {
return this._tarefas
}
Expand Down
4 changes: 4 additions & 0 deletions src/app/models/Material.ts
Original file line number Diff line number Diff line change
Expand Up @@ -469,6 +469,10 @@ export class Material {
this._is_zip_moving = moving
}

get codigo() {
return `${this._numero} ${this._uf}`
}

// Verifica se dois materiais são iguais
public equal(material: Material): boolean {
return this._numero === this.formatNumber(material.numero) && this._uf === material.uf.toUpperCase()
Expand Down
6 changes: 6 additions & 0 deletions src/app/models/listas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,3 +96,9 @@ export type Tarefa = {
ativa: boolean
concluida: boolean
}

export enum EXAME_STATUS {
DISPONIVEL,
BLOQUEADO,
CONCLUIDO,
}
Loading

0 comments on commit fe255e6

Please sign in to comment.