Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
js
import { createSoapClient, createSoapHeader } from '../lib/amadeus'
import { writeJson, requestXml, requestJson } from '../util/apiJson'
import OrderService from '../service/order'
import { getPayAmount } from '../service/flights/getPayAmount'
import Str from '../db/redis/str'
exports.PNRAddMultiElements = async function (req, res) {
const data = req.body
const searchInput = buildQuery(data)
const validate = validateAge(data)
if (!validate.value) {
return res.json({
status: 0,
errMessge: validate.messge
})
}
const statusCode = req.body.statusCode
let uniqueReference = new Set([...req.body.passengerType]).size
const defaultSession = JSON.parse(req.session.soapSession)
try {
const client = await createSoapClient(createSoapHeader('PNRADD_16_1_1A', defaultSession), true)
var {result :PNRAddMultiElementsResult, session} = await PNR_AddMultiElements(client, searchInput)
var {result : FarePricePNRWithBookingClassResult, session }= await Fare_PricePNRWithBookingClass(client, session || defaultSession)
var {result: TicketCreateTSTFromPricingResult, session} = await Ticket_CreateTSTFromPricing(client, session || defaultSession, uniqueReference)
// console.log(JSON.stringify(session))
// var {result: PNRAddMultiElementsSave, session} = await PNR_AddMultiElements_Save(client, session)
// var {result :CommandCrypticResult, session} = await Command_Cryptic(client, session || defaultSession, req.body.email)
// console.log(JSON.stringify(session))
req.session.soapSession = JSON.stringify(session)
// const client2 = await createSoapClient(client, session)
// await singOut(clienct, session || defaultSession)
// // const closePNRAddMultiElementsResult = await ClosePNRAddMultiElements(client, defaultSession)
// requestJson('TicketCreateTSTFromPricingResult', TicketCreateTSTFromPricingResult)
// requestJson('PNRAddMultiElementsResult', PNRAddMultiElementsResult)
// requestJson('FarePricePNRWithBookingClassResult', FarePricePNRWithBookingClassResult)
//const number = PNRAddMultiElementsSave.pnrHeader[0].reservationInfo.reservation.controlNumber
const payAmount = getPayAmount(FarePricePNRWithBookingClassResult)
console.log(payAmount)
var result = await OrderService.save({
//userId: req.session.user.id,
payAmount: payAmount,
mobile: req.body.mobile,
email: req.body.email,
})
console.log(`/pay?orderId=${result._id}`)
return res.json({
status: 1,
redirect: `/pay?orderId=${result._id}`
})
} catch(e) {
return res.json({
status: 0,
messge: '订票失败',
errMessge: JSON.stringify(e)
})
}
}
function PNR_AddMultiElements (client, searchInput) {
return new Promise((resolve, reject) => {
requestJson('PNR_AddMultiElements', searchInput)
client.PNR_AddMultiElements(searchInput, function(err, result, soapEnvelope, header, request) {
requestXml('PNR_AddMultiElements', request)
requestXml('PNR_AddMultiElements_reply', soapEnvelope)
let session = ''
if (header && header.Session) {
session = {
statusCode: header.Session.attributes.TransactionStatusCode,
SessionId: header.Session.SessionId,
SequenceNumber:header.Session.SequenceNumber,
SecurityToken:header.Session.SecurityToken
}
}
if (err) {
return reject(err)
}
return resolve({
result,
session
})
})
})
}
const test2 = {
"pricingOptionGroup": {
"pricingOptionKey": {
"pricingOptionKey": "RP"
}
}
}
function Fare_PricePNRWithBookingClass(client, defaultSession) {
const len = client.getSoapHeaders().length
client.changeSoapHeader(len - 1, createSoapHeader('TPCBRQ_15_1_1A', defaultSession))
// writeJson('Fare_PricePNRWithBookingClass', test2)
requestJson('Fare_PricePNRWithBookingClass', test2)
return new Promise((resolve, reject) => {
console.log('FarePricePNRWithBooking--->start')
client.Fare_PricePNRWithBookingClass(test2, function(err, result, soapEnvelope, header, request) {
// console.log(JSON.stringify(header.Session))
requestXml('Fare_PricePNRWithBookingClass', request)
requestXml('Fare_PricePNRWithBookingClass_reply', soapEnvelope)
let session = null
if (header && header.Session) {
session = {
statusCode: header.Session.attributes.TransactionStatusCode,
SessionId: header.Session.SessionId,
SequenceNumber:header.Session.SequenceNumber,
SecurityToken:header.Session.SecurityToken
}
}
if (err) {
return reject(err)
}
return resolve({
result,
session
})
})
})
}
exports.singOut = async (req, res) => {
//const len = client.getSoapHeaders().length
// defaultSession.statusCode = 'end'
let defaultSession = JSON.parse(req.session.soapSession)
defaultSession.statusCode = 'End'
const client = await createSoapClient(createSoapHeader('VLSSOQ_04_1_1A', defaultSession), true)
// writeJson('Fare_PricePNRWithBookingClass', test2)
client.Security_SignOut({}, function(err, result, soapEnvelope, header, request) {
// console.log(JSON.stringify(header.Session))
requestXml('Security_SignOut', request)
requestXml('Security_SignOut_reply', soapEnvelope)
if (err) {
return res.json({
err
})
}
return res.json({
result
})
})
}
function PNR_AddMultiElements_Save(client, defaultSession) {
let searchInput = {
pnrActions: {
optionCode: "11"
}
}
const len = client.getSoapHeaders().length
client.changeSoapHeader(len - 1, createSoapHeader('PNRADD_16_1_1A', defaultSession))
return new Promise((resolve, reject) => {
client.PNR_AddMultiElements(searchInput, function(err, result, soapEnvelope, header, request) {
requestXml('PNR_AddMultiElements_Save', request)
requestXml('PNR_AddMultiElements_Save_reply', soapEnvelope)
let session = ''
if (header && header.Session) {
session = {
statusCode: header.Session.attributes.TransactionStatusCode,
SessionId: header.Session.SessionId,
SequenceNumber:header.Session.SequenceNumber,
SecurityToken:header.Session.SecurityToken
}
}
if (err) {
return reject(err)
}
return resolve({
result,
session
})
})
})
}
function Ticket_CreateTSTFromPricing(client, defaultSession, uniqueReference = 1) {
const len = client.getSoapHeaders().length
client.changeSoapHeader(len - 1, createSoapHeader('TAUTCQ_04_1_1A', defaultSession))
let psaList = []
for (let i = 1; i <= uniqueReference; i++) {
psaList.push({
"itemReference": {
"referenceType": "TST",
"uniqueReference": i
}
})
}
//writeJson('Ticket_CreateTSTFromPricing', psaList)
return new Promise((resolve, reject) => {
client.Ticket_CreateTSTFromPricing({
"psaList": psaList
}, function(err, result, soapEnvelope, header, request) {
requestXml('Ticket_CreateTSTFromPricing', request)
requestXml('Ticket_CreateTSTFromPricing_reply', soapEnvelope)
// console.log(JSON.stringify(header.Session))
let session = null
if (header && header.Session) {
session = {
statusCode: header.Session.attributes.TransactionStatusCode,
SessionId: header.Session.SessionId,
SequenceNumber:header.Session.SequenceNumber,
SecurityToken:header.Session.SecurityToken
}
// req.session.soapSession = JSON.stringify(session)
}
if (err) {
return reject(err)
}
return resolve({
result,
session
})
})
})
}
// exports.singOut = async function(req, res) {
// }
exports.retrieve = async function(req, res) {
const client = await createSoapClient(createSoapHeader('PNRRET_16_1_1A'))
const number = req.query.number
try {
const pnr_retrieve_result = await PNR_Retrieve(client, number)
return res.json({
pnr_retrieve_result
})
} catch(e) {
return res.json(e)
}
}
exports.queue = async function(req, res) {
let defaultSession = JSON.parse(req.session.soapSession)
const client = await createSoapClient(createSoapHeader('QUQPCQ_03_1_1A', defaultSession), true)
const number = req.query.number
try {
const {result, session} = await Queue_PlacePNR(client, number)
req.session.soapSession = JSON.stringify(session)
return res.json({
result
})
} catch(e) {
return res.json(e)
}
}
function PNR_Retrieve(client, controlNumber) {
let searchInput = {
"retrievalFacts": {
"retrieve": { "type": "2" },
"reservationOrProfileIdentifier": {
"reservation": {
"controlNumber": controlNumber
}
}
}}
return new Promise((resolve, reject) => {
client.PNR_Retrieve(searchInput, function(err, result, soapEnvelope, header, request) {
requestXml('PNR_Retrieve', request)
requestXml('PNR_Retrieve_reply', soapEnvelope)
if (err) {
console.log(err)
return reject(err)
}
console.log(err)
console.log(result)
return resolve(result)
})
})
}
function Queue_PlacePNR(client, controlNumber) {
let searchInput = {
"placementOption": {
"selectionDetails": { "option": "QEQ" }
},
"targetDetails": {
"targetOffice": {
"sourceType": { "sourceQualifier1": "3" },
"originatorDetails": { "inHouseIdentification1": "YVRC4210G" }
},
"queueNumber": {
"queueDetails": { "number": "99" }
},
"categoryDetails": {
"subQueueInfoDetails": {
"identificationType": "C",
"itemNumber": "1"
}
}
},
"recordLocator": {
"reservation": { "controlNumber": controlNumber }
}
}
return new Promise((resolve, reject) => {
client.Queue_PlacePNR(searchInput, function(err, result, soapEnvelope, header, request) {
requestXml('Queue_PlacePNR', request)
requestXml('Queue_PlacePNR_reply', soapEnvelope)
let session = null
if (header && header.Session) {
session = {
statusCode: header.Session.attributes.TransactionStatusCode,
SessionId: header.Session.SessionId,
SequenceNumber:header.Session.SequenceNumber,
SecurityToken:header.Session.SecurityToken
}
console.log('queue' + JSON.stringify(session))
// req.session.soapSession = JSON.stringify(session)
}
if (err) {
console.log(err)
return reject(err)
}
return resolve({
result,
session
})
})
})
}
function buildQuery(params) {
let firstName = params.firstName
let lastName = params.lastName
let birthDate = params.birthDate
birthDate = birthDate.map((item) => {
let year = item.substring(0, 4)
let month = item.substring(4, 6)
let day = item.substring(6, 8)
return `${day}${month}${year}`
})
let count = params.passengerType.length
let email = params.email
let mobile = params.number + '-' + params.mobile
let adt_ch = params.passengerType.filter((item) => item != 'INF')
let adt_ch_count = adt_ch.length
let inf = params.passengerType.filter((item) => item == 'INF')
let infCount = inf.length
let travellerInfo = []
adt_ch.forEach((item, index) => {
index = parseInt(index, 10)
let obj = {}
let passengerData = []
let passenger = {}
passenger = {
firstName: firstName[index],
type: item,
}
if (infCount > 0) {
passenger.infantIndicator = "3"
}
passengerData.push({
travellerInformation: {
traveller: {
surname: lastName[index]
},
passenger: passenger
},
dateOfBirth: {
dateAndTimeDetails: {
qualifier: "706",
date: birthDate[index]
}
}
})
if (item == 'ADT') {
if (inf[index]) {
infCount--
passengerData.push({
travellerInformation: {
traveller: {
surname: lastName[adt_ch_count + index]
},
passenger: {
firstName: firstName[adt_ch_count + index],
type: 'INF'
}
},
dateOfBirth: {
dateAndTimeDetails: {
qualifier: "706",
date: birthDate[adt_ch_count + index]
}
}
})
}
}
obj.elementManagementPassenger = {
reference: {
qualifier: 'PR',
number: index + 1
},
segmentName: "NM"
}
obj.passengerData = passengerData
travellerInfo.push(obj)
})
//if (infCount)
//todo 婴儿比大人多
return {
pnrActions: {
optionCode: "0"
},
travellerInfo: travellerInfo,
dataElementsMaster: getDataElementsMaster(params)
}
}
exports.index = async (req, res) => {
// if (!req.session.user) {
// return res.redirect(`/auth/?from=${encodeURIComponent(req.originalUrl)}`)
// }
const passenger = req.params.passenger
const formItems = []
let passengers = passenger.split('-')
passengers.forEach((item) => {
let temp = item.split('_')
if (temp[1] > 0) {
for(let i = 0; i < temp[1]; i++) {
let type = temp[0] === 'CH' ? 'CHD' : temp[0]
formItems.push({
type: type
})
}
}
})
const id = JSON.parse(req.session.soapSession).SessionId
const redisStr = Str(id, 2400)
let result = await redisStr.get()
result = JSON.parse(result) || {}
return res.render('form', {
data: {
query: req.query,
formItems: formItems
},
itineraryDetails: result.itineraryDetails,
passengers: result.passengers,
bestPriceInfo: result.bestPriceInfo
})
}
function validateAge(data) {
let passengerType = data.passengerType
let birthDate = data.birthDate
for(let i = 0; i < passengerType.length; i++) {
if (passengerType[i] == 'CHD') {
if (!check(birthDate[i], 12)) {
return {
value: false,
messge: `乘客${i + 1}年龄必须小于12周岁`
}
break;
}
}
if (passengerType[i] == 'INF') {
if (!check(birthDate[i], 2)) {
return {
value: false,
messge: `乘客${i + 1}年龄必须小于2周岁`
}
}
break;
}
}
return {
value: true,
messge: ''
}
function check(date , age) {
const current = new Date()
const year = current.getFullYear()
const month = current.getMonth() + 1
const day = current.getDate()
const birthYear = parseInt(date.substring(0, 4), 10)
const birthMonth = parseInt(date.substring(4, 6), 10)
const birthDate = parseInt(date.substring(6, 8), 10)
if (year - birthYear > age) {
return false
}
if (year - birthYear == age) {
if (month - birthMonth > 0) {
return false
}
if (month - birthMonth == 0 && day - birthDate >= 0) {
return false
}
}
return true
}
}
function getDataElementsMaster(params) {
let email = params.email
let moblie = params.mobile
let temp = {
"marker1": "",
"dataElementsIndiv": [
{
"elementManagementData": {
"segmentName": "AP"
},
"freetextData": {
"freetextDetail": {
"subjectQualifier": "3",
"type": "P02"
},
"longFreetext": email
}
},
{
"elementManagementData": {
"segmentName": "AP"
},
"freetextData": {
"freetextDetail": {
"subjectQualifier": "3",
"type": "3"
},
"longFreetext": moblie
}
},
// {
// "elementManagementData": {
// "segmentName": "TK"
// },
// "ticketElement": {
// "ticket": {
// "indicator": "OK"
// }
// }
// },
{
"elementManagementData": {
"segmentName": "RF"
},
"freetextData": {
"freetextDetail": {
"subjectQualifier": "3",
"type": "P22"
},
"longFreetext": "online"
}
}
]
}
let passport = buildPassport(params)
passport.forEach(e => {
temp.dataElementsIndiv.push(e)
})
return temp
}
function buildPassport(params) {
let {sex, countryCode, birthDate, passengerType, expired, lastName, firstName, passport} = params
let arr = []
passport.forEach((item, index) => {
arr.push(
{"elementManagementData": {
"segmentName": "SSR"
},
"serviceRequest": {
"ssr": {
"type": "DOCS",
"status": "HK",
"quantity": "1",
"companyId": "YY",
"freetext": getText(countryCode[index], passport[index], expired[index], sex[index], firstName[index], lastName[index], birthDate[index], passengerType[index])
}
},
"referenceForDataElement": {
"reference":{
"qualifier": "PT",
"number": (index + 2).toString() //有毒
}
}
})
})
return arr
function getText(
countryCode,
passport,
expired,
sex,
firstName,
lastName,
birthDate,
passengerType
) {
if (passengerType === 'INF') {
sex = sex + 'I'
}
return `P-${countryCode}-${passport}-${countryCode}-${getTime(birthDate)}-${sex}-${getTime(expired)}-${lastName}-${firstName}`
}
function getTime(str) {
let map = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
let day = str.substring(6, 8)
let month = map[parseInt(str.substring(4, 6), 10) - 1]
let year = str.substring(2, 4)
return `${day}${month}${year}`
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.