How to use purchaseQuery method in argos

Best JavaScript code snippet using argos

purchase.js

Source:purchase.js Github

copy

Full Screen

1const { gql, ForbiddenError, UserInputError } = require('apollo-server-express');2const { Branch } = require('../models/branch');3const { Products } = require('../models/products');4const { Inventory } = require('../models/inventory');5const { Purchases } = require('../models/purchases');6const { ProductPurchases } = require('../models/productPurchases');7const { IdError } = require('../func/errors');8const typeDefs = gql`9 "Represents a Customer purchase"10 type Purchase{11 PurchaseID: ID12 CustomerFirstName: String13 CustomerLastName: String14 BillingAddress: String15 DeliveryAddress: String16 Paid: Boolean17 TotalPrice: Float18 Dispatched: Boolean19 Branch: Branch20 Products: [OrderItem]21 }22 extend type Query{23 "Get a purchase as a customer"24 getPurchase(25 PurchaseID: ID!, 26 CustomerFirstName: String!, 27 CustomerLastName: String!28 ): Purchase29 "Get the purchase orders per branch"30 getBranchPurchases(31 BranchID: ID!32 Dispatched: Boolean33 ): [Purchase]34 }35 input purchaseDetails{36 "Branch you want to order from"37 Branch: ID!38 CustomerFirstName: String!39 CustomerLastName: String!40 BillingAddress: String!41 DeliveryAddress: String!42 Products: [43 ProductOrder44 ]!45 }46 extend type Mutation{47 "Add an order to the system as a customer"48 createPurchase(49 Details: purchaseDetails!50 ): Purchase51 "Set dispatch of a Purchase"52 dispatchPurchase(53 PurchaseID: ID!54 Dispatched: Boolean!55 ): Purchase56 }57`;58const resolvers = {59 Query: {60 getPurchase: async (parent, arg, ctx, info) => {61 purchaseQuery = await Purchases.query().findById(arg.PurchaseID)62 if (purchaseQuery instanceof Purchases) {63 // Check if details match64 if ((purchaseQuery.CustomerFirstName != arg.CustomerFirstName) || (purchaseQuery.CustomerLastName != arg.CustomerLastName)) {65 throw new UserInputError(66 'Invalid Purchase Details', { invalidArgs: Object.keys(arg) }67 )68 }69 // Building reply70 purchaseProductQuery = await ProductPurchases.query().where('PurchaseID', arg.PurchaseID)71 // Get products to reply with72 replyProducts = []73 for (const item in purchaseProductQuery) {74 inventoryQuery = await Inventory.query().findById(purchaseProductQuery[item].InventoryID)75 replyProducts.push({76 Qty: purchaseProductQuery[item].QTY,77 Product: (await Products.query().findById(inventoryQuery.ProductID))78 })79 }80 // Builds return81 return {82 PurchaseID: purchaseQuery.PurchaseID,83 CustomerFirstName: purchaseQuery.CustomerFirstName,84 CustomerLastName: purchaseQuery.CustomerLastName,85 BillingAddress: purchaseQuery.BillingAddress,86 DeliveryAddress: purchaseQuery.DeliveryAddress,87 Paid: purchaseQuery.Paid,88 TotalPrice: purchaseQuery.TotalPrice,89 Dispatched: purchaseQuery.Dispatched,90 Branch: (await Branch.query().findById(purchaseQuery.BranchID)),91 Products: replyProducts,92 }93 } else {94 throw new IdError(95 'Purchase does not exist', { invalidArgs: Object.keys(arg) }96 )97 }98 },99 getBranchPurchases: async (parent, arg, ctx, info) => {100 if (ctx.auth) {101 // Check if branch exists102 branchQuery = await Branch.query().findById(arg.BranchID)103 if (!(branchQuery instanceof Branch)) {104 throw new IdError(105 'Branch does not exist', { invalidArgs: Object.keys(arg) }106 )107 }108 // Builds query for purchases109 purchaseQuery = Purchases.query().where('BranchID', arg.BranchID)110 if ('Dispatched' in arg) { // If dispatched has been specified in query111 purchaseQuery = purchaseQuery.where('Dispatched', arg.Dispatched)112 }113 purchaseQuery = await purchaseQuery114 reply = [] // Array to hold reply to return115 for (const item in purchaseQuery) {116 purchaseProductQuery = await ProductPurchases.query().where('PurchaseID', purchaseQuery[item].PurchaseID)117 // Get products to reply with118 replyProducts = []119 for (const item in purchaseProductQuery) {120 inventoryQuery = await Inventory.query().findById(purchaseProductQuery[item].InventoryID)121 replyProducts.push({122 Qty: purchaseProductQuery[item].QTY,123 Product: (await Products.query().findById(inventoryQuery.ProductID))124 })125 }126 reply.push({127 PurchaseID: purchaseQuery[item].PurchaseID,128 CustomerFirstName: purchaseQuery[item].CustomerFirstName,129 CustomerLastName: purchaseQuery[item].CustomerLastName,130 BillingAddress: purchaseQuery[item].BillingAddress,131 DeliveryAddress: purchaseQuery[item].DeliveryAddress,132 Paid: purchaseQuery[item].Paid,133 TotalPrice: purchaseQuery[item].TotalPrice,134 Dispatched: purchaseQuery[item].Dispatched,135 Branch: branchQuery, // As this queury is ever for one branch, we can reuse the same branch query136 Products: replyProducts,137 })138 }139 return reply140 } else {141 throw new ForbiddenError(142 'Authentication token is invalid, please log in'143 )144 }145 },146 },147 Mutation: {148 createPurchase: async (parent, arg, ctx, info) => {149 /*150 In Theory IRL you would also have a check in place to make sure that the payment went151 through via service like Stripe (A payment gateway), also if any of the checks failed 152 and a payment was already taken you would initate a refund here as well. 153 We haven't added and logic or fields for said infomation here.154 */155 // Check if branch exists in system156 branchQuery = await Branch.query().findById(arg.Details.Branch)157 if (!(branchQuery instanceof Branch)) {158 throw new IdError(159 'Branch does not exist', { invalidArgs: Object.keys(arg) }160 )161 }162 // Check product and stock of product in branch & tabulate order cost163 purchaseProductStore = [] // Place to store products164 purchaseTotalCost = 0.0 // Stores total cost165 for (const item in arg.Details.Products) {166 productQuery = await Products.query().findById(arg.Details.Products[item].ProductID)167 if (productQuery instanceof Products) {168 // Check Inventory and stock exist for branch169 inventoryQuery = await Inventory.query().where('BranchID', arg.Details.Branch).where('ProductID', productQuery.ProductID)170 if (inventoryQuery.length > 1) {171 throw new Error(172 `Internal Error on Product: ${arg.Details.Products[item].ProductID} Branch: ${arg.Details.Branch}`173 )174 } else if (inventoryQuery.length == 1) {175 // check if inventory of branch is enough to process order176 if (inventoryQuery[0].QTY >= arg.Details.Products[item].Qty) {177 // We add the product to the array if we have enough product to proces the order178 purchaseProductStore.push({179 InventoryID: inventoryQuery[0].InventoryID,180 QTY: arg.Details.Products[item].Qty181 })182 // Add item to total cost of purchase183 purchaseTotalCost = purchaseTotalCost + (productQuery.Price * arg.Details.Products[item].Qty)184 } else {185 throw new UserInputError(186 `Branch does not have enough stock of ${arg.Details.Products[item].ProductID}`, { invalidArgs: Object.keys(arg) }187 )188 }189 } else {190 throw new UserInputError(191 `Product: ${arg.Details.Products[item].ProductID} not stocked by branch`, { invalidArgs: Object.keys(arg) }192 )193 }194 } else {195 throw new IdError(196 `Product: ${arg.Details.Products[item].ProductID} does not exist`, { invalidArgs: Object.keys(arg) }197 )198 }199 }200 // Create the order in a transaction201 try {202 purchaseTrans = await Purchases.transaction(async trx => {203 purchaseInsert = await Purchases.query(trx).insertGraphAndFetch({204 CustomerFirstName: arg.Details.CustomerFirstName,205 CustomerLastName: arg.Details.CustomerLastName,206 BillingAddress: arg.Details.BillingAddress,207 DeliveryAddress: arg.Details.DeliveryAddress,208 Paid: true,209 TotalPrice: purchaseTotalCost,210 BranchID: arg.Details.Branch,211 Dispatched: false,212 // This create the entries in the productPurchases as a nested insert with relationships we specified in DB models213 productPurchases: purchaseProductStore214 })215 });216 } catch (err) {217 console.log(err)218 // Catches error from transaction219 throw new Error("Internal error create Purchase Order")220 }221 if (purchaseInsert instanceof Purchases) {222 // Build reply223 replyProducts = [] //Holds products224 const inventoryTrx = await Inventory.startTransaction();225 try {226 for (const item in purchaseInsert.productPurchases) { //For each product in the purchase order227 // Update Inventory228 inventoryUpdate = await Inventory.query().findById(purchaseInsert.productPurchases[item].InventoryID).decrement("QTY", purchaseInsert.productPurchases[item].QTY)229 // Add product to a hold 230 replyProducts.push({231 Product: (await Products.query().findById((await Inventory.query().findById(purchaseInsert.productPurchases[item].InventoryID)).ProductID)),232 Qty: purchaseInsert.productPurchases[item].QTY233 })234 }235 await inventoryTrx.commit();236 } catch (err) {237 await inventoryTrx.rollback();238 // We roll back manually for purchases and productPurchases instead of using transactions to roll back239 // and objection.js has an issue where it can't update inventory while using nested transactions here.240 await ProductPurchases.query().delete().where('PurchaseID', purchaseInsert.PurchaseID)241 await Purchases.query().deleteById(purchaseInsert.PurchaseID) // remove order from failed order242 throw new Error("Internal error create Purchase Order")243 }244 return {245 PurchaseID: purchaseInsert.PurchaseID,246 CustomerFirstName: purchaseInsert.CustomerFirstName,247 CustomerLastName: purchaseInsert.CustomerLastName,248 BillingAddress: purchaseInsert.BillingAddress,249 DeliveryAddress: purchaseInsert.DeliveryAddress,250 Paid: purchaseInsert.Paid,251 TotalPrice: purchaseInsert.TotalPrice,252 Dispatched: purchaseInsert.Dispatched,253 Branch: branchQuery,254 Products: replyProducts,255 }256 } else {257 throw new Error("Internal error create Purchase Order")258 }259 },260 dispatchPurchase: async (parent, arg, ctx, info) => {261 if (ctx.auth) {262 purchaseQuery = await Purchases.query().findById(arg.PurchaseID)263 if (!(purchaseQuery instanceof Purchases)) {264 throw new IdError(265 'Purchase does not exist', { invalidArgs: Object.keys(arg) }266 )267 }268 purchaseQuery = await Purchases.query().patchAndFetchById(arg.PurchaseID, { Dispatched: arg.Dispatched })269 // Building reply270 purchaseProductQuery = await ProductPurchases.query().where('PurchaseID', arg.PurchaseID)271 // Get products to reply with272 replyProducts = []273 for (const item in purchaseProductQuery) {274 inventoryQuery = await Inventory.query().findById(purchaseProductQuery[item].InventoryID)275 replyProducts.push({276 Qty: purchaseProductQuery[item].QTY,277 Product: (await Products.query().findById(inventoryQuery.ProductID))278 })279 }280 // Builds return281 return {282 PurchaseID: purchaseQuery.PurchaseID,283 CustomerFirstName: purchaseQuery.CustomerFirstName,284 CustomerLastName: purchaseQuery.CustomerLastName,285 BillingAddress: purchaseQuery.BillingAddress,286 DeliveryAddress: purchaseQuery.DeliveryAddress,287 Paid: purchaseQuery.Paid,288 TotalPrice: purchaseQuery.TotalPrice,289 Dispatched: purchaseQuery.Dispatched,290 Branch: (await Branch.query().findById(purchaseQuery.BranchID)),291 Products: replyProducts,292 }293 } else {294 throw new ForbiddenError(295 'Authentication token is invalid, please log in'296 )297 }298 }299 }300}301module.exports = {302 Purchase: typeDefs,303 PurchaseResolvers: resolvers,...

Full Screen

Full Screen

PurchaseController.js

Source:PurchaseController.js Github

copy

Full Screen

1import { Controller, Delete, Get, Post, Put } from "../Infrastructure/expressUtlis";2import { inject } from "inversify";3@Controller("/v1/purchases", "ShouldHaveBranch")4class PurchaseController {5 @inject("PurchaseService")6 /** @type{PurchaseService}*/ purchaseService = undefined;7 @inject("PurchaseQuery")8 /** @type{PurchaseQuery}*/ purchaseQuery = undefined;9 @Get("/")10 getAll(req) {11 return this.purchaseQuery.getAll(req.query);12 }13 @Get("/:id")14 getById(req) {15 return this.purchaseQuery.getById(req.params.id);16 }17 @Get("/max/number")18 maxNumber() {19 const result = this.purchaseQuery.maxNumber();20 return result.max;21 }22 @Post("/")23 create(req) {24 const id = this.purchaseService.create(req.body);25 Utility.delay(500);26 if (req.body.status === 'confirm')27 this.purchaseService.confirm(id);28 return this.purchaseQuery.getById(id);29 }30 @Post("/:id/confirm")31 confirm(req) {32 const id = req.params.id;33 this.purchaseService.confirm(id);34 return this.purchaseQuery.getById(id);35 }36 @Post("/:id/fix")37 fix(req) {38 const id = req.params.id;39 this.purchaseService.fix(id);40 return this.purchaseQuery.getById(id);41 }42 @Put("/:id")43 update(req) {44 const id = req.params.id,45 before = this.purchaseQuery.getById(id);46 this.purchaseService.update(id, req.body);47 if (req.body.status === 'confirmed' && before.status === 'draft')48 this.purchaseService.confirm(id);49 return this.purchaseQuery.getById(id);50 }51 @Delete("/:id")52 remove(req) {53 this.purchaseService.remove(req.params.id);54 }55 @Post("/:id/generate-journal")56 generateJournal(req) {57 const id = req.params.id;58 this.purchaseService.generateJournal(id);59 }60 @Delete("/:id/remove-journal")61 removeJournal(req) {62 const id = req.params.id;63 this.purchaseService.removeJournal(id);64 }65 @Post("/:id/generate-inputs")66 generateInputs(req) {67 const id = req.params.id;68 this.purchaseService.generateInputs(id);69 }70 @Delete("/:id/remove-inputs")71 removeInputs(req) {72 const id = req.params.id;73 this.purchaseService.removeInputs(id);74 }...

Full Screen

Full Screen

helpers.js

Source:helpers.js Github

copy

Full Screen

1import { Plan, Purchase } from "@argos-ci/database/models";2export async function getOrCreatePurchase({ accountId, planId }) {3 const purchase = await Purchase.query().findOne({4 accountId,5 planId,6 endDate: null,7 });8 if (purchase) return purchase;9 return Purchase.query().insertAndFetch({ accountId, planId });10}11export async function getPlanOrThrow(payload) {12 const { id: githubId } = payload.marketplace_purchase.plan;13 const plan = await Plan.query().findOne({ githubId });14 if (!plan) throw new Error(`missing plan with githubId: '${githubId}'`);15 return plan;16}17function getPayloadPlan(payload) {18 return payload.previous_marketplace_purchase19 ? payload.previous_marketplace_purchase.plan20 : payload.marketplace_purchase.plan;21}22export async function getActivePurchaseOrThrow(payload) {23 const { id: planGithubId } = getPayloadPlan(payload);24 const { id: accountGithubId } = payload.marketplace_purchase.account;25 const today = new Date().toISOString();26 const purchaseQuery = Purchase.query()27 .where("startDate", "<=", today)28 .joinRelated("plan")29 .where("plan.githubId", planGithubId)30 .where((query) =>31 query.whereNull("endDate").orWhere("endDate", ">=", today)32 );33 if (payload.marketplace_purchase.account.type === "User") {34 purchaseQuery.joinRelated("user").where("user.githubId", accountGithubId);35 } else {36 purchaseQuery37 .joinRelated("organization")38 .where("organization.githubId", accountGithubId);39 }40 const purchases = await purchaseQuery;41 if (purchases.length === 0) {42 throw new Error(43 `missing purchase with plan’s githubId: '${planGithubId}' and account’s githubId: '${accountGithubId}'`44 );45 }46 if (purchases.length > 1) {47 throw new Error(48 `multiple actives purchases for plan with githubId: '${planGithubId}' and account with githubId: '${accountGithubId}'`49 );50 }51 return purchases[0];...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1define('Mobile/SalesLogix/Views/OpportunityContact/List', [2], function(3) {4 return declare('Mobile.SalesLogix.Views.OpportunityContact.List', [List], {5 itemTemplate: new Simplate([6 '<h3>{%: $.Contact.NameLF %}</h3>',7 '<h4>{%: $.Contact.Title %}</h4>',8 '<h4>{%: $.Role %}</h4>',9 '<h4>{%: $.Contact.AccountName %}</h4>'10 calledText: 'Called ${0}',

Full Screen

Using AI Code Generation

copy

Full Screen

1var argosy = require('argosy')2var argosyPattern = require('argosy-pattern')3var purchaseQuery = pattern({4})5var service = argosy()6service.use(purchaseQuery, function (msg, cb) {7 cb(null, {result: 'success'})8})9service.listen({port: 8000})10var argosy = require('argosy')11var argosyPattern = require('argosy-pattern')12var purchaseQuery = pattern({13})14var service = argosy()15service.use(purchaseQuery, function (msg, cb) {16 cb(null, {result: 'success'})17})18service.listen({port: 8000})19var argosy = require('argosy')20var argosyPattern = require('argosy-pattern')21var purchaseQuery = pattern({22})23var service = argosy()24service.use(purchaseQuery, function (msg, cb) {25 cb(null, {result: 'success'})26})27service.listen({port: 8000})28var argosy = require('argosy')29var argosyPattern = require('argosy-pattern')30var purchaseQuery = pattern({31})32var service = argosy()33service.use(purchaseQuery, function (msg, cb) {34 cb(null, {result: 'success'})35})36service.listen({port: 8000})

Full Screen

Using AI Code Generation

copy

Full Screen

1define('Mobile/SalesLogix/Views/Opportunity/Detail', [2], function(3) {4 return declare('Mobile.SalesLogix.Views.Opportunity.Detail', [Detail, _RightDrawerListMixin], {5 potentialBaseText: 'potential (base)',6 potentialOpportunityText: 'potential (opportunity)',7 potentialMyText: 'potential (my)',

Full Screen

Using AI Code Generation

copy

Full Screen

1define('Mobile/SalesLogix/Views/Report/PurchaseOrderStatus', [2], function(3) {4 return declare('Mobile.SalesLogix.Views.Report.PurchaseOrderStatus', [View], {5 hashTagQueries: {6 },7 hashTagQueriesText: {

Full Screen

Using AI Code Generation

copy

Full Screen

1var argosPurchase = require('./argosPurchase.js');2var argos = new argosPurchase();3var item = "123456789";4argos.purchaseQuery(item, function(data) {5 console.log(data);6});7## argosPurchase.purchaseQuery(item, callback)8## argosPurchase.purchaseQueryAsync(item)

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run argos automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful