Skip to content

Commit

Permalink
Merge pull request #14 from blasferna/feature/name-endpoint
Browse files Browse the repository at this point in the history
Names endpoint
  • Loading branch information
blasferna authored May 22, 2023
2 parents 3cc81b5 + 0b8bf64 commit 7b6ccb7
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 12 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,4 +104,4 @@ docker run --name people -p 80:80 ghcr.io/blasferna/people

## Roadmap
* <s>Base de datos de RUC auto actualizado.</s>
* Base de datos de personas basado en el padrón nacional.
* <s>Base de datos de personas basado en el padrón nacional.</s>
25 changes: 18 additions & 7 deletions app/models.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import sqlalchemy

from .db import metadata, metadata_1
from .utils import int_to_datestr
from .utils import str_to_datestr


rucs = sqlalchemy.Table(
Expand All @@ -16,12 +16,12 @@
)

personas = sqlalchemy.Table(
"cedulas",
"persona",
metadata_1,
sqlalchemy.Column("id", sqlalchemy.Integer, primary_key=True),
sqlalchemy.Column("cedula", sqlalchemy.Integer, primary_key=True),
sqlalchemy.Column("apellidos", sqlalchemy.String),
sqlalchemy.Column("nombres", sqlalchemy.String),
sqlalchemy.Column("fecnac", sqlalchemy.Integer),
sqlalchemy.Column("nacimiento", sqlalchemy.Integer),
)


Expand All @@ -45,19 +45,30 @@ async def get_dict(db, _rucs):
class Persona:
@staticmethod
async def retreive(db, cedula):
return await db.fetch_one(personas.select().where(personas.c.id == cedula))
return await db.fetch_one(personas.select().where(personas.c.cedula == cedula))

@staticmethod
async def get_ruc(db, cedula):
data = await Persona.retreive(db, cedula)
if data is not None:
return {
"ruc": data.id,
"ruc": data.cedula,
"razonsocial": f"{data.apellidos} {data.nombres}",
"tipo": "F",
"categoria": 0,
"dv": None,
"fecNac": int_to_datestr(data.fecnac),
"fecNac": str_to_datestr(data.nacimiento),
"estado": "",
}
return None

@staticmethod
async def filter_by_ids(db, _ids):
_in = ",".join(map(lambda x: f"'{x}'", _ids))
sql = f"SELECT c.cedula, c.apellidos ||' '|| c.nombres as razonsocial FROM persona c WHERE c.cedula IN ({_in})"
return await db.fetch_all(sql)

@staticmethod
async def get_dict(db, _ids):
data = await Persona.filter_by_ids(db, _ids)
return {x.cedula: x for x in data}
24 changes: 20 additions & 4 deletions app/service.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
import csv
from io import BytesIO, StringIO
from typing import Optional
from typing import List, Optional

import pandas as pd
from fastapi import FastAPI, File, Form, HTTPException, UploadFile
from fastapi.responses import HTMLResponse
from pydantic import BaseModel
from starlette.middleware.cors import CORSMiddleware

from . import _set, ips, mimetypes, models
from .db import db, db_1
from .utils import PrettyJSONResponse, get_delimitter, int_to_datestr
from .utils import PrettyJSONResponse, get_delimitter, str_to_datestr

app = FastAPI()
app.add_middleware(
Expand Down Expand Up @@ -63,13 +64,28 @@ async def get_persona(cedula):
"fecNac": None,
}
return {
"cedula": result.id,
"cedula": result.cedula,
"apellidos": result.apellidos,
"nombres": result.nombres,
"fecNac": int_to_datestr(result.fecnac),
"fecNac": str_to_datestr(result.nacimiento),
}


class Document(BaseModel):
id: str


@app.post("/names", response_class=PrettyJSONResponse)
async def set_names(documents: List[Document]):
ids = [d.id for d in documents]
people = await models.Persona.get_dict(db_1, ids)
data = {str(k): v.razonsocial for k, v in people.items()}
ids = list(set(ids) - set(data.keys()))
tax_payers = await models.Ruc.get_dict(db, ids)
data.update({str(k): v.razonsocial for k, v in tax_payers.items()})
return data


@app.post("/validate-ruc", response_class=PrettyJSONResponse)
async def create_upload_file(
file: Optional[UploadFile] = File(None),
Expand Down
4 changes: 4 additions & 0 deletions app/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@ def int_to_datestr(value):
return fecnac.strftime("%d/%m/%Y")


def str_to_datestr(value):
return datetime.strptime(value, "%Y-%m-%d").strftime("%d/%m/%Y")


def encrypt_param(param, variant="ruc"):
encryption_key = base64.b64decode("aCIbjMuVGtwF8nlSKoPydE==")
text = json.dumps({variant: param}).encode()
Expand Down

0 comments on commit 7b6ccb7

Please sign in to comment.