Skip to content

Commit

Permalink
Merge pull request #127 from P4-Games/feature/update-user
Browse files Browse the repository at this point in the history
merge feature/update-user into develop
  • Loading branch information
dappsar authored Oct 16, 2024
2 parents 12f0d70 + 97a532c commit 94135b8
Show file tree
Hide file tree
Showing 17 changed files with 220 additions and 195 deletions.
7 changes: 7 additions & 0 deletions next.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ module.exports = {
'storage.googleapis.com',
'cilxj-yiaaa-aaaag-alkxq-cai.icp0.io',
'gateway.pinata.cloud',
'w.wallhaven.cc',
'img.freepik.com'],
remotePatterns: [
{
Expand All @@ -44,6 +45,12 @@ module.exports = {
hostname: 'img.freepik.com',
port: '',
pathname: '/**',
},
{
protocol: 'https',
hostname: 'w.wallhaven.cc',
port: '',
pathname: '/**',
}
],
},
Expand Down
12 changes: 10 additions & 2 deletions src/app/api/_data/data-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,14 @@ export async function updateUserCode(userId: string, code: number | undefined):
return result
}

export async function updateUser(contact: IAccount): Promise<boolean> {
const filter = { _id: getObjectId(contact.id) }
const updateData = { name: contact.name }
const setValue = { $set: updateData }
const result: boolean = await updateOneCommon(DB_CHATTERPAY_NAME, SCHEMA_USERS, filter, setValue)
return result
}

export async function getWalletNfts(wallet: string): Promise<INFT[] | undefined> {
const client = await getClientPromise()
const db = client.db(DB_CHATTERPAY_NAME)
Expand Down Expand Up @@ -179,12 +187,12 @@ export async function getWalletNfts(wallet: string): Promise<INFT[] | undefined>
return nfts
}

export async function getNftById(id: string): Promise<INFT | undefined> {
export async function getNftById(nftId: string): Promise<INFT | undefined> {
const client = await getClientPromise()
const db = client.db(DB_CHATTERPAY_NAME)

const nft: INFT | null = await db.collection(SCHEMA_NFTS).findOne({
id
id: nftId
})

if (!nft) {
Expand Down
2 changes: 1 addition & 1 deletion src/app/api/_data/mongo-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ export async function updateOneCommon(
`updated ${colName}: ${matchedDocuments} document(s) found and ${modifiedDocuments} document(s) updated.`
)

return result.modifiedCount > 0
return result.modifiedCount > 0 || matchedDocuments > 0
} finally {
// NONE
}
Expand Down
3 changes: 2 additions & 1 deletion src/app/api/_hooks/api-resolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,8 @@ export const endpoints = {
dashboard: {
root: getFullUIEndpoint('app'),
user: {
id: (id: string) => getFullUIEndpoint(`user/${id}`)
id: (id: string) => getFullUIEndpoint(`user/${id}`),
update: (id: string) => getFullUIEndpoint(`user/${id}`)
},
wallet: {
balance: (id: string) => getFullUIEndpoint(`wallet/${id}/balance`),
Expand Down
7 changes: 6 additions & 1 deletion src/app/api/_hooks/use-contact.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { endpoints } from 'src/app/api/_hooks/api-resolver'
import { post, endpoints } from 'src/app/api/_hooks/api-resolver'

import { useGetCommon } from './common'

Expand All @@ -7,3 +7,8 @@ import { useGetCommon } from './common'
export function useGetContact(contactId: string) {
return useGetCommon(endpoints.dashboard.user.id(contactId))
}

export async function updateContact(userId: string, data: { name: string }) {
const res = await post(endpoints.dashboard.user.update(userId), data, {})
return res
}
1 change: 0 additions & 1 deletion src/app/api/v1/nft/[id]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ export async function GET(request: Request, { params }: { params: IParams }) {

try {
const nft: INFT | undefined = await getNftById(params.id)
console.log('3', params, nft)

if (nft) {
return NextResponse.json(nft)
Expand Down
59 changes: 57 additions & 2 deletions src/app/api/v1/user/[id]/route.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { NextResponse } from 'next/server'
import { NextRequest, NextResponse } from 'next/server'

import { getUserByPhone } from 'src/app/api/_data/data-service'
import { updateUser, getUserById, getUserByPhone } from 'src/app/api/_data/data-service'

import { IAccount } from 'src/types/account'

Expand Down Expand Up @@ -56,3 +56,58 @@ export async function GET(request: Request, { params }: { params: IParams }) {
})
}
}

export async function POST(req: NextRequest, { params }: { params: IParams }) {
try {
const { id } = params
const { name }: { name: string } = await req.json()

if (!name || !id) {
return new NextResponse(
JSON.stringify({
code: 'INVALID_REQUEST_PARAMS',
error: 'Missing id or name in request body'
}),
{
status: 400,
headers: { 'Content-Type': 'application/json' }
}
)
}

const user: IAccount | undefined = await getUserById(id)
if (!user) {
return new NextResponse(
JSON.stringify({ code: 'USER_NOT_FOUND', error: 'user not found with that id' }),
{
status: 404,
headers: { 'Content-Type': 'application/json' }
}
)
}

user.name = name
const reult: boolean = await updateUser(user)

if (!reult) {
return new NextResponse(
JSON.stringify({
code: 'USER_UPDATE_ERROR',
error: 'user update error'
}),
{
status: 400,
headers: { 'Content-Type': 'application/json' }
}
)
}

return NextResponse.json({ reult })
} catch (ex) {
console.error(ex)
return new NextResponse(JSON.stringify({ error: 'Error in update user' }), {
status: 400,
headers: { 'Content-Type': 'application/json' }
})
}
}
4 changes: 2 additions & 2 deletions src/app/dashboard/user/account/page.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { AccountView } from 'src/sections/account/view'
import { AccountEditView } from 'src/sections/account/view'

// ----------------------------------------------------------------------

Expand All @@ -7,5 +7,5 @@ export const metadata = {
}

export default function AccountPage() {
return <AccountView />
return <AccountEditView />
}
87 changes: 51 additions & 36 deletions src/auth/context/jwt/auth-provider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ enum Types {
LOGIN = 'LOGIN',
GENERATE_CODE = 'GENERATE_CODE',
REGISTER = 'REGISTER',
LOGOUT = 'LOGOUT'
LOGOUT = 'LOGOUT',
UPDATE_USER = 'UPDATE_USER'
}

type Payload = {
Expand All @@ -33,6 +34,9 @@ type Payload = {
user: AuthUserType
}
[Types.LOGOUT]: undefined
[Types.UPDATE_USER]: {
user: AuthUserType
}
}

type ActionsType = ActionMapType<Payload>[keyof ActionMapType<Payload>]
Expand All @@ -45,40 +49,40 @@ const initialState: AuthStateType = {
}

const reducer = (state: AuthStateType, action: ActionsType) => {
if (action.type === Types.INITIAL) {
return {
loading: false,
user: action.payload.user
}
}
if (action.type === Types.LOGIN) {
return {
...state,
user: action.payload.user
}
}

if (action.type === Types.GENERATE_CODE) {
return {
...state,
user: null
}
}

if (action.type === Types.REGISTER) {
return {
...state,
user: action.payload.user
}
}

if (action.type === Types.LOGOUT) {
return {
...state,
user: null
}
switch (action.type) {
case Types.INITIAL:
return {
loading: false,
user: action.payload.user
}
case Types.LOGIN:
return {
...state,
user: action.payload.user
}
case Types.GENERATE_CODE:
return {
...state,
user: null
}
case Types.REGISTER:
return {
...state,
user: action.payload.user
}
case Types.LOGOUT:
return {
...state,
user: null
}
case Types.UPDATE_USER: // <-- Manejar la acción UPDATE_USER
return {
...state,
user: action.payload.user
}
default:
return state
}
return state
}

// ----------------------------------------------------------------------
Expand Down Expand Up @@ -241,6 +245,16 @@ export function AuthProvider({ children }: Props) {
})
}, [])

// update_user
const updateUser = useCallback((user: AuthUserType) => {
dispatch({
type: Types.UPDATE_USER,
payload: {
user
}
})
}, [])

// ----------------------------------------------------------------------

const checkAuthenticated = state.user ? 'authenticated' : 'unauthenticated'
Expand All @@ -259,9 +273,10 @@ export function AuthProvider({ children }: Props) {
loginWithCode,
generateCode,
register,
logout
logout,
updateUser
}),
[generateCode, login, loginWithCode, logout, register, state.user, status]
[generateCode, login, loginWithCode, logout, register, state.user, status, updateUser]
)

return <AuthContext.Provider value={memoizedValue}>{children}</AuthContext.Provider>
Expand Down
1 change: 1 addition & 0 deletions src/auth/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,4 +51,5 @@ export type JWTContextType = CanRemove & {
generateCode: (email: string, codeMsg: string, recaptchaToken: string) => Promise<void>
register: (email: string, password: string, firstName: string, lastName: string) => Promise<void>
logout: () => Promise<void>
updateUser: (user: AuthUserType) => void
}
12 changes: 9 additions & 3 deletions src/locales/langs/br.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,17 @@
"required": "obrigatório",
"must-be-numeric": "Deve ser numérico",
"must-be-max": "Deve ter no máximo {MAX_DIGITS} dígitos",
"must-be-valid-email": "O email deve ser um endereço de email válido",
"must-be-valid-email": "O email deve ser um endereço de email válido",
"must-be-min": "Deve ter no mínimo {MIN_CHARS} caracteres",
"nodata": "Sem Dados",
"close": "Fechar",
"view": "Ver",
"share": "Compartilhar",
"metadata": "Ver Metadata"
"metadata": "Ver Metadata",
"msg": {
"update-success": "Atualização bem-sucedida!",
"update-error": "Erro de atualização"
}
},
"menu": {
"overview": "Visão geral",
Expand Down Expand Up @@ -318,6 +323,7 @@
}
},
"account": {
"title": "Conta"
"title": "Conta",
"save": "Salvar Alterações"
}
}
10 changes: 8 additions & 2 deletions src/locales/langs/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,16 @@
"must-be-numeric": "Must be numeric",
"must-be-max": "Must be a maximum of {MAX_DIGITS} digits",
"must-be-valid-email": "Email must be a valid email address",
"must-be-min": "Must have a minimum of {MIN_CHARS} chars",
"nodata": "No Data",
"close": "Close",
"view": "View",
"share": "Share",
"metadata": "View Metadata"
"metadata": "View Metadata",
"msg": {
"update-success": "Update Success!",
"update-error": "Update error"
}
},
"menu": {
"overview": "overview",
Expand Down Expand Up @@ -318,6 +323,7 @@
}
},
"account": {
"title": "Account"
"title": "Account",
"save": "Save Changes"
}
}
10 changes: 8 additions & 2 deletions src/locales/langs/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,16 @@
"must-be-numeric": "Debe ser numérico",
"must-be-max": "Debe tener un máximo de {MAX_DIGITS} dígitos",
"must-be-valid-email": "El correo electrónico debe ser una dirección de correo válida",
"must-be-min": "Debe tener un mínimo de {MIN_CHARS} caracteres",
"nodata": "Sin Datos",
"close": "Cerrar",
"view": "Ver",
"share": "Compartir",
"metadata": "Ver Metadata"
"metadata": "Ver Metadata",
"msg": {
"update-success": "¡Actualización exitosa!",
"update-error": "Error de actualización"
}
},
"menu": {
"overview": "Visión general",
Expand Down Expand Up @@ -319,6 +324,7 @@
}
},
"account": {
"title": "Cuenta"
"title": "Cuenta",
"save": "Guardar Cambios"
}
}
Loading

0 comments on commit 94135b8

Please sign in to comment.