reportes.js 2.42 KB
import EC from 'elliptic'
import { tap } from 'ramda'
import { Buffer } from 'buffer/'
import { BACKEND_URL } from '../../constants'
import { ownPrivate } from '../../constants/keys'

const ec = new EC.ec('secp256k1')
const clientPriv = ec.keyFromPrivate(ownPrivate)

export const REPORTE_REQUESTED = 'REPORTE_REQUESTED'
export const reporteRequested = () => ({
  type: REPORTE_REQUESTED
})

export const REPORTE_RECEIVED = 'REPORTE_RECEIVED'
export const reporteReceived = ({ reporte }) => ({
  type: REPORTE_RECEIVED,
  reporte,
})

export const REPORTE_FAILED = 'REPORTE_FAILED'
export const reporteFailed = (error) => ({
  type: REPORTE_FAILED,
  error
})

export const requestReporte = (id, email) => (dispatch) => {
  dispatch(reporteRequested())
  const url = `${BACKEND_URL}/reportes/solicitud/${id}/usuario/${email}/`
  const options = {
    method: 'GET',
    headers: {
      Accept: 'application/json',
    },
  }

  return fetch(url, options)
    .then(response => response.text())
    .then(tap(text => dispatch({ type: 'TEXT_RECEIVED', text })))
    .then(JSON.parse)
    .then(json => dispatch(reporteReceived(json)))
    .catch(error => dispatch(reporteFailed(error)))
}


export const REPORTE_POSTED = 'REPORTE_POSTED'
export const reportePosted = (reporte) => ({
  type: REPORTE_POSTED,
  reporte
})
export const REPORTE_POST_FAILED = 'REPORTE_POST_FAILED'
export const reportePostFailed = () => ({
  type: REPORTE_POST_FAILED
})
export const REPORTE_POST_SUCCESS = 'REPORTE_POST_SUCCESS'
export const reportePostSuccess = (result) => ({
  type: REPORTE_POST_SUCCESS,
  result
})


export const postReporte = (solicitudId, usuario, reporte) => (dispatch) => {
  dispatch(reportePosted(reporte))
  const message = JSON.stringify({ reporte, usuario })
  const firma = new Buffer(clientPriv.sign(message).toDER()).toString('hex')

  const options = {
    method: 'POST',
    body: message,
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
    },
  }


  const url = `${BACKEND_URL}/solicitudes/${solicitudId}/reporte/${firma}`

  const internal = () => fetch(url, options)
    .then(response => response.text())
    .then(tap(text => dispatch({ type: 'TEXT_RECEIVED', text })))
    .then(JSON.parse)
    .then(json => {
      if (json.error) return dispatch(reportePostFailed(json.error))
      return dispatch(reportePostSuccess(json))
    })
    .catch(error => dispatch(reportePostFailed(error)))
  return internal()
}